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
|
1 2 3 |
public interface Calculate { abstract int calculate(int operand1, int oerand2, Operator operator); } |
|
1 2 3 |
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"); } } |
|
1 2 3 4 5 6 7 8 9 10 11 |
public class CalculatorTest { public static void main(String[] args) { Calculate calc = new CalculateImpl(); int result = calc.calculate(5,6,Operator.ADD); result = calc.calculate(result,6,Operator.MULTIPLY); result = calc.calculate(result,1,Operator.SUBTRACT); result = calc.calculate(result,5,Operator.DIVIDE); System.out.println("result=" + result); } } |
Output: result=13
Approach 2: OOP
|
1 2 3 |
public interface MathCommand<E> { abstract E execute(E operand1, E operand2); } |
|
1 2 3 4 5 6 7 |
public class AddCommand implements MathCommand<Integer>{ @Override public Integer execute(Integer operand1, Integer operand2) { return operand1 + operand2; } } |
|
1 2 3 4 5 6 7 |
public class SubtractCommand implements MathCommand<Integer>{ @Override public Integer execute(Integer operand1, Integer operand2) { return operand1 - operand2; } } |
|
1 2 3 4 5 6 7 |
public class MultiplyCommand implements MathCommand<Integer>{ @Override public Integer execute(Integer operand1, Integer operand2) { return operand1 * operand2; } } |
|
1 2 3 4 5 6 7 |
public class DivideCommand implements MathCommand<Integer>{ @Override public Integer execute(Integer operand1, Integer operand2) { return operand1 / operand2; } } |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class CalculatorTest2 { public static void main(String[] args) { MathCommand<Integer> command = new AddCommand(); Integer result = command.execute(5, 6); command = new MultiplyCommand(); result = command.execute(result, 6); command = new SubtractCommand(); result = command.execute(result, 1); command = new DivideCommand(); result = command.execute(result, 5); System.out.println("result=" + result); } } |
When you have more mathematical operations,
…