-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem1_lsp.py
More file actions
87 lines (59 loc) · 1.79 KB
/
problem1_lsp.py
File metadata and controls
87 lines (59 loc) · 1.79 KB
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
82
83
84
85
86
87
"""
Problem 1: Liskov Substitution Principle (LSP)
"""
from abc import ABC, abstractmethod
# ---------- BAD DESIGN (LSP VIOLATION) ----------
class BadRectangle:
def set_dimensions(self, width, height):
self.width = width
self.height = height
def calculate_area(self):
return self.width * self.height
class BadSquare(BadRectangle):
def set_dimensions(self, width, height):
# Violates LSP: changes behavior
self.width = width
self.height = width
def bad_process_shape(shape):
shape.set_dimensions(5, 10)
print("Bad Area:", shape.calculate_area())
# ---------- GOOD DESIGN (LSP FOLLOWED) ----------
class Shape(ABC):
@abstractmethod
def set_dimensions(self, *args):
pass
@abstractmethod
def calculate_area(self):
pass
class Rectangle(Shape):
def set_dimensions(self, width, height):
self.width = width
self.height = height
def calculate_area(self):
return self.width * self.height
class Square(Shape):
def set_dimensions(self, side):
self.side = side
def calculate_area(self):
return self.side * self.side
class Circle(Shape):
def set_dimensions(self, radius):
self.radius = radius
def calculate_area(self):
return 3.14 * self.radius * self.radius
def process_shape(shape: Shape):
print("Area:", shape.calculate_area())
if __name__ == "__main__":
print("LSP Violation Example:")
bad_process_shape(BadRectangle())
bad_process_shape(BadSquare())
print("\nCorrect LSP Example:")
rect = Rectangle()
rect.set_dimensions(5, 10)
square = Square()
square.set_dimensions(5)
circle = Circle()
circle.set_dimensions(3)
process_shape(rect)
process_shape(square)
process_shape(circle)