I\'ve read some of article about the practice that making Square an inheritance class of Rectangle class is a bad practice, saying it violate the LSP (Liskov substitution p
What's wrong with it from an Liskov substitution principle (LSP) perspective is that your Rectangle
s and Square
s are mutable. That means that you have to explicitly reimplement the setters in the subclass, and lose the benefits of inheritance. If you make Rectangle
s immutable, i.e., if you want a different Rectangle
you create a new one rather than altering the measurements of an existing one, then there's no problem with violating LSP.
class Rectangle
attr_reader :width, :height
def initialize(width, height)
@width = width
@height = height
end
def area
@width * @height
end
end
class Square < Rectangle
def initialize(length)
super(length, length)
end
end
Using attr_reader
gives getters but not setters, hence the immutability. With this implementation both Rectangles
and Squares
provide visibility to height
and width
, for a square those will always be the same, and the concept of area is consistent.