在特殊情况下使用保留变量值是一种不好的做法吗? [英] Is it a bad practice to use reserved variable values for special cases?

查看:23
本文介绍了在特殊情况下使用保留变量值是一种不好的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说过这个故事的两个结局.一种观点认为,使用数字变量的特殊值来表示特殊状态是一种设计缺陷.但是,我经常遇到这种行为.

I have heard both ends of the story. One view is that using a special value of a numeric variable to indicate special state is a design flaw. However, I meet this behavior all the time.

一个例子是一个字节无符号整数,其中值 255 表示缺少信息.

An example would be a byte unsigned integer, where the value 255 indicates lack of information.

这是一种不好的做法吗?如果是,在哪些特殊情况下是允许/鼓励的?

Is this a bad practice? If so, in what exceptional cases it is allowed/encouraged?

推荐答案

这绝对不是一个不好的做法,假设你负担得起,即可表示整数的范围有足够的额外值,您永远不需要在现实生活中使用.

This is absolutely not a bad practice, assuming that you can afford it, i.e. the range of representable integers has enough extra values that you never need to use in real-life situations.

例如,如果您需要完整范围的无符号字节,包括 255,那么为 255 赋予未知"的新含义将是一个问题.如果 255 从未用于真实"数据,那么您可以随意赋予它任何您想要的含义.

For example, if you needed a full range of unsigned bytes, including the 255, then giving 255 a new meaning of "unknown" would be a problem. If 255 is never used for the "real" data, then you are free to assign it any meaning that you would like.

然而,错误的是在整个代码中使用了特殊的数字,而没有为它们分配一个特殊的名称.例如,

What's wrong, however, is using special numbers throughout the code without assigning them a special name. For example,

if (myByte == 255) {
    // Process the situation when the value is unknown
}

毫无疑问是坏的.您应该命名所有特殊常量,并在整个代码中仅使用这些名称:

is unquestionably bad. You should name all your special constants, and use only these names throughout your code:

if (myByte == UNKNOWN_VALUE) {
    // You can skip the comment about processing an unknown value:
    // the name of the constant tells your readers what's going on.
}

这篇关于在特殊情况下使用保留变量值是一种不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆