The before code uses a single class with conditional statements to handle movement rules, making it hard to maintain and extend. The after code uses polymorphism by defining a base Piece class and subclasses for each piece type, each implementing its own move method. This design is cleaner, easier to extend, and follows object-oriented principles.
### Before: Without polymorphism (all logic in one class)
class Piece:
def __init__(self, type):
self.type = type
def move(self, position):
if self.type == 'pawn':
# pawn movement logic
return 'pawn moves'
elif self.type == 'knight':
# knight movement logic
return 'knight moves'
# more conditions for other pieces
### After: With polymorphism (each piece has its own class)
class Piece:
def move(self, position):
raise NotImplementedError()
class Pawn(Piece):
def move(self, position):
return 'pawn moves'
class Knight(Piece):
def move(self, position):
return 'knight moves'
# Usage
pieces = [Pawn(), Knight()]
for p in pieces:
print(p.move(None))