CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 5 of 6 · 2 min read

Testing and frameworks

Fakes in tests, containers for big programs.

Testing and frameworks

The biggest everyday gain is in tests. A test builds the service with simple stand-ins and checks what happened.

List<String> sent = new ArrayList<>();
BookingService t = new BookingService(
    () -> 42,
    (to, msg) -> sent.add(to + "|" + msg),
    new MemoryStore());
t.book("ravi");

After this, sent holds one entry, "ravi|booked at 42". The clock is fixed, the notifier writes to a list, and no mail is sent. Because Clock and Notifier each have one method, a lambda serves as the fake.

CC notes a wider effect. Code that is hard to test is usually tightly coupled, so writing tests pushes a design toward interfaces and injection, which lowers coupling.

For large programs, building the graph by hand gets long. A DI framework, such as Spring, reads the wiring from configuration or annotations and builds the objects. CC mentions Spring as an example of a framework that offers DI. A framework only automates the composition root. The class design is the same: constructor parameters, interfaces and no hidden new. Learn the manual form first, and mention frameworks in an interview as a tool.

A caution from Level 2, module 7. Do not create an interface for every class just to inject it. Inject what is likely to change or to be faked: time, storage, network, notifications and randomness.

Common mistake

Passing the whole application context or a "service locator" object into a class and letting it pick what it wants. The dependencies become hidden again.

Interview angle

Answer in your head first, then open it.

What is dependency injection?

A class receives its dependencies from outside, normally through its constructor, and does not create them.

Why use it?

Classes become flexible and testable, because real dependencies can be swapped for fakes.

How is it different from a factory or a singleton?

A factory creates objects on request. A singleton hides one global instance. DI makes needs visible and lets the caller decide.

Check yourself: 1. What does sent hold after the test runs? 2. What does a DI framework automate?

Words you will meet

Word Meaning
Dependency injection Passing the objects a class needs into it from outside
Constructor injection Receiving dependencies as constructor parameters
Composition root The single place where objects are created and wired
Inversion of control Moving the job of creating or choosing helpers out of a class
Fake A simple stand-in used in place of a real dependency in a test