Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

As by design an enum constant in java is a singleton, and for sake of concurrent usage I normally create stateless enum instances and use method parameters to inject the data as needed.

Example:

Currently I am creating a REST service which has Operations (implemented as an enum using a variant of the strategy pattern).

public enum Operation {

  DO_THIS() {
    public Result doSomething(Object theData) {
    }
  } ,
  // Other Operations go here
  ;

  public abstract Result doSomething(Object theData);

}

Now I want to collect data about how often an operation has been called and how often it succeeded and the like.

I could save the state externally when using the enum instance but it rather seems that the state should be saved in the Operation as the operation should contain it's own state.

Now my general question is:

Is a stateful enum instance (besides from concurrency issues) a bad design?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
161 views
Welcome To Ask or Share your Answers For Others

1 Answer

I think it violates the Principle of Least Astonishment.

People expect the common usage of enums as they were originally designed - as constants or tokens, and not as general purpose classes with state.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...