`
leonzhx
  • 浏览: 793479 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Item 30: Use enums instead of int constants

阅读更多

1.  Programs that use the int enum pattern are brittle. Because int enums are compile-time constants, they are compiled into the clients that use them. If the int associated with an enum constant is changed, its clients must be recompiled. If they aren’t, they will still run, but their behavior will be undefined.

 

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. Enum types are effectively final, by virtue of having no accessible constructors.

 

3.  enum types let you add arbitrary methods and fields and implement arbitrary interfaces. They provide high-quality implementations of all the Object methods, they implement Comparable and Serializable, and their serialized form is designed to withstand most changes to the enum type.

 

4.  There is a better way to associate a different behavior with each enum constant: declare an abstract method in the enum type, and override it with a concrete method for each constant in a constant-specific class body. Such methods are knows as constant-specific method implementations:

// Enum type with constant-specific method implementations
public enum Operation {
    PLUS { double apply(double x, double y){return x + y;} },
    MINUS { double apply(double x, double y){return x - y;} },
    TIMES { double apply(double x, double y){return x * y;} },
    DIVIDE { double apply(double x, double y){return x / y;} };
    abstract double apply(double x, double y);
}

 

Abstract methods in an enum type must be overridden with concrete methods in all of its constants.

 

5.  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.

 

6.  Enum constructors aren’t permitted to access the enum’s static fields, except for compile-time constant fields. This restriction is necessary because these static fields have not yet been initialized when the constructors run.

 

7.  Consider the strategy enum pattern if multiple enum constants share common behaviors:

// 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 {
        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);
        }
    }
}

 

分享到:
评论

相关推荐

    Effective Java 3rd edition(Effective Java第三版英文原版)附第二版

    Item 34: Use enums instead of int constants Item 35: Use instance fields instead of ordinals Item 36: Use EnumSet instead of bit fields Item 37: Use EnumMap instead of ordinal indexing Item 38: ...

    effectice_java第二版 英文

    10. **条目10:优先考虑使用枚举而非int常量(Use Enums Instead of Int Constants)** 枚举提供了类型安全,可以方便地添加方法和实现接口,比使用整数常量更易管理和维护。 11. **条目11:使用泛型(Generics)*...

    Ruby-TranslateEnum简单零依赖Rails的Enums翻译gem

    在Ruby on Rails开发中,枚举(Enums)是一种常见的数据类型,用于定义有限的、命名的整数集合。这些枚举常用于模型属性,提供更易读、更强大的代码。"Ruby-TranslateEnum"是一个针对Rails应用的开源gem,旨在为...

    Enums.NET:Enums.NET是一种高性能的类型安全的.NET枚举实用程序库

    v4.0的变化删除了v3.0中不推荐使用的NonGenericEnums , NonGenericFlagEnums , UnsafeEnums和UnsafeFlagEnums类,同时还删除了所有其他不推荐使用的方法,以缩小库的大小。 建议从2.x及以下版本升级到3.x,然后...

    Google C++ Style Guide(Google C++编程规范)高清PDF

    All of a project's header files should be listed as descentants of the project's source directory without use of UNIX directory shortcuts . (the current directory) or .. (the parent directory). For...

    Effective C++, 3rd Edition

    - **Item2: 优先使用consts、enums和inline而非#define** - 使用现代C++的特性(如const变量、枚举类型和内联函数)代替传统的宏定义可以提高代码的可读性和安全性。 - **Item3: 尽可能使用const** - const关键字...

    C++出错提示英汉对照表

    #### Enumeration constants syntax error (枚举常数语法错误) - **解释**:枚举类型的成员定义中出现语法问题。 - **示示例**: ```cpp enum Color { RED, GREEN, BLUE }; // 正确 enum Color { RED, GREEN, ...

    Struct And Enums结构和枚举

    Point p2 = { X: 30, Y: 40 }; // 直接初始化 ``` 3. **结构的复制与比较**: 值类型的复制是浅复制,意味着复制的是内存中的副本,改变副本不会影响原始对象。比较结构使用`==`和`!=`运算符,比较的是成员的值。 ...

    reconstant:在编程语言之间共享常量定义,并使常量再次常量

    constants : - name : SOME_CONSTANT value : " this is a constant string " - name : OTHER_CONSTANT value : 42 enums : - name : SomeEnum values : - A - B - C - name : OtherEnum

    Easy collider editor 2.5

    By using primitive colliders instead of mesh colliders, rigidbodies can be added to gameobjects to allow for physics interactions. This tool allows for easy addition of multiple 3D primitive ...

    effective_java_new:Effective_java_new

    5. **使用枚举代替常量类(Use Enums Instead of Integers for Constants)**:枚举类型提供了类型安全,可以避免硬编码的整数值,同时提供方法和字段,增强了可读性和可维护性。 6. **避免使用 finalize()**:Java...

    CSharp 3.0 With the .NET Framework 3.5 Unleashed(english)

    - **Enums**: Enumerations, or enums, are a way to define named constants for a set of related values. They are commonly used to represent a group of options or states. ### 7. Debugging Applications ...

    enums_COD_

    Enums IDa for COD Warfare

Global site tag (gtag.js) - Google Analytics