Question

I've been thinking recently about the Liskov Substitution Principle and how it relates to my current task. I have a main form which contains a menu; into this main form I will dock a specific form as a MDI child. This specific form may or may not contain a menu. If it does, I want to merge it with the main menu. So the situation is like this:

public class MainForm
{
    public void Dock(SpecificBaseForm childForm)
    {
        this.Dock(childForm);
        if (childForm is IHaveMenu)
        {
            this.Menu.Merge(childForm as IHaveMenu).Menu;
        }
    }
 }

public interface IHaveMenu
{
   Menu Menu {get;}
}

public abstract class SpecificBaseForm{}

public class SpecificFormFoo : SpecificBaseForm {}

public class SpecificFormBar: SpecificBaseForm,IHaveMenu
{
    public Menu Menu{get {return this.Menu;}}
}

Now the two children are not "exactly" interchangeble: one has a menu; the other doesn't. Is this a misuse of the is/as contruct in C#? If this is not correct, what would be the clean solution?

Was it helpful?

Solution

No, it's not a violation of the Liskov substitution principle. Whether the specific sub classes implement different interfaces don't matter as long as they can be used in place of the base class.

Also keep in mind that the LSP is about the behaviour of the class, not about the signatures of methods or whether they implement an additional interface or not.

OTHER TIPS

The Liskov substitution principle states that the base classes must be able to be replaced by their more derived subtypes. The subclasses don't need to be able to replace each other, as long as each individually can replace the base class without breaking the program or otherwise causing it to not function as desired. So the instance you described does not violate the LSP.

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