Monday 26 May 2014

Java tricks. Extending enumerations

Goal: 1) to have a type that represents a static set of constant values, so we can benefit from the compile-time check… or in less words, an Enum type, 2) to be able to extend the pre-defined set of values in the client class that extends a base client class… ideally, NewEnum extends BaseEnum.
Unfortunately, it’s not possible to extend enum type in Java, because of the enum nature: enum is an ordinal type, which makes it possible to be used in switch operator.
So the solution I’ve come up with is to introduce an interface. Let’s see how it works with the following example.
public interface State {
    String name(); // will be implemeted by java.lang.Enum class
}public class Entity {
    private State state = ObjectState.CREATED;
    public void setState(State state) { this.state = state; }
    public State getState() { return state; }
    public enum ObjectState implements State {
        CREATED, ACTIVE, DELETED
    }
}
public class Order extends Entity {
    public enum OrderState implements State {
        ACCEPTED, DELIVERED, CANCELLED
    }
}
public class EntityController {
    public void create(Entity entity) { entity.setState(ObjectState.CREATED); }
    public void delete(Entity entity) { entity.setState(ObjectState.DELETED); }
    public void activate(Entity entity) { entity.setState(ObjectState.ACTIVE); }
}
public class OrderController extends EntityController {
    public void accept(Order order) { order.setState(OrderState.ACCEPTED); }
    public void deliver(Order order) { order.setState(OrderState.DELIVERED); }
    public void cancel(Order order) { order.setState(OrderState.CANCELLED); }
}
Pros: both goals achieved, namely we’ve got static constant values and we are not limited by a pre-defined set of values, we can extend it for future use cases.
Cons: there’s no real extensibility of base enum, so we should be aware of the existing base enum before ‘extending’ it, so we don’t repeat values from it.

No comments:

Post a Comment