Requirement – handling invalid input

Provided that our implementation is basically doing nothing, we are going to focus only on one thing—reading single operands. If the input is a single number (no operators) then it's a valid reverse notation and the value of the number is returned. Anything other than that is considered not a valid RPN for now.

This requirement is translated into these four tests:

public class ReversePolishNotationTest {
private ReversePolishNotation reversePolishNotation =
new ReversePolishNotation();

@Test(expected = NotReversePolishNotationError.class)
public void emptyInputThrowsError() {
reversePolishNotation.compute("");
}

@Test(expected = NotReversePolishNotationError.class)
public void notANumberThrowsError() {
reversePolishNotation.compute("a");
}

@Test
public void oneDigitReturnsNumber() {
assertThat(reversePolishNotation.compute("7")).isEqualTo(7);
}

@Test
public void moreThanOneDigitReturnsNumber() {
assertThat(reversePolishNotation.compute("120")).isEqualTo(120);
}
}

Our compute method is now required to throw an IllegalArgumentException when an invalid input is provided. In any other case it returns the number as an integer value. This can be achieved with the following lines of code:

public class ReversePolishNotation {
int compute(String expression) {
try {
return (Integer.parseInt(expression));
} catch (NumberFormatException e) {
throw new NotReversePolishNotationError();
}
}
}

This requirement has been fulfilled. The other requirement is a bit more complex, so we are going to divide it into two—single operations, which means only one operation, and complex operations, which involve more than one operation of any kind.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.241.116