A trivial coding example (i.e. a Calculator) tackled using the following programming paradigms in Java not only to perform well in coding interviews, but also to learn these programming paradigms.
Approach 1: Procedural Programming
Approaches 2 – 4: Object Oriented Programming
Approach 5: Functional Programming (Java 8)
Approach 1: Procedural
|
public interface Calculate { abstract int calculate(int operand1, int oerand2, Operator operator); } |
|
public enum Operator { ADD, SUBTRACT, DIVIDE, MULTIPLY; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
public class CalculateImpl implements Calculate { @Override public int calculate(int operand1, int operand2, Operator operator) { switch (operator) { case ADD: return operand1 + operand2; case SUBTRACT: return operand1 - operand2; case MULTIPLY: return operand1 * operand2; case DIVIDE: return operand1 / operand2; } throw new RuntimeException(operator + "is unsupported"); } } |
…