CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 2 of 6 · 2 min read

The rule

Point at stable abstractions.

Think of a lamp and a wall socket. The lamp does not know whether the power comes from a coal plant or a solar panel. It only knows the shape of the plug. The socket is an abstraction, and both the lamp and the power station follow it.

CA states the principle as follows. The most flexible systems are those where source code refers only to abstractions and not to concrete classes. In Java, this means that import statements and field types should name interfaces or abstract classes, and not the concrete classes that implement them.

CA is realistic about this. Treating it as an absolute rule is unrealistic, since every system depends on concrete things. java.lang.String is concrete, and nobody should try to hide it. The reason is that String is stable. Changes to it are rare and carefully controlled. So the rule is aimed at the volatile concrete classes, which are the ones the team is actively writing and changing.

CA explains why abstractions are safer. A change to an interface forces a change in every class that implements it. A change to a class's inside rarely changes its interface. So interfaces change less often than implementations, and good designers work hard to keep them steady. Depend on the steady thing.

Dependency inversion principle

The dependency inversion principle says that important code should depend on interfaces, and that detailed code should implement those interfaces, so that details can change without touching the important code.

Example: a BookingService that holds a Notifier interface, not an SmtpSender class.

Volatile

A class is volatile when it is under active development and changes often.

Example: a team's own email-sending class, as opposed to String.

Check yourself: 1. Why is depending on String acceptable? 2. Why do interfaces change less than implementations? 3. Which kind of class does the rule target?