Design patterns and domain modeling

Substitution contract test

Check accepted inputs and rejection semantics for implementations. Executed Java 21 fixture.

Formal Syntax & Structure

java syntaxjava
Counter.add(n)

Working Example

Example Snippetjava
public class Main {    interface Counter { void add(int n); int value(); }    static int next(int old, int n) {        if (n < 0) throw new IllegalArgumentException("negative");        return Math.addExact(old, n);    }    static class MutableCounter implements Counter {        int count;        public void add(int n) { count = next(count,n); }        public int value() { return count; }    }    static class ArrayCounter implements Counter {        final int[] cell = {0};        public void add(int n) { cell[0] = next(cell[0],n); }        public int value() { return cell[0]; }    }    public static void main(String[] args) {        for (Counter c : java.util.List.of(new MutableCounter(), new ArrayCounter())) {            c.add(2); c.add(3);            if (c.value() != 5) throw new AssertionError();            try { c.add(-1); throw new AssertionError(); }            catch (IllegalArgumentException expected) { }            System.out.println(c.value());        }    }}
Java Reference