Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Business logic in Enums?

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

}
like image 416
sma Avatar asked Jul 30 '10 17:07

sma


4 Answers

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?

like image 124
abyx Avatar answered Sep 18 '22 22:09

abyx


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;
 }
}
like image 20
james Avatar answered Sep 22 '22 22:09

james


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.

like image 20
b_erb Avatar answered Sep 20 '22 22:09

b_erb


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.

like image 42
tpdi Avatar answered Sep 18 '22 22:09

tpdi