Last week I was involved in some new employee code reviews and pairing interviews. Since most people that apply to ThoughtWorks do our Mars Rover problem, I decided that I should probably give the problem a try. The solution is pretty simple, which is probably why most people select this problem. I happened to be in a programming mood at the time, so I decided to make the problem a little more difficult.
Could I write a solution without an IF statement?
It turns out that I can and the results were very interesting. Here is the first cut of my spin left method before the change over.
Here is another deviation with if statements, because you know... switches are smelly.
Then here is what I came up with when trying to remove all my conditions.
Personally, I find it much more readable than the other two. This is something I would not have expected given an arbitrary challenge. Maybe those anti-if people are onto something.
Might also consider states
ReplyDeleteclass East: IDirection{
public IDirection SpinLeft(){
return new North();
}
public IDirection SpinRight(){
return new South();
}
}
A directional vector could fit on there as well
I ended up with 5 classes in the end and some constants (like Direction). Seemed to work pretty well and the total code was about 100 lines, with another 100 lines of tests. Pretty fun little problem.
ReplyDelete