So, I here was my previous code:
public enum eDay {
eMON,
eTUE,
eWED
}
eDay day = eMON;
switch( day ) {
case eMON:
//load class 1
break;
case eTUE:
//load class 2
break;
case eWED:
//load class 3
break;
}
Reading around, the OO way to do things is to have an enum that overrides a method rather than using a switch statement, such as:
enum eDay {
eMON {
@Override
public void loadClass() {
//load class 1
}
},
eTUE {
@Override
public void loadClass() {
//load class 2
}
};
public abstract void loadClass();
}
void aMethodSomewhere(final eDay e) {
e.loadClass();
}
While the concept of using polymorphism makes sense to me, rather than using a switch statement, what happens in the situation where the enum is used in different classes to do different things? For example, different classes behave differently according to a limited set of options, defined in the enum ( so not always performing loadClass() ).
Should you define different methods according to the different classes? To my mind, that would increase object coupling greatly.
I would really like to do OO properly, so good advice is much appreciated.
Many thanks.
In general, you want to use polymorphism to avoid
if()
blocks and for behavior reuse, you should favor composition.In your case, I understand that there is some dynamic behavior involved in your design and, therefore, the use of enums could not be advisable.
Enums have a lot of advantages: they're final, static and every instance is a singleton by default. Whenever I need a static singleton that is up when the JVM starts, I favor enums over classes.
In this case, if you have some dynamic behavior going on, you could write a class with some static final properties that are an instance of the same class. With proper visibility modifiers for constructors or factory methods, the external API of the class could be the same as with the enum.
In order to inject the dynamic behavior, you could use Strategy design pattern or even inject a Function (if you're using Java8) as a parameter in the class' constructor.
If your behavior is not dynamic, you could continue using enums, but you could inject the behavior in their constructor to improve readability: