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

前端 未结 5 2483
借酒劲吻你
借酒劲吻你 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:47

    The question is, "how do you want to turn a modifiable class into a read-only class by inheriting from it?" With inheritance you can extend a class but not restrict it. Doing so by throwing exceptions would violate the Liskov Substitution Principle (LSP).

    The other way round, namely deriving a modifiable class from a read-only class would be OK from this point of view; however, how do you want to turn a read-only property into a read-write property? And, moreover, is it desirable to be able to substitute a modifiable object where a read-only object is expected?

    However, you can do this with interfaces

    interface IReadOnly
    {
        int MyProperty { get; }
    }
    
    interface IModifiable : IReadOnly
    {
        new int MyProperty { set; }
        void Save();
    }
    

    This class is assignment compatible to the IReadOnly interface as well. In read-only contexts you can access it through the IReadOnly interface.

    class ModifiableClass : IModifiable
    {
        public int MyProperty { get; set; }
        public void Save()
        {
            ...
        }
    }
    

    UPDATE

    I did some further investigations on the subject.

    However, there is a caveat to this, I had to add a new keyword in IModifiable and you can only access the getter either directly through the ModifiableClass or through the IReadOnly interface, but not through the IModifiable interface.

    I also tried to work with two interfaces IReadOnly and IWriteOnly having only a getter or a setter respectively. You can then declare an interface inheriting from both of them and no new keyword is required in front of the property (as in IModifiable). However when you try to access the property of such an object you get the compiler error Ambiguity between 'IReadOnly.MyProperty' and 'IWriteOnly.MyProperty'.

    Obviously, it is not possible to synthesize a property from separate getters and setters, as I expected.

提交回复
热议问题