Is it considered good practice to put any type of business logic in Enums? Not really intense logic, but more of like convenience utility methods. For example:
public enum OrderStatus {
OPEN, OPEN_WITH_RESTRICTIONS, OPEN_TEMPORARY, CLOSED;
public static boolean isOpenStatus(OrderStatus sts) {
return sts == OPEN || sts == OPEN_WITH_RESTRICTIONS || sts == OPEN_TEMPORARY;
}
}
IMHO, this enables you to put relevant information right where it's likely to be used and searched for. There's no reason for enums not to be actual classes with actual responsibility.
If this allows you to write simpler code, and SOLID code, why not?
Yes, i think this is a good idea. However, i think it can be implemented much more cleanly using instance methods:
public enum OrderStatus {
OPEN, OPEN_WITH_RESTRICTIONS, OPEN_TEMPORARY,
CLOSED {
@Override isOpen() { return false; }
};
public boolean isOpen()
{
return true;
}
}
I often use Enums for singleton instances. Thus they contain almost only business logic. Being classes that implcitly extend Enum
they can even implement interfaces.
I'd only consider using Enums if it fits to the enumerated values, i.e. the buisness logic is tightly coupled with the instances.
Since the logic in your example is so closely tied to the (names of the) enumerated values, I can't think of a better place to put it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With