Lets say I have realy long switch/case
block, which makes my inner me say 'it does not look good'
switch (option) {
case ERROR:
doSomething();
break;
case SUCCESS:
doSomething();
break;
case WARNING:
doSomething();
break;
case SUCCESS_WITH_WARNING:
doSomething();
break;
case SUCCESS_WITH_ERROR:
doSomething();
break;
case FATAL:
doSomething();
break;
case INFO:
doSomething();
break;
default:
break;
}
Remamber that we can always add more enums etc. Let's say that method in case
block are printing something to the console. So they are just void
.
I was trying to use visitor, but it seems there are better choices, so with visitor it looks like that:
public enum ImportOption {
SUCCEEDED{
@Override
public void accept(ImportOptionVisitor visitor) {
visitor.visitSucceededImport();
}
},
FAILED{
@Override
public void accept(ImportOptionVisitor visitor) {
visitor.visitFailedImport();
}
},
WARNING{
@Override
public void accept(ImportOptionVisitor visitor) {
visitor.visitWarningImport();
}
};
public abstract void accept(ImportOption.ImportOptionVisitor visitor);
public interface ImportOptionVisitor{
void visitSucceededImport();
void visitFailedImport();
void visitWarningImport();
}
And than in place of switch we got:
option.accept(new ImportOptionVisitor() {
@Override
public void visitSucceededImport() {
// TODO Auto-generated method stub
}
@Override
public void visitFailedImport() {
// TODO Auto-generated method stub
}
@Override
public void visitWarningImport() {
// TODO Auto-generated method stub
}
But it seems exaggerated even for long switches like 100 enums. I read a little about command pattern. But I am not sure how to implement it. Any ideas how to make a replace switch
and make code a little more readable etc?
Aucun commentaire:
Enregistrer un commentaire