Programming with Units


In this post I describe a code ‘meta-pattern’ that has helped me segregate responsibilities and keep tests neat.

Note: there is more I’d like to say about this topic, so consider this a draft.


A Unit is a class that follows this structure:


@RequiredArgsConstructor // trivial constructor via Lombok
public class NameForTheClass {

  private final SomeDependencyA a;
  private final SomeDependencyB b;

  public ReturnType methodName([Arg arg, ...]) {

  // as many private methods as desired



Example JUnit 5 tests with Mockito:

public class NameForTheClassTests {

  @Mock private SomeDependencyA a;
  @Mock private SomeDependencyB b;
  @InjectMocks private NameForTheClass subject;

  public void methodName_pathA() {
    when(a.someMethod(x, y)).thenReturn(z);

    val result = subject.methodName(a, b, c);

    val expected = [...];

Intuition: Correct by Construction

A cluster of pure Units can be programmed in a ‘correct by construction’ fashion:

Prescription: Programming Paradigm

My recommended programming paradigm is Functional Programming.

This means that: