Port of schuchert.wikispaces.com


Open/Closed Exercise Hints

Open/Closed Exercise Hints

Example of before/after test

The tests will all be converted to using the new API of the calculator. One way to do that is below in the after example.

Test Example Before Applying OCP

    @Test
    public void addsNumbersCorrectly() {
        calculator.enter(BigDecimal.valueOf(13));
        calculator.enter(BigDecimal.valueOf(-2));
        calculator.add();
        assertEquals(BigDecimal.valueOf(11), calculator.x());
    }

Test Example After Applying OCP

    @Test
    public void addsNumbersCorrectly() {
        calculator.enter(BigDecimal.valueOf(13));
        calculator.enter(BigDecimal.valueOf(-2));
        calculator.execute("add");
        assertEquals(BigDecimal.valueOf(11), calculator.x());
    }

Notice, you can do this in small steps. Assuming adding execute(String), you could:

public void execute(String operatorName) {
    add();
}
public void execute(String operatorName) {
    if("add".equals(operatorName))
        add();
    if("subtract".equqls(operatorName))
        subtract();
}

Example of test for unknown operators

Every solution introduces problems. The change in the API of the RpnCalculator introduces a few issues:

While this is not “the final” version, we can begin to address some of these things with some tests. Here’s one such test that at least addresses mis-named operators.

    @Test
    public void handlesUnknownOperator() {
        String badOperatorName = "--BOGUS--";

        IllegalArgumentException illegalArgumentException = assertThrows(
                IllegalArgumentException.class,
                () -> calculator.execute(badOperatorName)
        );

        assertEquals("Operator: '" + badOperatorName + "' does not exist", illegalArgumentException.getMessage());
    }

Comments

" Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.