CSE Roadmap

Common tier · about 2 hours · 7 parts

Part 4 of 7 · 1 min read

Four shapes

Choose the shape that fits what the thing is.

Shape Use it for Room system example
Class An object that changes or has behaviour Booking, BookingService
Record A value that never changes Room, TimeSlot
Enum A small fixed set of named values BookingStatus
Interface A promise that several classes can keep PricingStrategy

A record gives a constructor, accessors, equals, hashCode and toString for free. Two records with equal fields are equal, which is exactly what a value object should do. An enum cannot be misspelled, unlike a string such as "CONFIRMED".

An interface fits where behaviour will vary. A made-up case: rooms may be free for staff but charged for visitors. A PricingStrategy interface with price(Booking) lets both be written as separate classes. Do not add an interface until a second version is likely. Level 2 explains why.

interface PricingStrategy {
    int priceInCents(Booking booking);
}

class FreeForStaff implements PricingStrategy {
    public int priceInCents(Booking booking) { return 0; }
}

Money is stored in whole cents as an int (or long), not as double, because floating-point numbers cannot hold 0.10 exactly.

Check yourself: 1. Which shape fits TimeSlot, and why? 2. Why use an enum and not a string for status? 3. Why store money in cents?