zoukankan      html  css  js  c++  java
  • Effective Java 31 Use instance fields instead of ordinals

    Principle

    Never derive a value associated with an enum from its ordinal; store it in an instance field instead.

    Bad practice Demo

    // Abuse of ordinal to derive an associated value - DON'T DO THIS

    public enum Ensemble {

    SOLO, DUET, TRIO, QUARTET, QUINTET,

    SEXTET, SEPTET, OCTET, NONET, DECTET;

    public int numberOfMusicians() {return ordinal() + 1;}

    }

       

    // The right way

    public enum Ensemble {

    SOLO(1), DUET(2), TRIO(3), QUARTET(4), QUINTET(5),

    SEXTET(6), SEPTET(7), OCTET(8), DOUBLE_QUARTET(8),

    NONET(9), DECTET(10), TRIPLE_QUARTET(12);

    private final int numberOfMusicians;

    Ensemble(int size) { this.numberOfMusicians = size; }

    public int numberOfMusicians() { return numberOfMusicians; }

    }

    Disadvantages

    1. If the constants are reordered, the numberOfMusicians method will break.
    2. If you want to add a second enum constant associated with an int value that you've already used, you're out of luck.
    3. You can't add a constant for an int value without adding constants for all intervening int values.

    Summary

    The Enum specification has this to say about ordinal: "Most programmers will have no use for this method. It is designed for use by general-purpose enum based data structures such as EnumSet and EnumMap." Unless you are writing such a data structure, you are best off avoiding the ordinal method entirely.

       

    作者:小郝
    出处:http://www.cnblogs.com/haokaibo/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    小熊派接入华为IOT
    VS2022 C++ 支持热重载
    Go入门笔记43HGet查询
    Go入门笔记45在WSL2上测试串口编程
    Yarn全新安装
    EdgexGo2.0学习19 no secty依然提示让输入token
    Ubuntu20.04安装Emqx
    shell脚本中echo显示内容带颜色
    EdgexGo2.0学习20 编译EdgeX Go UI
    EdgexGo2.0学习18 消息总线目标
  • 原文地址:https://www.cnblogs.com/haokaibo/p/use-instance-fields-instead-of-ordinals.html
Copyright © 2011-2022 走看看