Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

This base class for some shapes I have in my game looks like this. Some of the s

ID: 644860 • Letter: T

Question

This base class for some shapes I have in my game looks like this. Some of the shapes can be resized, some of them can not.

   private Shape shape;

    public virtual void SetSizeOfShape(int x, int y)
    {
        if (CanResize()){
            shape.Width = x;
            shape.Height = y;
        }
        else {
            throw new Exception("You cannot resize this shape");
        }

    }
    public virtual bool CanResize()
    {
        return true;
    }
In a sub class of a shape that I don't ever want to resize I am overriding the CanResize() method so a piece of client code can check before calling the SetSizeOfShape() method.

    public override bool CanResize()
    {
        return false;
    }
Here's how it might look in my client code:

    public void DoSomething(Shape s)
    {
        if(s.CanResize()){
            s.SetSizeOfShape(50, 70);
        }
    }
Is this violating LSP?

Explanation / Answer

In a nutshell, the Liskov Substitution Principle states that, given a number of objects that conform to a particular interface, you should be able to swap them without causing errors in your program.

If you can do that, then your classes don't violate LSP.

The example provided in the LSP article on Wikipedia is quite illuminating. It says:

A typical example that violates LSP is a Square class that derives from a Rectangle class, assuming getter and setter methods exist for both width and height. The Square class always assumes that the width is equal with the height. If a Square object is used in a context where a Rectangle is expected, unexpected behavior may occur because the dimensions of a Square cannot (or rather should not) be modified independently.

This problem cannot be easily fixed: if we can modify the setter methods in the Square class so that they preserve the Square invariant (i.e., keep the dimensions equal), then these methods will weaken (violate) the postconditions for the Rectangle setters, which state that dimensions can be modified independently.

Violations of LSP, like this one, may or may not be a problem in practice, depending on the postconditions or invariants that are actually expected by the code that uses classes violating LSP. Mutability is a key issue here. If Square and Rectangle had only getter methods (i.e., they were immutable objects), then no violation of LSP could occur.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote