readonly class design when a non-readonly class is already in place

前端 未结 5 2405
借酒劲吻你
借酒劲吻你 2021-02-19 16:55

I have a class that upon construction, loads it\'s info from a database. The info is all modifiable, and then the developer can call Save() on it to make it Save that informati

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-19 17:34

    Definitely do not make the read-only class inherit from the writable class. Derived classes should extend and modify the capabilities of the base class; they should never take capabilities away.

    You may be able to make the writable class inherit from the read-only class, but you need to do it carefully. The key question to ask is, would any consumers of the read-only class rely on the fact that it is read-only? If a consumer is counting on the values never changing, but the writable derived type is passed in and then the values are changed, that consumer could be broken.

    I know it is tempting to think that because the structure of the two types (i.e. the data that they contain) is similar or identical, that one should inherit from the other. But that is often not the case. If they are being designed for significantly different use cases, they probably need to be separate classes.

提交回复
热议问题