CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 6 of 6 · 2 min read

Exercises

Easy

Easy 1: Spot the leak (20 minutes)

Find the way a caller can change the inside of this class: a final field Date opens, a getter returning it, and a constructor storing the argument.

Done when: you name two leaks, one in the constructor and one in the getter.

Hint

The constructor stores the caller's object, and the getter hands it out.

Easy 2: Run Money (20 minutes)

Type the Money class and compute fee.times(3).plus(Money.rupees(120)) for a fee of 500 rupees.

Done when: it prints 1620.00 and fee still prints 500.00.

Hint

Each operation returns a new object.

Easy 3: Value or entity (20 minutes)

Label each as value or entity: a phone number, a customer account, a date range, a booking, a postal address.

Done when: five items each have a label and one reason.

Hint

Ask whether two with the same content are interchangeable.

Medium

Medium 1: Fix the leaks (45 minutes)

Repair the class from Easy 1 using Instant or a defensive copy. Write a test that tries both attacks.

Done when: both attacks fail and the test says so.

Hint

Instant is immutable, so no copy is needed.

Medium 2: Email address (45 minutes)

Write an immutable Email value that checks the format in the constructor, lowercases the domain, and defines equals and hashCode.

Done when: two spellings of the same address compare equal and a bad address is rejected.

Hint

Normalise in the constructor, before storing.

Medium 3: Cart with withers (45 minutes)

Write an immutable Cart with withItem and withoutItem. Show that earlier carts do not change.

Done when: three carts exist at once with different contents.

Hint

Copy the list, change the copy, wrap in a new cart.

Hard

Hard 1: Money with a rate (90 minutes)

Extend Money to convert between two currencies with a rate given as a value object. Use a rounding rule and state it.

Done when: converting there and back is tested, and a note says where the rounding error appears.

Hint

Hold the rate as scaled integers or BigDecimal.

Hard 2: Record with a list (90 minutes)

Write a record with a List<String> field. Show the leak, then repair it with a compact constructor and an unmodifiable copy.

Done when: a test shows the leak before and no leak after.

Hint

List.copyOf in the compact constructor.

Hard 3: Entities and values (90 minutes)

Design a hotel booking with Guest, Room, Stay and Booking. Decide which are values and which are entities, and which fields of the entities are immutable.

Done when: a table lists each class with its kind and a reason, and the code shows the booking changing state through one method.

Hint

Identity usually means an id that never changes.