Keep it stupidly-simple
2 min read

Keep it stupidly-simple

When I started to learn the intricacies of Javascript I was working alongside a colleague. He was a great programmer with different strengths than mine so it gave me a nice learning boost by turning pretty much everything into a competition.

I remember him one time showing me how much he shortened his code in some random function by using short ifs / ternary operators instead of the traditional if / else methods. Being at that stage of dangerous newbies trying to be clever we soon took things way to far.

What could have been a somewhat nice (albeit verbose) nice nested if...

if (case_1) {
     if (case_2) {
          result = method_a();
     } else {
          result = method_b();
     }
} else {
     result = method_c();
}

...was turned into a long and beastly short-circuited expression...

result = (case_1) ? (case_2) ? method_a() : method_b() : method_c();

... for the sake of brevity and "cleverness". Real developers wrote less code.

It is indeed true that less code is usually better than more code. No code is the best case scenario, everyone knows that. But what you should be aiming for is readability and I learned that the hard way.

I was supposed to make a zoom method that took and scaled an image while centering it around the clicked point, without surpassing certain boundaries. With some good, old-fashioned pen and paper experimentation, I came down with the algorithm.

The first version contained some clearly named variables in the vein of:

var targetCenterX = targetX + targetWidth / 2;

var centerDifferenceX = targetCenterX - clickX;

The whole method had a couple of dozens of lines of code. Way too much, I thought. So I compressed everything into a one-liner mega formula, comprising all the computations.

I was really proud of myself. I saved so much space and my code was now shorter. It felt like I was being a godlike hacker mathematician, coming up with clever theorems!

Then a week passed and a bug was discovered with the positioning in some edge cases. In a complete 180 degrees turn of events, I felt really stupid as I looked at that unintelligible mess of magic numbers and ratios, not knowing where to start.

I slowly but surely reverse-engineered the original method with the help of the initial scribbling made on paper. It was a painful lesson but a valuable one. See, it turns out that it's a much more clever strategy to code in a ELI5 fashion.

Clearly named variables, with meaningful names and complicated algorithms deconstructed step by step may not make the most glamorous code but they make sure that you comprehend what on earth you were doing there even after a lot of times passes.

You could say that this is one of the secrets of programming. Try to learn more each year but write code assuming the future version of you will be stupider. To paraphrase the famous principle, Keep it stupidly-simple.