Question

In C# - but it may be applicable to other languages - in the context of LSP, how can I ensure that a class inheriting from another (mutable) one will not break the original contract?

For example: If I have public, internal or protected property setters, there is a risk that inheriting classes will break the original contract. The same is applicable for virtual methods.

This is especially true if the owner of the parent and inheriting classes are not the same persons as it may introduce a lack of knowledge in the contract and in the intention of the original developer.

Is immutability the only one solution or are there some other ways of doing? I tend to consider that inheritance corresponds to a "behaves like a"-relationship instead of a "is a"-relationship. Is it a correct logical safeguard?

Here's an example for the sake of illustration:

public class Foo
{
    public virtual void DummyMethod(int dummyParameter)
    {
        if (dummyParameter > 10) { throw new ArgumentOutOfRangeException(); }
    }
}

public class Bar : Foo
{
    public override void DummyMethod(int dummyParameter)
    {
        if (dummyParameter < 0) { throw new InvalidOperationException(); }
    }
}

I noticed some other questions dealing with this topic (here for example) but I'm looking for general solutions or good practices to apply to avoid facing these issues upfront.

Was it helpful?

Solution

You can prevent violation of the LSP by using the sealed keyword.

This means you now can't inherit from this class at all, so you have to decide which you prefer: eliminating the risk of violating the LSP or the freedom to inherit and modify.

Credit to @Hans Passant for first mentioning sealed in comments.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top