The before code mixes all logic in one class and uses a simple list to track spots, which is hard to extend. The after code uses separate classes for Vehicle and ParkingSpot, encapsulating behavior and making it easier to add features like different spot types or vehicle sizes.
### Before: No clear design, everything in one function
class ParkingLot:
def __init__(self, capacity):
self.capacity = capacity
self.spots = [None] * capacity
def park(self, vehicle):
for i in range(self.capacity):
if self.spots[i] is None:
self.spots[i] = vehicle
return i
return -1
### After: Object-oriented design with classes
class Vehicle:
def __init__(self, license_plate, vehicle_type):
self.license_plate = license_plate
self.vehicle_type = vehicle_type
class ParkingSpot:
def __init__(self, spot_id, spot_type):
self.spot_id = spot_id
self.spot_type = spot_type
self.is_free = True
self.vehicle = None
def park_vehicle(self, vehicle):
if self.is_free and self.spot_type == vehicle.vehicle_type:
self.vehicle = vehicle
self.is_free = False
return True
return False
def remove_vehicle(self):
self.vehicle = None
self.is_free = True
class ParkingLot:
def __init__(self, spots):
self.spots = spots
def park_vehicle(self, vehicle):
for spot in self.spots:
if spot.park_vehicle(vehicle):
return spot.spot_id
return -1