“How do I learn to write simpler, more efficient code with fewer lines?”
I’ve been asked this question a lot lately. Writing clear code is a noble endeavor, but a lot of programmers end up writing jumbled garble in their quest for elegance.
That said, I would like to address an incorrect assumption is hidden in the question. Simple code and fewer lines are concepts that are almost always at odds with each other.
The word simple comes from the latin word simplex, which is the opposite of complexus, which means braided, or together.
For example, let’s say that you have 6 lines of code that does 2 things:
AAAAAAAA AAAAAAAA AAAAAAAA AAAAAAAA BBBBBBBB BBBBBBBB
Let’s imagine that you discover that you can make part A shorter.
AAAAAAAA AAAAAAAA BBBBBBBB BBBBBBBB
Nice, that’s all good. Your code is now shorter and clearer. However, it’s a common mistake a programmer to not hold themselves back after this point, and you start reducing your line code further, but at the expense of making your code more complex and braided together:
AAAAAAAA AAAAAAAABBBBBBBB BBBBBBBB
A lot of the people asking me this question hang around on TopCoder-like sites. It’s important to recognize that what you’re doing on these sites is not professional programming, it is competitive programming. In an actual software team, the code of a good programmer is (in order of importance):
- Performant (but only when it needs to be)
1. Bug-free A good programmer understands the problem well, and spends a lot of time with each piece of code, thinking about everything that can go wrong, and delivers the code with unit tests. A programmer that doesn’t do these things is passing off that work to the next programmer touching the code and is often destructive to the team.
2. Clear Good programmers prioritizes understandable code over clever or elegant code. This is because they know that 95% of software development time is not spent writing code, it’s spent inside others code, trying to understand it.
3. Performant (but only when it needs to be) Good programmers know that to make things performant, you’re endangering point 1 & 2, so they only do performance optimization for parts of code that actually affects end-user performance. Good programmers have a gut feel for what parts of the code this is. Great programmers know that their gut feel is very often wrong, and use performance profiling tools to find out which parts of the code are bottlenecks.
In summary, strive to write clear code. Sometimes, that means using less code, but often it means breaking things apart into nicely separated lines of code that does one thing each, because you’re not writing code for the computer or yourself, you’re writing your code for the programmer that will read this code after you.
I’m going to post something interesting next week that I’d hate you to miss out on —hit that follow button.