CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 2 of 6 · 2 min read

Two bad ways

Telescoping constructors and setters.

Think of ordering a coffee. Telling the barista "large, oat milk, two sugars, no foam, extra hot" in a fixed order, with a blank for every item you skip, is slow and easy to get wrong. A form with labelled boxes is better.

A booking request has three required items (room, start, end) and several optional ones (attendees, projector, catering). EJ describes two common ways to write such a class, and why both fall short.

The first is the telescoping constructor. The class has one constructor with the required fields, another that adds one optional field, another that adds two, and so on. A call such as new BookingRequest("A1", 9, 11, 8, true, false) is hard to read. A reader cannot tell which number is the attendee count and which boolean is the projector. EJ grants that the approach works, but says it is awkward to write with many parameters and worse to read. Swapping two parameters of the same type compiles without complaint and gives a silent bug.

The second is the JavaBeans style. The class has an empty constructor, and the caller sets each field with a setter. Calls are readable. But EJ names serious problems. The object is in an inconsistent state while it is half built, and the class cannot check that its fields fit together. Using it in that state fails in ways far from the cause. It also rules out an immutable class (Level 1, module 2), because the setters change the object after it exists.

Telescoping constructor

A telescoping constructor is a series of constructors, each with one more optional parameter than the last.

Example: BookingRequest(room, start, end), then BookingRequest(room, start, end, attendees), then one more with projector.

Check yourself: 1. What makes a long constructor call hard to read? 2. Why can JavaBeans objects be inconsistent? 3. Why do setters rule out immutability?