Created
May 11, 2021 16:39
-
-
Save armandofox/8c1a10862521a34e274c3f1cfa5c24d8 to your computer and use it in GitHub Desktop.
lsp_square_rect_fix.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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