Should I always/ever/never initialize object fields to default values?

前端 未结 17 2154
臣服心动
臣服心动 2020-12-09 14:49

Code styling question here.

I looked at this question which asks if the .NET CLR will really always initialize field values. (The answer is yes.) But it

17条回答
  •  孤城傲影
    2020-12-09 15:49

    If a field will often have new values stored into it without regard for what was there previously, and if it should behave as though a zero was stored there initially but there's nothing "special" about zero, then the value should be stored explicitly.

    If the field represents a count or total which will never have a non-zero value written to it directly, but will instead always have other amounts added or subtracted, then zero should be considered an "empty" value, and thus need not be explicitly stated.

    To use a crude analogy, consider the following two conditions:

    1. `if (xposition != 0) ...
    2. `if ((flags & WoozleModes.deluxe) != 0) ...

    In the former scenario, comparison to the literal zero makes sense because it is checking for a position which is semantically no different from any other. In the second scenario, however, I would suggest that the comparison to the literal zero adds nothing to readability because code isn't really interested in whether the value of the expression (flags & WoozleModes.deluxe) happens to be a number other than zero, but rather whether it's "non-empty".

    I don't know of any programming languages that provide separate ways of distinguishing numeric values for "zero" and "empty", other than by not requiring the use of literal zeros when indicating emptiness.

提交回复
热议问题