问题
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;
}
}
回答1:
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?
回答2:
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;
}
}
回答3:
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.
回答4:
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.
回答5:
Enums primary job is the enforce a specific set of values with programmer friendly names. If you business logic can be expressed as a static set of values then Enums are a good way to go. Don't forget that in Java you can create Enum classes which hold more than one value, useful if you have a bunch of related values.
来源:https://stackoverflow.com/questions/3373847/business-logic-in-enums