I have a few Java enums as such
public enum Aggregation
{
MORTGAGE( \"Mortgage\" ),
POOLS( \"Pools\" ),
PORTFOLIO( \"Portfolio\" );
private
Favor composition over inheritance and programming for the sake of interfaces. Since Enums are classes (not regular, but still - classes) you can create some field containing shared logic, let the enum implement you interface and delegate implementation to this field.
Relevant code snippets:
Shared interface
public interface MyInterface {
void someMethod();
}
Logic implementation
public class MyInterfaceImpl implements MyInterface {
public void someMethod() {
System.out.println("Do smth...");
}
}
First enum
public enum EnumA implements MyInterface {
;
private MyInterface impl = new MyInterfaceImpl();
public void someMethod() {
impl.someMethod();
}
}
Second enum
public enum EnumB implements MyInterface {
;
private MyInterface impl = new MyInterfaceImpl();
public void someMethod() {
impl.someMethod();
}
}
Please do note that EnumA
and EnumB
are not really code duplication, since that is plain delegation (valid, in my opinion). Also please note that everything is nicely glued together by using interface.