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
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