quaylar
quaylar

Reputation: 2635

Java-Design: Enum state?

I realize (having read other posts on SO as well) that it's bad design (or better said in my case it would also not make sense) to add state to enum constants.

Nevertheless i am finding myself right now in a situation where i need something similar to this. An application i am writing uses error-constants (enum), which i am using to indicate errors by adding them to a Map<Error, ErrorInfo> (note that these are not application-errors, but "Errors" that are part of the application). Well - i now realize that i actually also need to indicate an ErrorLevel of INFO, WARN, FATAL for these. Since the ErrorLevel of an Error depends on the context it occurred in, i cannot statically assign ErrorLevel's to the Error-enums, in other words, an Error.E1 can be of ErrorLevel.WARN one time, but might be ErrorLevel.FATAL another time.

I am thinking about how i could best incorporate this ErrorLevel in my design, but all i have come up with up to now is, to introduce a new class which simply wraps an Error and an ErrorLevel and use it within the Map instead of Error.

Since Errors and their severity seem to me something that must be quite common, i am sure that there are smarter way to do this, so i would greatly appreciate your ideas on how to design this better.

--qu

Upvotes: 2

Views: 833

Answers (2)

Jonathan
Jonathan

Reputation: 2766

If I understood your problem correctly, putting a transient state to the enum won't do the trick. As there is only one instance per enum-type by changing the error-level you would not only change it for the current error you are assessing but for all errors of the same type in the application.

You wrote, the errorlevel is depending on the context and at the same time that ErrorInfo describes the context of the occurance of the error. If you can calculate the errorlevel based on the errortype and the context, I would suggest some static method

public static ErrorLevel getLevel(Error, ErrorInfo) {
  //..
}

Upvotes: 2

Andreas Dolk
Andreas Dolk

Reputation: 114807

I do not agree in total that it is always bad design adding mutable state to enums. Enums are like Singletons and whenever it makes sense to use a stateful singleton in your application, you can do the same with enum. Like with singletons we just have to keep in mind, that a state change has a pretty global effect.

For sure, stateful enums won't help in your case, because you want context specific error levels.

As an alternative, consider using a simple multimap:

Map<Context, Map<Error, ErrorLevel>> errors;

The idea is to store multiple maps for different contexts. So for a known context (I quickly invented a type...) you get the context specific parameter map.

Upvotes: 1

Related Questions