Skip to content

Instantly share code, notes, and snippets.

@omedale
Last active April 22, 2019 20:13
Show Gist options
  • Save omedale/72eca5fb016e413e3d52001532b8ba6b to your computer and use it in GitHub Desktop.
Save omedale/72eca5fb016e413e3d52001532b8ba6b to your computer and use it in GitHub Desktop.
Liskov Substitution Principle
class Rectangle
attr_accessor :height, :width
def calculate_area
width * height
end
end
class Square < Rectangle
def width=(width)
super(width)
@height = width
end
def height=(height)
super(height)
@width = height
end
end
rectangle = Rectangle.new
rectangle.height = 2
rectangle.width = 1
p rectangle.calculate_area
square = Square.new
square.height = 4
square.width = 2
p square.calculate_area
# We performed the same steps on parent and derived class
#but we observed different behaviour. Interfaces of parent and derived class are not consistent.
#solved by creating two separate classes with their own behaviour.
class Shape
def calculate_area
raise NotImplementedError
end
end
class Rectangle < Shape
attr_accessor :height, :width
def calculate_area
height * width
end
end
class Square < Shape
attr_accessor :side_length
def calculate_area
side_length * side_length
end
end
rectangle = Rectangle.new
rectangle.height = 2
rectangle.width = 1
p rectangle.calculate_area
square = Square.new
square.side_length = 4
p square.calculate_area
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment