The RPN calculator implementation is a good exercise for working through a languages capabilities and exploring OO strategies.
I have done four variations of the RPN calculator as exploratory into languages:
This implementation utilizes Java and Gradle.
To install Java and Gradle, either download or install using brew
brew install java
brew install gradleTo run the tests, run the following command:
gradle test-
Create a new operator implementation class. Add this class to the
operatorsdirectory. Follow the conventation of(operator name)-operator.js(example:addition-operator.js). -
The operator implementation class needs to implement the interface
Operator, which will have the class implement the following methods
doOperation(RpnStack): this method is responsible forpop-ing the operands from the stack, execute the operation, andpushthe result back to the stackhandlesOperatorCharacter(String): this method is responsible for checking if this class handles a particular operator character. For example, an addition operation class would returntruefor+.
A sample base implementation for addition is shown below:
public class AdditionOperator implements Operator {
private static final String PLUS = "+";
@Override
public int doOperation(RpnStack numbers) {
int rhs = numbers.pop();
int lhs = numbers.pop();
int result = rhs + lhs;
numbers.push(result);
return result;
}
@Override
public boolean handlesOperatorCharacter(String operand) {
return PLUS.contentEquals( operand );
}
}- Register operator in
OperatorRegistry. To do this, add the following statement:
operatorRegistry.add( new AdditionOperator() );