Which approach would be better between the following two?
I have chosen enums since, in the typical case subtype polymorphishm is the best approach; also this is a typical approach when writing a simple factory method.
public class SomeClass {
public SomeEnum returnAType(String someString) {
//implementation bellow
}
private boolean method1() {
//...
}
private boolean method2() {
//...
}
private boolean method3() {
//...
}
}
The first implementation of returnATypeMethod; this is faster since it does not call method2 and method3 (and possibly more) if method1 is valid.
public SomeEnum returnAType(String someString) {
if(method1(someString)) {
SomeEnum.ENUM1.doSomething();
return SomeEnum.ENUM1;
}
if(method2(someString)) {
SomeEnum.ENUM2.doSomething();
return SomeEnum.ENUM2;
}
if(method3(someString)) {
SomeEnum.ENUM3.doSomething();
return SomeEnum.ENUM3;
}
SomeEnum.DEFAULT_ENUM.doSomething();
return SomeEnum.DEFAULT_ENUM;
}
The second implementation of returnATypeMethod; this is more clear and no code duplicate:
public SomeEnum returnAType(String someString) {
SomeEnum enumType = SomeEnum.DEFAULT_ENUM;
if(method1(someString)) {
enumType = SomeEnum.ENUM1;
}
if(method2(someString)) {
enumType = SomeEnum.ENUM2; }
}
if(method3(someString)) {
enumType = SomeEnum.ENUM3;
}
enumType.doSomething();
return enumType;
}
I would be tempted to use
}