用幻数(1)或全局常量检查列表大小?(Check list size with a magic number (1) or global constant?)

编程入门 行业动态 更新时间:2024-10-25 14:30:28
用幻数(1)或全局常量检查列表大小?(Check list size with a magic number (1) or global constant?)

我正在与同事讨论以下代码:

private static final byte ONE_ELEMENT = 1; private boolean isListSizeEqualsOne(List<MyClass> myList) { return myList.size() == ONE_ELEMENT; }

我认为,这种代码承认会减少关于幻数的警告,但不必要地同时增加混乱。 我建议内联全局变量:

private boolean isListSizeEqualsOne(List<MyClass> myList) { return myList.size() == 1; }

有没有关于这个例子的文献?

I'm in an argument with a co-worker about the following code:

private static final byte ONE_ELEMENT = 1; private boolean isListSizeEqualsOne(List<MyClass> myList) { return myList.size() == ONE_ELEMENT; }

I'm arguing that this kind of code admittedly reduces a warning about a magic number but unnecessarily increases clutter at the same time. I'm suggesting to inline the global variable instead:

private boolean isListSizeEqualsOne(List<MyClass> myList) { return myList.size() == 1; }

Is there any literature for / against this example?

最满意答案

我认为代码的问题已经在方法本身中了。 就像注释一样,方法名称不应该表明代码的作用,而是为什么 。 换句话说,它应该表明它提供的功能,而不是它的实现。

也就是说,它应该表达这种方法在系统中扮演的角色。 因此,不是使用名称isListSizeEqualsOne ,而是使用指示“为什么”的名称。 例如, resultIsUnique或errorReturned (如果您使用的API是一个包含单个元素的列表指示错误)。

然后常数的命名如下:

resultIsUnique :常量UNIQUE_RESULT_COUNT=1 errorReturned :常量ERROR_RESULT_COUNT=1

最后,我不认为为内联常量启用警告是一个好主意。 对数字使用命名常量只有合理

该值必须在任何地方相同(例如文件格式的幻数), 或者 值需要明显的名称,例如数学常量

如果你需要那些含义很明显的常量(例如通过比较大小为零来检查一个空列表),那么我认为一个简单的内联值是完全正确的。

I think the problem with the code is already in the method itself. Just like comments, a method name should not indicate what the code does, but why. In other words, it should indicate the functionality it provides, not its implementation.

That is, it should express the role that this method plays in the system. so instead of the name isListSizeEqualsOne, use a name that indicates the "why". For example resultIsUnique, or errorReturned (if you use an API where a list with a single element indicates an error).

Then the naming of the constant follows:

resultIsUnique: constant UNIQUE_RESULT_COUNT=1 errorReturned: constant ERROR_RESULT_COUNT=1

Finally, I don't think it is a good idea to enable warnings for inline constants. Using named constants for numbers only makes sense if either

the value must be the same everywhere (e.g. magic number for a file format), or the value needs a name to be obvious, such as mathematical constants

If you need constants whose meaning is obvious (such as checking for an empty list by comparing the size to zero), then I think a plain inline value is perfectly ok.

更多推荐

本文发布于:2023-07-26 02:41:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1269917.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:常量   全局   大小   列表   Check

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!