The before code moves the elevator position without tracking state, allowing conflicting moves. The after code uses a state variable to track if the elevator is idle, moving up, or moving down, preventing conflicting commands and making behavior predictable.
### Before: No explicit state management
class Elevator:
def __init__(self):
self.position = 0
def move_up(self):
# Moves up without checking current state
self.position += 1
def move_down(self):
# Moves down without checking current state
self.position -= 1
### After: With explicit state management
class Elevator:
IDLE = 'idle'
MOVING_UP = 'moving_up'
MOVING_DOWN = 'moving_down'
def __init__(self):
self.position = 0
self.state = Elevator.IDLE
def move_up(self):
if self.state == Elevator.MOVING_DOWN:
print('Cannot move up while moving down')
return
self.state = Elevator.MOVING_UP
self.position += 1
def move_down(self):
if self.state == Elevator.MOVING_UP:
print('Cannot move down while moving up')
return
self.state = Elevator.MOVING_DOWN
self.position -= 1
def stop(self):
self.state = Elevator.IDLE