[Java] Reduce if statements with Enum

Introduction

It is often said that 80% of the time spent reading the source code when touching a program during maintenance and development. Therefore, you should always be aware of source code that is highly readable and maintainable, but when it comes to business systems, there are inevitably many conditional branches depending on the type of contract, the type of business partner, and so on. I feel that it tends to be. So, I learned that there is a method using Enum as one of the methods to reduce the if statement, so I will post it so as not to forget it.

Benefits of reducing if statements

If there are many conditional branches by if statements, using Enum makes it very easy to read.

Concrete example

SampleEnum.java


public enum SampleEnum {

	kind1(new Kind1()),
	kind2(new Kind2()),
	kind3(new Kind3()),
	kind4(new Kind4());

	SuperKind kind;

	private SampleEnum(SuperKind kind) {
		this.kind = kind;
	}

	public void execute(Object obj) {
		kind.execute(obj);
	}
}

First, prepare an Enum. Next, for each property, describe the processing class you want to execute and define the constructor. Finally, define the execution method of the processing class you want to execute.

The implementation of Enum itself is completed in these 3 steps. After that, when a type is added, just add a property and describe the processing class you want to execute for each type.

Kind1.java


public class Kind1 implements SuperKind {

	public void execute(Object obj){

		if(!(obj instanceof String)) {
			System.out.println("Please specify a character string as an argument");
		}
		System.out.println("In Kind1 class" + obj);
	}
}

The processing class you want to execute. Here, I will simply output a statement that shows that the class was executed to the console. SuperKind is an interface. Since the contents only define the ʻexecute` method here, I will omit it.

Main.java


public class Main {

	public static void main(String[] args) {

		SampleEnum test1 = SampleEnum.valueOf("kind1");
		SampleEnum test2 = SampleEnum.valueOf("kind2");
		SampleEnum test3 = SampleEnum.valueOf("kind3");
		SampleEnum test4 = SampleEnum.valueOf("kind4");

		String string = "Enum test";

		test1.execute(string);
		test2.execute(string);
		test3.execute(string);
		test4.execute(string);
	}
}

This is the main class. The result of executing here is as follows.

Testing Enums in Kind1 classes
Testing Enums in Kind2 classes
Testing Enums in Kind3 classes
Testing Enums in Kind4 classes

Finally

By implementing this kind of implementation, I felt that the range of utilization is wide, such as reducing if statement judgments in the Factory class and reducing if statement judgments such as which business logic process to call.

Recommended Posts

[Java] Reduce if statements with Enum
Java if and switch statements
[Java] Branch enum with switch statement
[Java] enum
Install java with Homebrew
Change seats with java
Install Java with Ansible
Comfortable download with JAVA
Ruby Learning # 17 If Statements
Switch java with direnv
Enum reverse map Java
Quickly implement a singleton with an enum in Java
Output true with if (a == 1 && a == 2 && a == 3) in Java (Invisible Identifier)
Download Java with Ansible
Let's scrape with Java! !!
[Java] About enum type
Build Java with Wercker
Endian conversion with JAVA
Easy BDD with (Java) Spectrum?
Use Lambda Layers with Java
Java multi-project creation with Gradle
Getting Started with Java Collection
Java Config with Spring MVC
Basic Authentication with Java 11 HttpClient
Let's experiment with Java inlining
Run batch with docker-compose with Java batch
[Template] MySQL connection with Java
Rewrite Java try-catch with Optional
Install Java 7 with Homebrew (cask)
[Java] JSON communication with jackson
Java to play with Function
Manipulating List with java8StreamAPI :: reduce
Enable Java EE with NetBeans 9
[Java] JavaConfig with Static InnerClass
About Java variable declaration statements
Let's operate Excel with Java! !!
Version control Java with SDKMAN
RSA encryption / decryption with java 8
Paging PDF with Java + PDFBox.jar
[Java] Content acquisition with HttpCliient
Java version control with jenv
Troubleshooting with Java Flight Recorder
Enum Strategy pattern in Java
Connect to DB with Java
Connect to MySQL 8 with Java
Error when playing with java
Java study memo 2 with Progate
[Java] Summary of for statements
Getting Started with Java Basics
[Ruby] problem with if statement
Reproduce Java enum in C #
Reduce verbose code with Lombok
Seasonal display with Java switch
Use SpatiaLite with Java / JDBC
Study Java with Progate Note 1
Compare Java 8 Optional with Swift
HTML parsing with JAVA (scraping)
Run Java VM with WebAssembly
Java while and for statements
Screen transition with swing, java
Java unit tests with Mockito