話の両端を聞いた。1 つの見解は、特別な状態を示すために数値変数の特別な値を使用することは設計上の欠陥であるというものです。しかし、私はいつもこの行動に遭遇します。
例として、値 255 が情報の欠如を示すバイト符号なし整数があります。
これは悪い習慣ですか?もしそうなら、どのような例外的なケースでそれが許可/奨励されていますか?
話の両端を聞いた。1 つの見解は、特別な状態を示すために数値変数の特別な値を使用することは設計上の欠陥であるというものです。しかし、私はいつもこの行動に遭遇します。
例として、値 255 が情報の欠如を示すバイト符号なし整数があります。
これは悪い習慣ですか?もしそうなら、どのような例外的なケースでそれが許可/奨励されていますか?
That depends very much on the situation; as always, strive to write things the simplest, easiest to understand way. Hopefully exceptional situation handling doesn't clutter up the code for the normal case (that's the idea behind exceptions, but they create their own mess...).
Be careful when selecting the value to be used for exceptional cases. For example, C/Unix conventions use this quite a bit, but make sure to use "impossible" values. So, getchar(3)
returns a character code as an int
, but returns a non-character EOF
for end of file. Similarly, read(2)
returns the number of characters read (could be 0 if nothing to be read), or -1 on error.
これは、余裕があることを前提とすると、絶対に悪い習慣ではありません。つまり、表現可能な整数の範囲には、実際の状況で使用する必要がない十分な追加の値があります。
たとえば、255を含むすべての範囲の符号なしバイトが必要な場合、255に「不明」の新しい意味を与えることは問題になります。「実際の」データに255が使用されていない場合は、任意の意味を自由に割り当てることができます。
ただし、問題は、コード全体で特別な名前を割り当てずに特別な番号を使用していることです。例えば、
if (myByte == 255) {
// Process the situation when the value is unknown
}
間違いなく悪いです。すべての特別な定数に名前を付け、コード全体で次の名前のみを使用する必要があります。
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.
}