Business logic in Enums?

浪尽此生 提交于 2020-01-02 02:35:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!