CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 4 of 6 · 2 min read

Quiet violations

Not supported, and special cases.

Most real violations are quieter than the square. Here are three shapes to recognise.

The first is a method that throws "not supported". A Room interface offers book(hours). A ClosedRoom implements it and throws an UnsupportedOperationException, since the room cannot be booked.

interface Room { void book(int hours); }

class OpenRoom implements Room {
    int booked;
    public void book(int hours) { booked += hours; }
}

class ClosedRoom implements Room {
    public void book(int hours) { throw new UnsupportedOperationException("closed"); }
}

A loop over a list of rooms prints "ok" for the open one and fails for the closed one. The caller must now add a try block, or a check, for a case the interface never mentioned. The interface promised something that one class cannot do. The better design splits the idea: keep book only on a Bookable interface and let ClosedRoom not implement it (module 4 of this level).

The second is a type check in the caller, such as if (room instanceof ClosedRoom). Any instanceof in code that should be generic hints at a broken substitution.

The third is a special case for a name or a vendor. CA gives a taxi aggregator that dispatches cars through a web address stored for each driver. All companies use the same fields. One company shortens one field name. To cope, a programmer adds if (uri.startsWith("acme.com")) in the dispatcher. Now the dispatcher knows about one company, and a merger or a second exception means another if. CA's cure is a configuration table, keyed by the address, that says how each company builds its request, so the code itself has no special case. The point is that a service which does not follow the shared interface leaks into the system.

Common mistake

Throwing "not supported" from an inherited method. If a subclass cannot honour the method, it probably should not be a subclass of that type.

Check yourself: 1. What does a caller of Room need to add to handle ClosedRoom? 2. Name two code signs of an LSP violation. 3. What cure does CA suggest for the taxi special case?