Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

java - Should enum objects be stateless?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...