I am trying to model some states in my file generation program,
at one point :
- I want to check the current status of the data
- if data is valid I want to continue
- otherwise I want to inform the user of the reason why I cannot continue
A psudocode would be like:
if(isValid()){
writeFile()
} else {
switch(getReason()){
case FAIL1: doSomething1();
break;
case FAIL2: doSomething2();
break;
case FAIL3: doSomething3();
break;
}
}
Not sure if an approach like this is correct, would like your advice/opinions. Where: in total there are less than 10 error states, and only one error state is applicable at a given time.
I would create a enum
for your Reason
and put all the specific information of your reason there. Then you can parametrize the doSomething
method with the specific information from the reason. Sounds to me like this could be a String
. With this approach it is much easier to extend your code.
The code could look like :
if(isValid()){
writeFile()
} else { Reason reason = getReason();
doSomething(reason.getMessage());
}
With your enum Reason
enum Reason {
REASON1("message1"), REASON2("message2")/* ... */;
private String message;
private Reason(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
The idea from garnulf is going in a good direction; but it is still not a really good solution in OO terms.
Thing is: you already mentioned the key concept that is important here: state, as in state machine.
You really want to use polymorphism here:
abstract class Reason() {
String getMessage() { // just to show that there might be some shared code
abstract void doSomething();
Then you would have different subclasses for your Reason class; and in the end, your client code boils down to:
getReason().doSomething();
Because each reason knows whats to do about itself! Of course, that might require some further thinking - depending on the fact what those different error reasons are really about.
The key point is: you really want to avoid any kind of switching over enum or string values. If at all, you hide such switches inside of factories, that return some abstract class / interface thingy (where the factory creates a concrete subclass/implementation for you).