What's wrong with the Square and Rectangle inheritance?

前端 未结 3 2001
Happy的楠姐
Happy的楠姐 2021-01-05 11:28

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

3条回答
  •  [愿得一人]
    2021-01-05 12:26

    What's wrong with it from an Liskov substitution principle (LSP) perspective is that your Rectangles and Squares are mutable. That means that you have to explicitly reimplement the setters in the subclass, and lose the benefits of inheritance. If you make Rectangles 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.

提交回复
热议问题