When I used Java for work before, there was a process that was difficult to understand, so I refactored it.
It was like this before the refactoring.
private void doProcess() {
A a = initial();
if (!chkfnc1(a)) {
throw new XXXException(x1);
}
if (!chkfnc2(a)) {
throw new XXXException(x2);
}
if (!chkfnc3(a)) {
throw new XXXException(x3);
}
execute(a); //Execution processing after check
}
private boolean chkfnc1(a) {}
private boolean chkfnc2(a) {}
private boolean chkfnc3(a) {}
Instance acquisition-> Instance legitimacy check (n times)-> Execution processing It is a flow.
Suppose chkfncN
flows in a sequence and has an order dependency.
If this situation continues, if the check requirement increases by one, it will be difficult to determine when the chkfncN
function will be checked, and it will be disgusting.
Enum When you hear the Enum,
--Correspondence with numerical values can be taken --Cases can be separated by switch-case
And so on. I think the biggest feature I think is that the order is guaranteed.
Also part of the Haskell typeclass Enum definition
class Enum a where
succ :: a -> a --Function showing the following values
pred :: a -> a --Function showing the previous value
Is defined.
Also in Java Enum
for (DaysOfWeekEnum day : DaysOfWeekEnum.values()) {
}
It can be processed in order like this
Java Enums ** Functions can be defined inside Enums ** https://qiita.com/KeithYokoma/items/9681b130ea132cfad64d
Based on the above, you can do this.
public enum MyChecker {
CHK1 {
@Override
public boolean chkfnc(A a) {}
@Override
public String erroMsg(){}
},
CHK2 {
@Override
public boolean chkfnc(A a) {}
@Override
public String erroMsg(){}
};
CHK3 {
@Override
public boolean chkfnc(A a) {}
@Override
public String erroMsg(){}
};
public abstract boolean chkfnc(A a);
public abstract String errorMsg;
}
Using the previous example
private void doProcess() {
A a = initial();
for (MyChecker val : MyChecker.values()) {
if (!val.chefnc) {
throw new XXXException(val.erroMsg);
}
}
}
And the inside of doProcess was refreshed and the view became better. Also, since the order is guaranteed by using Enum, it is almost as if you want to guarantee the operation.
There weren't many articles that used Enum valies in Java like this, so I wrote it. The situation where it can be used is limited, but if you recognize that the enum guarantees the order, I think that other applications will also work.
Recommended Posts