Programming with Units

Abstract

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.

Structurally

A Unit is a class that follows this structure:

Example:

@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
}

Semantically

Testing

Example JUnit 5 tests with Mockito:

@RunWith(MockitoJUnitRunner.StrictStubs.class)
public class NameForTheClassTests {

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

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

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

    val expected = [...];
    assertThat(expect).isEqualTo(result);
  }
}

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: