Sometimes you need to take your code to a deep dark forest where 2 + 2 = 5
The title here paraphrases a quote of the late world chess champion Mikhail Tal when he states that
You must take your opponent into a deep dark forest where 2 + 2 = 5 , and the path leading out is only wide enough for one
Tal, nicknamed, the wizard of Riga was a master in creating chaos, messing up ordered positions to create difficulties that only he could handle. That was his favorite territory and where he was comfortable.
Chess is an elegant game where most of the time, following the rules and choosing the priority of such rules are the keys for success. However my goal here is to show that if you adhere blindly to the rules that will only take you to a limited level. And this metaphor is a lesson we can take from chess to life and to software development.
When coding most of the time elegance and efficiency walk hand-to-hand, however there are some examples where that's not the case.
Let's see the code below:
def fib ( n ) n >= 2 ? fib(n-1) + fib(n-2) : 1 end
This is cute, correct but very very naïve. Someone might cry now, wait you are going the straw man path to which I would answer yes, because in five minutes (this post has been written to be a lightning talk limited to 5-minutes) it's not possible to dissect a real life example. And that's why I took chess as my companion.
In chess we also have a number of design patterns: fight for the center, develop your pieces early, protect the king, avoid double pawns, etc. And if we neglect those we are often punished by our opponent.
The example I'm about to show is a game from a former world champion the Russian Vasily Smyslov vs the american child prodigy and grandmaster Samuel Reshevsky, they are fighting for the 1948 world title and it seems that Smyslov playing with white better but then he shows that by playing ugly he can be much better.
Here the natural move would be Qf3 with the idea of Qd3 in the future. By the way, if you feed this position to the computer (Stockfish 8 64 POPCNT) that's the move it will choose for at least 10 minutes of thinking.
The computer discard Smyslov move as bad and don't return to revisit it until you show it. Then when exploring the move several levels deep it sees that although ugly and apparently inefficient it's a winning move and the easiest way to win the game.
It's ugly and it hits most of our chess prejudices because if the black Queen captures the white one then to recapture we have to double pawns expose it the King have an open file in front of the king and then that makes the move very very
ugly but a wining one.
Make no mistake, I'm not advocating that we write ugly code and don't follow design patterns, what I want is to entice us to think that to achieve a Grandmaster level in development sometimes we need to get rid of our prejudices and give ourselves the luxury of making an ugly yet efficient code.
A video of the talk