An interesting question: how to handle variables in the same way for all objects of the class and does not change at run time, and at the same time it is allowed to configure between executions. Since the first two prerequisites dictate that the variable must be static and finite (for example, a constant), the third does not fit in, which means that there will not be a beautiful way to achieve all three (reflection is required, or you need either a static or final constraint).
Since there is no correct solution to the modeling method now, I think that the wisest thing would be to take a step back and rethink the placement of the variable: does this logic need to be saved in the enumeration itself? What changed when the value of the constant, the enumeration itself, or something else changed? In what cases should this constant change the value?
In your example, it may be that different countries have different threshold values for what is considered an adult, or that the threshold value changes, then maybe a small service that determines which of PersonType a Person is the right way.
@Service public class PersonTypeService { @Value("${threshold.for.adulthood}") private int thresholdForAdulthood; public PersonType determinePersonType(final Person person) { if (person.getAge() >= thresholdForAdulthood) { return PersonType.ADULT; } return PersonType.CHILD; } }
In general, I would like to allow enumerations to respond only to “what” and leave “how” and “why” for domain classes and services. In this example, all enumerations should know the values that it provides to a person, why it should provide a certain value or how it is determined is not included in the enumeration.
source share