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.
If there are many conditional branches by if statements, using Enum makes it very easy to read.
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
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