Skip to content

Checkpoint: Swap a Policy

The Course
•
20 min study

A useful interface lets you change one decision without changing its consumer. This checkpoint combines constructor injection, behavioral contracts and tests. Do not introduce a hierarchy or a framework: a small interface and two implementations are enough.

Work through the example

A rule may be tested independently from the object that uses it. The example checks a boundary explicitly: 25 is accepted and 26 rejected. When a caller receives a rule, the rule's accepted domain must be clear. These implementations accept every int as input and return false for invalid durations.

Before Run, write the output and identify the exact line responsible for each result. Each editor is a separate program; names and edits in one box do not carry into the next.

Predict, then run Java
public class Main {
    public static void main(String[] args) {
        Rule rule = new ShortRule();
        System.out.println(rule.accepts(25));
        System.out.println(rule.accepts(26));
        System.out.println(rule.accepts(0));
    }
}

interface Rule {
    boolean accepts(int minutes);
}

final class ShortRule implements Rule {
    public boolean accepts(int minutes) {
        return minutes > 0 && minutes <= 25;
    }
}
Check your prediction
Text
true
false
false

Compare the behavior

A consumer should call the supplied policy rather than repeat its logic. Otherwise swapping implementations would change nothing. Here the independent Positive rule accepts a long session that ShortRule would reject. Both return booleans with the same meaning.

Trace the changed case Java
public class Main {
    public static void main(String[] args) {
        Rule rule = new Positive();
        int accepted = 0;
        for (int value : new int[] {-1, 10, 40}) {
            if (rule.accepts(value)) {
                accepted++;
            }
        }
        System.out.println(accepted);
    }
}

interface Rule {
    boolean accepts(int minutes);
}

final class Positive implements Rule {
    public boolean accepts(int minutes) {
        return minutes > 0;
    }
}
Check your prediction
Text
2

Plan your acceptance cases

Before writing the complete implementation, predict these cases without running the solution. Keep the requirements above as the authority; this table highlights distinct promises rather than prescribing a particular class layout.

CaseExpected behaviorSkill it checks
0,10,40 under PositiveTwo acceptedDelegated behavior
Same input under ShortRuleOne acceptedInterchangeable policy
Empty input under eitherZero; no hidden hard-coded policyTraversal independent of policy

After your first version works, choose one row and introduce a plausible defect that it should expose. Restore the correct version, then recreate the central operation without the worked example. If one skill is missing, revisit that lesson before combining more features.

Practice independently

Exercise

Checkpoint: Swap a Policy: practice

Build Counter receiving a Rule in its constructor. count(int[]) counts accepted entries without changing the input. Supply Positive and ShortRule implementations. On {0, 10, 40}, Positive must count 2 and ShortRule must count 1. Check empty input gives zero under either policy and print Policy checks passed.

Spend a few minutes on your own first. Compile after one small change, read the first error, and check the result against the requirements rather than matching the solution's layout.

Your workspace Java
public class Main {
    public static void main(String[] args) {
        System.out.println("Implement the interchangeable policies and Counter");
    }
}
Hint 1: the idea

Counter owns traversal; Rule owns the acceptance decision. Keep those responsibilities separate.

Hint 2: a first step

Store the Rule field, then replace a hard-coded comparison inside the loop with a call to accepts.

Show one solution

One possible implementation follows. Compare its decisions with yours: which values can change, what inputs are accepted, and what would expose a mistake?

Java
public class Main {
    public static void main(String[] args) {
        int[] input = {0, 10, 40};
        Counter positive = new Counter(new Positive());
        Counter shortOnly = new Counter(new ShortRule());
        check(positive.count(input) == 2);
        check(shortOnly.count(input) == 1);
        check(positive.count(new int[0]) == 0);
        check(shortOnly.count(new int[0]) == 0);
        check(input[2] == 40);
        System.out.println("Policy checks passed");
    }

    static void check(boolean condition) {
        if (!condition) {
            throw new AssertionError("policy contract");
        }
    }
}

interface Rule {
    boolean accepts(int minutes);
}

final class Positive implements Rule {
    public boolean accepts(int minutes) {
        return minutes > 0;
    }
}

final class ShortRule implements Rule {
    public boolean accepts(int minutes) {
        return minutes > 0 && minutes <= 25;
    }
}

final class Counter {
    private final Rule rule;

    Counter(Rule rule) {
        if (rule == null) {
            throw new IllegalArgumentException("rule required");
        }
        this.rule = rule;
    }

    int count(int[] values) {
        int count = 0;
        for (int value : values) {
            if (rule.accepts(value)) {
                count++;
            }
        }
        return count;
    }
}

Expected output:

Text
Policy checks passed

Change it and test again

Temporarily hard-code value > 0 in Counter. The ShortRule check must fail. Restore delegation, add boundary checks at 25 and 26, and introduce an EvenPositive rule without editing Counter.

Explain before moving on

Which tests verify the consumer and which verify the policy? Explain how the same split will help test a task service against an in-memory repository.

Was this article helpful?

Your response is saved on this device.