How to provide implementations for enum values in Java?

user1298426 :

I have enum class with values which are suppose to grow by time and I want users who add new enum values also provide the impementation somewhere. But I am not sure how to force them to provide impementation as impementation will be in some other class. For e.g.

public enum DayType {
    SUNDAY,
    MONDAY;
}

Referred in a class

class X{
DateType dateType;
..
}

And used in some other class

if (x.getDateType().equals(DayType.SUNDAY)) {
...
}else if(x.getDateType().equals(DayType.MONDAY)){
..
}

So if someone adds DateType then he should be forced to add impementation in above if-else logic as well. Preferably by adding functional interfaces if possible?

I can not force impementation in enum class as the impementation has spring dependencies.

GhostCat salutes Monica C. :

The real answer is: don't do this.

If you have some "type", and you know that this "type" will see new incarnations over time, that need different behavior, then the answer is to use an abstract class and polymorphism.

It doesn't matter if you use if/else chains, or switch statements: the idea that you have something like:

if (someObject.getSomething() == whatever) { then do this } else { that }

is bad practice!

If at all, you should use such a switch statement within a factory to return different subclass instances, to then call "common" methods on such objects.

Your current approach is A) externalizing knowledge about internal state and B) also enforcing dependencies in multiple ways.

This is how spaghetti code starts! Better step back and think about more OOP ways of solving this!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=84892&siteId=1