Advertisement
saasbook

liskov_example.rb

Mar 6th, 2012
1,024
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.12 KB | None | 0 0
  1. class Rectangle
  2.   attr_accessor :width, :height, :top_left_corner
  3.   def new(width,height,top_left) ... ; end
  4.   def area ... ; end
  5.   def perimeter ... ; end
  6. end
  7.  
  8. # A square is just a special case of rectangle...right?
  9.  
  10. class Square < Rectangle
  11.   # ooops...a square has to have width and height equal
  12.   attr_reader :width, :height, :side
  13.   def width=(w)  ; @width = @height = w ; end
  14.   def height=(w) ; @width = @height = w ; end
  15.   def side=(w)   ; @width = @height = w ; end
  16. end
  17.  
  18. # But is a Square really a kind of Rectangle?
  19.  
  20. def make_twice_as_wide_as_high(r, dim)
  21.   r.width = 2*dim
  22.   r.height = dim
  23. end
  24. # violates LSP, if this method is part of "contract"!
  25.  
  26. # LSP-compliant solution: replace inheritance with delegation
  27. # Ruby's duck typing still lets you use a square in most places where
  28. #  rectangle would be used - but no longer a subclass in LSP sense.
  29.  
  30. class Square
  31.   def initialize(side,top_left_corner)
  32.     @rect = Rectangle.new(side,side,top_left_corner)
  33.   end
  34.   def area      ; @rect.area      ; end
  35.   def perimeter ; @rect.perimeter ; end
  36.   def side=(s) ; @rect.width = @rect.height = s ; end
  37. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement