SOLID Liskov Substitution Principle

If I have something like

class square : figure {}

class triangle : figure {}

      

Does this mean that I should never use the squares and triangles classes, but only refer to the figure?

How to never do this:

var x = new square();

      

+2


source to share


3 answers


In your case, LSP means that all behavior inherited from figure

must be suitable for square

or triangle

. Therefore, you would not want to have setters for figure.Side1

, Side2

and Side3

because it doesn't make sense for square

.

You will need to refer to square

or at some point triangle

, but only in cases where what you are doing is subclassing. If you are doing behavior that will apply equally well to all shapes (probably the Draw method) then it should take a parameter figure

, not an square

or triangle

.

As an example, your classes can be configured like this:



abstract class figure
{
    abstract void draw();
}

class triangle : figure
{
    void draw()
    {
        // ...
    }
}

class drawer
{
    void call_draw(figure fig)
    {
        fig.draw();
    }
}

      

As long as it figure.draw()

is virtual, that is, its implementation can (or should) be overridden by a subclass, you can enforce behavior triangle

draw()

even if the object is used as figure

.

+6


source


You must define the classes square

and triangle

and implement your methods - and you must be able to build them as you indicated:

var x = new square();

      

Most if not all other uses square

and triangle

should be done through the base classfigure.



As far as LSP is concerned , this applies to other methods in other classes that take figure

as a parameter:

other_method(figure fig);

      

This method should be happy to work, regardless of whether an instance is passed to it square

or triangle

, and it doesn't need to try to find the actual class to work with.

+2


source


I need to know the difference between Liskov's substitution principle and segregation interface, it looks like it looks like.

-1


source







All Articles