saasbook

lsp_square_rect_fix.rb

Mar 13th, 2014
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 0.56 KB | None | 0 0
  1. # LSP-compliant solution: replace inheritance with delegation
  2. # Ruby's duck typing still lets you use a square in most places where
  3. #  rectangle would be used - but no longer a subclass in LSP sense.
  4. class Square
  5.   attr_accessor :rect
  6.   def initialize(side, top_left)
  7.     @rect = Rectangle.new(side, side, top_left)
  8.   end
  9.   def area      ; rect.area      ; end
  10.   def perimeter ; rect.perimeter ; end
  11.   # A more concise way to delegate, if using ActiveSupport (see text):
  12.   #  delegate :area, :perimeter, :to => :rectangle
  13.   def side=(s) ; rect.width = rect.height = s ; end
  14. end
Add Comment
Please, Sign In to add comment