A couple of weeks ago, I shared an exercise I used to evaluate OO design skills on recruiting interviews. I got some interesting feedback from different people out there. Today I want to share an answer. As someone pointed out, this is a very simple problem, but even so, I could find no one to solve this. Not even one. In my experience, the moment the interview went on another direction than a CRUD exercise the developer find himself lost. So let’s review the problem statement:
Design a program that given a string such as “(1+2)/3*4” returns the correct result.
Finding the abstractions
So we need an object that evaluates an expression and returns a numeric value. Straightforward.
However, having an object that evaluates every single type of operation present in the expression is a violation of the single responsibility principle. The solution? Divide and conquer. Let’s create an object for each operation.
Now, all the calculator must do is to pass the expression to every operation object. Even when the message it’s called Evaluate, the return value from each operation object should be the expression with the values in place so that it can be passed to the next operation object. To extend the calculator capabilities all that’s needed is to add another operation object. This can easily be accomplished using an interface implemented by all the operation objects.
Focusing on the what, not how
I want to bring your attention to the fact that so far we haven’t discussed how this objects are going to evaluate the relevant bits of the expression. We don’t even have the data types on the messages (is expression a string or an object?) To me this is the hallmark of an experienced OO developer: the ability to focus on the big picture and ignore the little details until needed. This is called abstraction. Traditionally we are trained to start thinking on an algorithmic way, thinking of every minute detail. It takes some time and effort to start focusing on the what and leave the how to later. Going this way, we can use another technique to design the objects internals (the how, the implementation details) such as TDD. For the record, I’d probably use a regex to match the arithmetic sign, extract the values, execute the operation and replace the value back into the expression.
The next challenge
So, if you ever were on an interview with me, this is the answer that you probably almost found. Anyway, I have another challenge here: Can you identify the design patterns used in this solution? Which patterns would you use to improve it?