简体   繁体   English

枚举中的业务逻辑?

[英]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;
 }

}

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?如果这允许您编写更简单的代码和SOLID代码,为什么不呢?

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.作为隐式扩展Enum类,它们甚至可以实现接口。

I'd only consider using Enums if it fits to the enumerated values, ie the buisness logic is tightly coupled with the instances.如果 Enums 适合枚举值,我只会考虑使用它,即业务逻辑与实例紧密耦合。

由于您示例中的逻辑与枚举值的(名称)紧密相关,我想不出更好的地方来放置它。

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.如果您的业务逻辑可以表示为一组静态值,那么 Enum 是一个不错的选择。 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.不要忘记,在 Java 中你可以创建包含多个值的Enum 类,如果你有一堆相关的值,这很有用。

For simple buisness logic as above it is ok, but i ran into a problem when it comes to the point of extending enums which is not possible.对于上面的简单业务逻辑,它是可以的,但是当涉及到扩展枚举时我遇到了一个问题,这是不可能的。 For example we stored additional data within the enums and later wanted to get a reverse mapping of the values for many different enums which would be easy with standard classes but is impossible with enums (without code duplication).例如,我们在枚举中存储了额外的数据,后来想要获得许多不同枚举的值的反向映射,这对于标准类来说很容易,但在枚举中是不可能的(没有代码重复)。
Standard classes can do the same (except of using in switch statements) and are more flexible and reliable.标准类可以做同样的事情(除了在 switch 语句中使用)并且更加灵活和可靠。 If the enumeration may get more complicated logic better use classes otherwise using enum with simple logic is quite fine in my opinion如果枚举可能会得到更复杂的逻辑,最好使用类,否则在我看来使用具有简单逻辑的枚举非常好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM