-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathliskov_substitution.rb
81 lines (65 loc) · 1.5 KB
/
liskov_substitution.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# Liskov’s principle tends to be the most difficult to understand. The principle
# states that you should be able to replace any instances of a parent class
# with an instance of one of its children without creating any unexpected or
# incorrect behaviors.
class Rectangle
def initialize(height, width)
@height = height
@width = width
end
def set_height(height)
@height = height
end
def set_width(width)
@width = width
end
def square
@width * @height
end
end
# Solution
# LSP says is if we know the interface of Rectangle, We need to be able to guess
# the interface of subtype class Square
# Square.new(3).square => 9
class Square < Rectangle
def initialize(side)
super(side, side)
end
def set_height(height)
super(height)
@width = height
end
def set_width(width)
super(width)
@height = width
end
end
# Another common instance of a Liskov violation is raising an exception for an
# overridden method in a child class. It’s also not uncommon to see methods
# overridden with modified method signatures causing branching on type in
# classes that depend on objects of the parent’s type. All of these either
# lead to unstable code or unnecessary and ugly branching.
class Animal
def walk
'walking_as_animal'
end
end
class Cat < Animal
def run
'run_as_cat'
end
end
# Solution
class Animal
def walk
'walking_as_animal'
end
def run
raise NotImplementedError
end
end
class Cat < Animal
def run
'run_as_cat'
end
end