我在类成员初始化中使用幻数:
private static final RangeMap<Integer, String> MY_MAP = new ImmutableRangeMap.Builder<Integer, String>()
.put(Range.closed(10, 31), "random string 1")
.put(Range.closed(32, 36), "random string 2")
.put(Range.closed(37, 39), "random string 3")
.put(Range.closed(40, 78), "random string 4")
// lot of similar lines here
.build();
代码非常清晰易读,但 checkstyle 给了我们大量关于 Checkstyle 的警告。我可以抑制警告,但我正在寻找更好的 Java 解决方案。
一种方法是使用常量,代码如下所示:
private static final Integer RANDOM_STRING_1_START = 10;
private static final Integer RANDOM_STRING_2_START = 32;
private static final Integer RANDOM_STRING_3_START = 37;
private static final Integer RANDOM_STRING_4_START = 40;
private static final Integer RANDOM_STRING_1_END = 31;
private static final Integer RANDOM_STRING_2_END = 36;
private static final Integer RANDOM_STRING_3_END = 39;
private static final Integer RANDOM_STRING_4_END = 78;
private static final RangeMap<Integer, String> MY_MAP = new ImmutableRangeMap.Builder<Integer, String>()
.put(Range.closed(RANDOM_STRING_1_START, RANDOM_STRING_1_END), "random string 1")
.put(Range.closed(RANDOM_STRING_2_START, RANDOM_STRING_2_END), "random string 2")
.put(Range.closed(RANDOM_STRING_3_START, RANDOM_STRING_3_END), "random string 3")
.put(Range.closed(RANDOM_STRING_4_START, RANDOM_STRING_4_END), "random string 4")
// lot of similar lines here
.build();
而且我认为它不像以前那样美观和可读。此外,打字时更容易出错。
任何想法如何定义值表而不抱怨 checkstyle?我不想压制警告,我想找到“Java方式”。