Effective Java 30 Use Enums instead of int constants
Enumerated type is a type whose legal values consist of a fixed set of constants, such as the seasons of the year.
// The int enum pattern - severely deficient!
public static final int APPLE_FUJI = 0;
public static final int APPLE_PIPPIN = 1;
public static final int APPLE_GRANNY_SMITH = 2;
public static final int ORANGE_NAVEL = 0;
public static final int ORANGE_TEMPLE = 1;
public static final int ORANGE_BLOOD = 2;
The basic idea behind Java's enum types is simple: they are classes that export one instance for each enumeration constant via a public static final field.
To associate data with enum constants, declare instance fields and write a constructor that takes the data and stores it in the fields.
Note
- unless you have a compelling reason to expose an enum method to its clients, declare it private or, if need be, package-private (Item 13).
- If an enum is generally useful, it should be a top-level class; if its use is tied to
a specific top-level class, it should be a member class of that top-level class (Item22)
- Compiler will reminds you that abstract methods in an enum type must be overridden with concrete methods in all of its constants.
/**
* Demo for enum type use abstract methods for Compile time checking on added enum type.
*/
package com.effectivejava.EnumAnnotations;
import java.util.HashMap;
import java.util.Map;
/**
* @author Kaibo
*
*/
public enum Operation {
PLUS("+") {
public double apply(double x, double y) {
return x + y;
}
},
MINUS("-") {
public double apply(double x, double y) {
return x - y;
}
},
TIMES("*") {
public double apply(double x, double y) {
return x * y;
}
},
DIVIDE("/") {
public double apply(double x, double y) {
return x / y;
}
};
private final String symbol;
Operation(String symbol) {
this.symbol = symbol;
}
@Override
public String toString() {
return symbol;
}
public abstract double apply(double x, double y);
}
Note
Enum types have an automatically generated valueOf(String)method that translates a constant's name into the constant itself. If you override the toString method in an enum type, consider writing a fromString method to translate the custom string representation back to the corresponding enum.
// Implementing a fromString method on an enum type
private static final Map<String, Operation> stringToEnum = new HashMap<String, Operation>();
static { // Initialize map from constant name to enum constant
for (Operation op : values())
stringToEnum.put(op.toString(), op);
}
// Returns Operation for string, or null if string is invalid
public static Operation fromString(String symbol) {
return stringToEnum.get(symbol);
}
4. Use nested enum for the strategy enum pattern. Using constant-specific methods.
/**
* Demo for the "Using Nested enum for enum strategy pattern."
*/
package com.effectivejava.EnumAnnotations;
/**
* @author Kaibo
*
*/
// The strategy enum pattern
enum PayrollDay {
MONDAY(PayType.WEEKDAY), TUESDAY(PayType.WEEKDAY), WEDNESDAY(
PayType.WEEKDAY), THURSDAY(PayType.WEEKDAY), FRIDAY(PayType.WEEKDAY), SATURDAY(
PayType.WEEKEND), SUNDAY(PayType.WEEKEND);
private final PayType payType;
PayrollDay(PayType payType) {
this.payType = payType;
}
double pay(double hoursWorked, double payRate) {
return payType.pay(hoursWorked, payRate);
}
// The strategy enum type
private enum PayType {
// constant-specific methods
WEEKDAY {
double overtimePay(double hours, double payRate) {
return hours <= HOURS_PER_SHIFT ? 0 : (hours - HOURS_PER_SHIFT)
* payRate / 2;
}
},
WEEKEND {
double overtimePay(double hours, double payRate) {
return hours * payRate / 2;
}
};
private static final int HOURS_PER_SHIFT = 8;
abstract double overtimePay(double hrs, double payRate);
double pay(double hoursWorked, double payRate) {
double basePay = hoursWorked * payRate;
return basePay + overtimePay(hoursWorked, payRate);
}
}
}
5. Switches on enums are good for augmenting external enum types with constant-specific behavior.
// Switch on an enum to simulate a missing method
public static Operation inverse(Operation op) {
switch(op) {
case PLUS: return Operation.MINUS;
case MINUS: return Operation.PLUS;
case TIMES: return Operation.DIVIDE;
case DIVIDE: return Operation.TIMES;
default: throw new AssertionError("Unknown op: " + op);
}
}
Summary
Enums are far more readable, safer, and more powerful than int constants. Enums can benefit from associating data with each constant sand providing methods whose behavior is affected by this data. When enums benefit from assocating multiple behaviors with a single method perfer constant-specific methods to enums that switch on their own values. Consider the strategy enum pattern if multiple enum constants share common behaviors.
Effective Java 30 Use Enums instead of int constants的更多相关文章
- effective java——30使用enum
1, 枚举太阳系八大行星 package com.enum30.www; public enum Planet {//枚举太阳系八大行星 MERCURY(3.302e+23,2.439e6), VEN ...
- Effective Java Index
Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st langu ...
- 《Effective Java》读书笔记 - 6.枚举和注解
Chapter 6 Enums and Annotations Item 30: Use enums instead of int constants Enum类型无非也是个普通的class,所以你可 ...
- Effective Java 第三版——30. 优先使用泛型方法
Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...
- Effective Java之避免创建不必要的对象
Effective Java中有很多值得注意的技巧,今天我刚开始看这本书,看到这一章的时候,我发现自己以前并没有理解什么是不必要的对象,所以拿出来跟大家探讨一下,避免以后犯不必要的错误! 首先书中对不 ...
- [Effective Java]第八章 通用程序设计
声明:原创作品,转载时请注明文章来自SAP师太技术博客( 博/客/园www.cnblogs.com):www.cnblogs.com/jiangzhengjun,并以超链接形式标明文章原始出处,否则将 ...
- 对于所有对象都通用方法的解读(Effective Java 第二章)
这篇博文主要介绍覆盖Object中的方法要注意的事项以及Comparable.compareTo()方法. 一.谨慎覆盖equals()方法 其实平时很少要用到覆盖equals方法的情况,没有什么特殊 ...
- Effective Java通俗理解(持续更新)
这篇博客是Java经典书籍<Effective Java(第二版)>的读书笔记,此书共有78条关于编写高质量Java代码的建议,我会试着逐一对其进行更为通俗易懂地讲解,故此篇博客的更新大约 ...
- Effective Java通俗理解(下)
Effective Java通俗理解(上) 第31条:用实例域代替序数 枚举类型有一个ordinal方法,它范围该常量的序数从0开始,不建议使用这个方法,因为这不能很好地对枚举进行维护,正确应该是利用 ...
随机推荐
- VueJs2.0建议学习路线
最近VueJs确实火了一把,自从Vue2.0发布后,Vue就成了前端领域的热门话题,github也突破了三万的star,那么对于新手来说,如何高效快速的学习Vue2.0呢. 既然大家会看这篇文章,那么 ...
- Android学习笔记之性能优化SparseArray
PS:终于考完试了.来一发.微机原理充满了危机.不过好在数据库89分,还是非常欣慰的. 学习内容: 1.Android中SparseArray的使用.. 昨天研究完横向二级菜单,发现其中使用了Sp ...
- C#加密类
var es= EncryptSugar.GetInstance(); string word = "abc"; var wordEncrypt = es.Encrypto(wor ...
- Brute Force --- UVA 10167: Birthday Cake
Problem G. Birthday Cake Problem's Link:http://uva.onlinejudge.org/index.php?option=com_onlinejudg ...
- 客户关系管理系统(CRM)的开发过程中使用到的开发工具总结
开发<客户关系管理系统(CRM)>软件过程,也就是一个标准的Winform程序的开发过程,我们可以通过这个典型的软件开发过程来了解目前的开发思路.开发理念,以及一些必要的高效率手段.本篇随 ...
- Fluent Nhibernate and Stored Procedures
sql:存储过程 DROP TABLE Department GO CREATE TABLE Department ( Id INT IDENTITY(1,1) PRIMARY KEY, DepNam ...
- HDU 5694---BD String
HDU 5694 Problem Description 众所周知,度度熊喜欢的字符只有两个:B和D.今天,它发明了一种用B和D组成字符串的规则:S(1)=BS(2)=BBDS(3)=BBDBBD ...
- 泛函编程(6)-数据结构-List基础
List是一种最普通的泛函数据结构,比较直观,有良好的示范基础.List就像一个管子,里面可以装载一长条任何类型的东西.如需要对管子里的东西进行处理,则必须在管子内按直线顺序一个一个的来,这符合泛函编 ...
- [PHP] java读取PHP接口数据
和安卓是一个道理,读取json数据 PHP文件: <?php class Test{ //日志路径 const LOG_PATH="E:\phpServer\Apache\logs\\ ...
- ztree addNode editName removeNode
1.ztree api中完全拥有以上操作的相关解释,及简单Demo. 2.主要是要学会将单独的效果组合起来使用. 2.1 如: 添加完新的Node节点之后,怎么立即进入新节点的编辑状态来修改名称(或 ...