Pattern for Creating a Simple and Efficient Value type

前端 未结 4 1877
臣服心动
臣服心动 2020-12-24 12:34

Motivation:

In reading Mark Seemann’s blog on Code Smell: Automatic Property he says near the end:

The bottom line is that au

4条回答
  •  轮回少年
    2020-12-24 13:22

    Is there a way to make MinValue/MaxValue const instead of readonly?

    No. However, the BCL doesn't do this, either. For example, DateTime.MinValue is static readonly. Your current approach, for MinValue and MaxValue is appropriate.

    As for your other two questions - usability and the pattern itself.

    Personally, I would avoid the automatic conversions (implicit conversion operators) for a "temperature" type like this. A temperature is not an integer value (in fact, if you were going to do this, I would argue that it should be floating point - 93.2 degrees C is perfectly valid.) Treating a temperature as an integer, and especially treating any integer value implicitly as a temperature seems inappropriate and a potential cause of bugs.

    I find that structs with implicit conversion often cause more usability problems than they address. Forcing a user to write:

     Celsius c = new Celcius(41);
    

    Is not really much more difficult than implicitly converting from an integer. It is far more clear, however.

提交回复
热议问题