The before code mixes move validation and check detection inside the Game class, making it hard to maintain. The after code moves validation and check detection into separate classes, improving modularity and testability.
### Before: move validation and check detection mixed in Game class
class Game:
def move(self, from_pos, to_pos):
# Validate move
if not self.is_valid_move(from_pos, to_pos):
return False
# Make move
self.board[to_pos] = self.board[from_pos]
self.board[from_pos] = None
# Check if king is in check
if self.is_king_in_check(self.current_player):
# Undo move
self.board[from_pos] = self.board[to_pos]
self.board[to_pos] = None
return False
return True
def is_valid_move(self, from_pos, to_pos):
# Complex logic here
pass
def is_king_in_check(self, player):
# Complex logic here
pass
### After: separated MoveValidator and CheckDetector
class MoveValidator:
def __init__(self, board):
self.board = board
def validate(self, from_pos, to_pos):
# Complex validation logic
pass
class CheckDetector:
def __init__(self, board):
self.board = board
def is_in_check(self, player):
# Complex check detection logic
pass
class Game:
def __init__(self):
self.board = ...
self.validator = MoveValidator(self.board)
self.check_detector = CheckDetector(self.board)
def move(self, from_pos, to_pos):
if not self.validator.validate(from_pos, to_pos):
return False
# Make move
self.board[to_pos] = self.board[from_pos]
self.board[from_pos] = None
if self.check_detector.is_in_check(self.current_player):
# Undo move
self.board[from_pos] = self.board[to_pos]
self.board[to_pos] = None
return False
return True