OOP Fundamentals • EncapsulationMedium⏱️ ~3 min
Application: Parking Lot Encapsulation
Domain: Parking Lot System
A parking lot must enforce capacity limits, prevent double-booking of spots, and manage vehicle assignments. Without encapsulation, these invariants can be violated.
ParkingLot
- floors: List<Floor>
- capacity: int
- occupiedCount: int
+ parkVehicle(vehicle): Ticket
+ unparkVehicle(ticket): Vehicle
+ isFull(): boolean
◆
ParkingSpot
- spotId: String
- isOccupied: boolean
- assignedVehicle: Vehicle
+ assignVehicle(vehicle): boolean
+ releaseVehicle(): Vehicle
+ isAvailable(): boolean
Encapsulation Decisions:
First, Protected Invariant: ParkingSpot.isOccupied must always match whether assignedVehicle is null. Making both private and providing assignVehicle() ensures they stay synchronized.
Second, Capacity Control: ParkingLot.occupiedCount is private. Only parkVehicle() and unparkVehicle() can modify it, preventing manual manipulation that could allow overbooking.
Third, Spot Assignment Logic: assignVehicle() checks availability before assignment. External code cannot bypass this check by directly setting assignedVehicle.
Critical Method: assignVehicle()
public assignVehicle(vehicle: Vehicle): boolean {
// Check invariant before modification
if (this.isOccupied) {
return false // Spot already taken
}
// Atomically update both fields
this.assignedVehicle = vehicle
this.isOccupied = true
return true
}
// Check invariant before modification
if (this.isOccupied) {
return false // Spot already taken
}
// Atomically update both fields
this.assignedVehicle = vehicle
this.isOccupied = true
return true
}
Without Encapsulation
Public
isOccupied field can be set to false while assignedVehicle still holds a vehicle, creating inconsistent state and double-booking.→
With Encapsulation
Private fields with
assignVehicle() method ensures both fields are always synchronized. Impossible to create invalid state.Interview Tip: For domain objects, identify what can go wrong (double-booking, exceeding capacity) and explain how private fields + validation methods prevent these scenarios.
💡 Key Takeaways
✓Private fields prevent inconsistent state between related attributes
✓Public methods enforce domain rules like capacity limits
✓Encapsulation enables atomic updates to multiple related fields
✓Spot availability is computed logic, not directly settable state
✓Changes to spot assignment algorithm don't affect client code
📌 Examples
1Parking spot preventing double-booking through private assignment
2Library BookCopy preventing checkout if already borrowed
3Elevator preventing floor requests beyond building range