Java 使用枚举与布尔值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4337942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using enum vs Boolean?
提问by TheJediCowboy
This may initially seem generic, but in fact, I am actually making the decision on which I need to use.
这最初可能看起来很一般,但实际上,我实际上正在决定我需要使用哪个。
What I am currently working on involves Employment Applications, those in which will need to be marked at some point Activeor Inactive. When an application is submitted, it will default to Active. For certain reasons, it might later be set to Inactive. It can only be one of these and never null(In case this changes anything).
我目前正在处理的工作涉及就业申请,这些申请需要在某些时候标记为Active或Inactive。提交申请时,它将默认为Active。出于某些原因,以后可能会将其设置为Inactive。它只能是其中之一并且永远不会为空(以防发生任何变化)。
I am using this with Java + Hibernate + PostgresSQL, in case this also makes any difference. My first instinct is to use Booleanas my solution so that it truly acts as a flag, but I have coworkers who have suggested using enumsor intsas more of a status rather then a flag.
我将它与Java + Hibernate + PostgresSQL 一起使用,以防万一这也有什么不同。我的第一直觉是使用Boolean作为我的解决方案,以便它真正充当标志,但我的同事建议使用枚举或整数作为状态而不是标志。
I have solved problems such as this using all of the above solutions, and they all seem somewhat transparent to eachother.
我已经使用上述所有解决方案解决了诸如此类的问题,而且它们似乎对彼此都有些透明。
Is there one way that is better for this situation?
有没有一种方法更适合这种情况?
采纳答案by Buhake Sindi
It totally depends on your requirement/specification. If you only want to record the status as active or inactive, the best way is to use boolean
.
这完全取决于您的要求/规格。如果只想将状态记录为活动或非活动,最好的方法是使用boolean
.
But if in the future, you will have a status such as,
但是,如果将来,您将拥有诸如,
- ACTIVE
- INACTIVE
- SUSPENDED
- BLOCKED
- 积极的
- 不活动
- 暂停
- 已屏蔽
Enums is perfect for you. In your case, for now, a boolean is sufficient. Don't try overcomplicate things too early, you'll lose focus in your design & development of your system.
枚举非常适合您。就您而言,目前,布尔值就足够了。不要过早尝试使事情变得过于复杂,否则您将失去对系统设计和开发的关注。
回答by aksarben
If true/false are the only possibilities, boolean makes more sense than enum (less overhead). Recommendation: Use the Boolean class instead of the boolean primitive, so you can detect the "unknown/undefined" state as well as true/false.
如果真/假是唯一的可能性,布尔值比枚举更有意义(更少的开销)。建议:使用 Boolean 类而不是 boolean 原语,这样您就可以检测“未知/未定义”状态以及真/假。
回答by Patrick Kafka
If you might ever have a need for more statuses other than Active and Inactive then you would want to use and enum or int status flag? That makes your code more flexible for future statuses.
如果您可能需要除 Active 和 Inactive 之外的更多状态,那么您会想要使用 enum 或 int 状态标志吗?这使您的代码对于未来的状态更加灵活。
回答by Karl Knechtel
Definitely don't use an int. Using an enum is future-proofing; you have to decide for yourself what's more readable, and whether YAGNIapplies. Be aware that boolean
is not the same thing as Boolean
; Boolean
is a class name, and as such, variables of type Boolean
can be null; whereas boolean
is a primitive.
绝对不要使用int。使用枚举是面向未来的;你必须自己决定什么更具可读性,以及YAGNI是否适用。请注意,boolean
这与Boolean
; Boolean
是一个类名,因此类型变量Boolean
可以为空;而boolean
是一个原语。
回答by AlwaysAProgrammer
In your case having a boolean value should suffice. Since the requirement is 'IsActive' and the immediate answer can be either true or false. Having an enum is ok but IMO, a boolean is right suited
在你的情况下,有一个布尔值就足够了。由于要求是“IsActive”,因此立即回答可以为真,也可以为假。有一个枚举是可以的,但 IMO,一个布尔值是正确的
回答by ColinD
Even ignoring the possibility of adding more status types in the future (which is certainly one good argument for an enum
), I think an enum
is absolutely the right way to go. You are not modelling a boolean condition, you are modelling the status of an application. Think about it: the application's status is not trueor false, it's active or inactive! A status enum
will represent this in the most natural way.
即使忽略将来添加更多状态类型的可能性(这当然是 an 的一个很好的论据enum
),我认为 anenum
绝对是正确的方法。您不是在为布尔条件建模,而是在为应用程序的状态建模。想一想:应用程序的状态不是true或false,它是活动的还是非活动的!状态enum
将以最自然的方式表示这一点。
You also get a lot of built in advantages from using an enum, such as having a text description of each status tied directly to it, so you don't have to do things like
您还可以通过使用枚举获得许多内置优势,例如将每个状态的文本描述直接关联到它,因此您不必做类似的事情
String text = application.isActive() ? "Active" : "Inactive";
You can just do
你可以做
String text = application.getStatus().toString();
Additionally, you can tie specific behavior directly to each status with abstract methods that each enum implements differently, associate specific data with each status, etc.
此外,您可以使用每个枚举以不同方式实现的抽象方法将特定行为直接绑定到每个状态,将特定数据与每个状态相关联,等等。
You can also easily allow a boolean isActive
check that is based on the status... you can't easily do that the other way around if you just store a boolean
.
您还可以轻松地允许isActive
基于状态的布尔检查……如果您只存储boolean
.
public boolean isActive() {
return status == Status.ACTIVE;
}
And the fact that null
shouldn't be a valid status is irrelevant... just ensure that any classes that store the status (say, your EmploymentApplication
class or whatever) throw a NullPointerException
if anyone tries to set a null
status on it.
并且null
不应该是有效状态的事实是无关紧要的......只要确保任何存储状态的EmploymentApplication
类(例如,您的类或其他类)NullPointerException
在有人试图对其设置null
状态时抛出一个。
回答by ArtOfWarfare
Is it not possible to do both?
两者都不能做吗?
enum Status {
ACTIVATE(true), INACTIVE(false);
private final boolean value;
Status(boolean value) {
this.value = value;
}
boolean getValue() {
return this.value;
}
}
Does this not get you the best of both worlds? It lets you use a boolean with the names ACTIVE and INACTIVE, rather than true and false?
这难道不是让你两全其美吗?它允许您使用名称为 ACTIVE 和 INACTIVE 的布尔值,而不是 true 和 false?
回答by madhawaOnline
I think it is better to use Enum instead of Boolean. In Effective java it prefers two-element enums to booleans. It has also suggested the following advantages of it. Code is easier to read ? Code is easier to read ? Code is easier to write (especially with IDE) ? Less need to consult documentation ? Smaller probability of error ? Much better for API evolution
我认为最好使用 Enum 而不是 Boolean。在 Effective java 中,它更喜欢二元素枚举而不是布尔值。它还提出了它的以下优点。代码更容易阅读?代码更容易阅读?代码更容易编写(尤其是使用 IDE)?更少需要查阅文档?出错概率更小?更适合 API 演化
Please refer the below link to get more details. https://www.cs.umd.edu/class/fall2009/cmsc132H/slides/still-effective.pdf
请参阅以下链接以获取更多详细信息。 https://www.cs.umd.edu/class/fall2009/cmsc132H/slides/still-effective.pdf
回答by Basil Bourque
Booleans are rare in business & industry
布尔值在商业和工业中很少见
In my experience building custom apps for business, an apparent duality such as "Female/Male" or "On/Off" nearly always evolve or morph into multiple values.
根据我为企业构建自定义应用程序的经验,诸如“女性/男性”或“开/关”之类的明显二元性几乎总是会演变或演变为多个值。
- "Female/Male" becomes "Unknown/Female/Male"
- "On/Off" becomes "On/WarmingUp/CoolingDown/Off"
- “女/男”变为“未知/女/男”
- “开/关”变成“开/预热/冷却/关闭”
Business rules are often not fully known early-on, or change over time.
业务规则通常在早期并不完全了解,或者随着时间的推移而变化。
Like many of my colleagues, I learned the hard way to never define such values as booleans. Changing from boolean to multiple values later is quite expensive and risky.
像我的许多同事一样,我学会了从不将此类值定义为布尔值的艰难方法。稍后从布尔值更改为多个值非常昂贵且有风险。
Java enums
Java 枚举
Enums have other benefits over a boolean.
枚举比布尔值还有其他好处。
Java enums are flexible & powerful
Java 枚举灵活而强大
The Enum
facility in Java is much more flexible, powerful, and useful than enums in most other languages. See Oracle Tutorial.
Enum
Java 中的工具比大多数其他语言中的枚举更加灵活、强大和有用。请参阅Oracle 教程。
Within your enum definition you can house representations of the values for presentation to the user and for storage in databases or files. This makes a handy one-stop-shop for a programmer to read all about this enum and how it used in your app.
在您的枚举定义中,您可以容纳值的表示形式,以便向用户展示和存储在数据库或文件中。这为程序员提供了一个方便的一站式商店,可以阅读有关此枚举的所有信息以及它在您的应用程序中的使用方式。
Here is a complete example. This one class shows what values we use in the user-interface and what values we persist.
这是一个完整的例子。这一类显示了我们在用户界面中使用的值以及我们保留的值。
package com.basilbourque.example;
public enum Status {
ACTIVE( "Active" , "active" ),
INACTIVE( "Inactive" , "inactive" ),
UNKNOWN( "Unknown" , "unknown" );
private String displayName, codeName;
Status ( String displayName , String codeName ) {
this.displayName = displayName;
this.codeName = codeName;
}
public String getDisplayName () { return this.displayName; } // Or even add a `Locale` argument to support localization.
public String getCodeName () { return this.codeName; }
// To find a `Status` enum object matching input retrieved from a database.
static public Status ofCodeName ( String codeName ) {
// Loop each of the enum objects to find a match.
for ( Status s : Status.values() ) {
if ( s.getCodeName().equals( codeName ) ) { return s; }
}
throw new IllegalArgumentException( "No such Status code name as: " + codeName );
}
@Override
public String toString() { return "app-status-" + this.getCodeName() ; }
}
Translating persisted values back to enum object
将持久值转换回枚举对象
Notice the static method that can return a Status
object matching a persisted value retrieved from a database:
请注意可以返回Status
与从数据库中检索到的持久值匹配的对象的静态方法:
Status s = Status.ofCodeName( myResultSet.getString( "code" ) ) ;
Flexible sets/maps
灵活的集合/地图
In Java, enums have their own implementation of Set
and Map
that are highly optimized both in terms of very little memory used and very fast execution.
在 Java 中,枚举有自己的实现,Set
并且Map
在使用的内存非常少和执行速度非常快方面都进行了高度优化。
Set< Status > auditApprovedStatuses = EnumSet.of( Status.ACTIVE , Status.INACTIVE ) ;
Set< Status > auditAlertStatuses = EnumSet.of( Status.UNKNOWN ) ;
…
if( auditAlertStatuses.contains( application.getStatus() ) ) {
this.alertAuditor( application ) ;
}
Notice how easy to update these set definitions if your definition of application-status changes.
请注意,如果您对应用程序状态的定义发生变化,更新这些集合定义是多么容易。
Informative toString
value
信息toString
价值
Whereas a boolean appears as true
or false
as a string, in your enum you can override toString
to generate a much more informative value such as app-status-inactive
.
虽然布尔值显示为字符串true
或false
字符串,但在您的枚举中,您可以覆盖toString
以生成信息量更大的值,例如app-status-inactive
.
Such values may be quite useful when logging, tracing, or debugging.
这些值在记录、跟踪或调试时可能非常有用。