首页 > 编程语言 > 详细

Effective Java 31 Use instance fields instead of ordinals

时间:2014-03-26 08:38:04      阅读:579      评论:0      收藏:0      [点我收藏+]

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.

   

Effective Java 31 Use instance fields instead of ordinals,布布扣,bubuko.com

Effective Java 31 Use instance fields instead of ordinals

原文:http://www.cnblogs.com/haokaibo/p/3623946.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!