How to ensure inheriting classes do not break base class contract in the context of LSP?

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.

Answers


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.


Need Your Help

Change GridView header placement

c# xaml gridview microsoft-metro windows-runtime

I have a normal GridView, that displays grouped data. My goal is to move the header (a button) from the top of the group to the left of the group.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.