views:

114

answers:

5

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

}
+11  A: 

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?

abyx
Now if only we could do that over here in C#-land :(
BlueRaja - Danny Pflughoeft
"There's no reason for enums not to be actual classes with actual responsibility.": In Java, enums **are** actual classes ;)
Brian S
@Brian - is what I'm saying, they should be treated as such (as opposed to C's enums)
abyx
I was hoping that would be the answer. I had heard before that Enums should just serve as holding constants and be essentially dumb objects.
+2  A: 

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.

tpdi
+3  A: 

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.

PartlyCloudy
+1 for writing singletons using enums, more people should use that method.
Zenzen
-1 for writing singletons.
Tom Hawtin - tackline
@Tom Hawtin there's nothing wrong with singletons in general. They can and are used poorly, but that doesn't mean it's a bad design pattern.
Brian S
Singletons can be abused like anything else, but are definitely useful when used correctly. Even Josh Bloch suggests using enums for that purpose, b/c then you don't have to worry about serialization and other commonly missed details with hand rolled singleton classes
Java Drinker
+1  A: 

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.

Michael Shopsin
+4  A: 

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;
 }
}
james
@james; good answer, and welcome to the site!
Dean J