Skip to content

Instantly share code, notes, and snippets.

@armandofox
Created May 11, 2021 16:39
Show Gist options
  • Save armandofox/8c1a10862521a34e274c3f1cfa5c24d8 to your computer and use it in GitHub Desktop.
Save armandofox/8c1a10862521a34e274c3f1cfa5c24d8 to your computer and use it in GitHub Desktop.
lsp_square_rect_fix.rb
# LSP-compliant solution: replace inheritance with delegation
# Ruby's duck typing still lets you use a square in most places where
# rectangle would be used - but no longer a subclass in LSP sense.
class Square
attr_accessor :rect
def initialize(side, top_left)
@rect = Rectangle.new(side, side, top_left)
end
def area ; rect.area ; end
def perimeter ; rect.perimeter ; end
# A more concise way to delegate, if using ActiveSupport (see text):
# delegate :area, :perimeter, :to => :rect
def side=(s) ; rect.width = rect.height = s ; end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment