I am trying to design a Parking Lot system using an object-oriented approach. The parking lot can have multiple types of parking spots such as Handicapped, Compact, Large, MotorBike etc.
Initially, I was thinking of creating an enum to model these different types as follows:
public enum ParkingSpotType {
HANDICAPPED,
COMPACT,
LARGE,
MOTORBIKE
}
And, then use these inside the ParkingSpot
class as follows:
public abstract class ParkingSpot {
private ParkingSpotType type;
}
Similarly, the Vehicle
class would also have VehicleType
, which would map to the ParkingSpotType
it requires for parking
public class Vehicle {
private VehicleType vehicleType;
// other fields
}
public enum VehicleType {
CAR (ParkingSpotType.COMPACT),
BUS (ParkingSpotType.LARGE),
TRUCK (ParkingSpotType.LARGE),
BIKE (ParkingSpotType.MOTORBIKE),
CYCLE (ParkingSpotType.MOTORBIKE);
private ParkingSpotType parkingSpotType;
VehicleType(ParkingSpotType parkingSpotType) {
this.parkingSpotType = parkingSpotType;
}
}
This was enabling me to find the ParkingSpotType
from Vehicle
simply by doing:
vehicle.getVehicleType().getParkingSpotType()
However, someone told me that this would violate the Open/Closed design principle. Any addition of a new type may require code changes in various existing places, which would violate the open/closed design principle which states that existing and well-tested classes should not be modified when a new feature needs to be introduced. It was suggested that I create different sub-classes for different types as follows:
public class HandicappedSpot extends ParkingSpot {
}
public class CompactSpot extends ParkingSpot {
}
public class LargeSpot extends ParkingSpot {
}
public class MotorbikeSpot extends ParkingSpot {
}
But with this approach, how would I map Vehicle to ParkingSpot if I don't have an enum modelling the same. Could someone please have a look and comment if the first approach is indeed bad wrt OO-Design. If yes, how would I solve the above-mentioned problem in the second approach ?