This question came to me as I play a programming game called EXAPUNKS. The game offers no code solution to any of its challenges but as long as you manage to complete your programming mission, you are set. After you have written the code, run tests which it passed (your code has to satisfy 100 different case scenarios iterating on the same problem), a histogram will show up and you can see how many cycles your code took and the shortest code gets you the highest ranking.
EXAPUNKS teaches me that shorter code = better code but is that always true?
What do you think? Is shorter code, better code?
Top comments (60)
Depends. I think a good example is to look at the daily Leetcode for Dec 2. (1266 if you're interested). Also, spoiler alert!
Here's the more readable version that I would like to see in someone's code.
And here's a version that runs a little bit faster due to inbuilt functions, but is much less readable:
So... you decide. If you come back to the second version in a year or two, are you going to be happy with yourself? Probably not. However, maybe an alternative that's even better than the first two options is to simply leave good comments, or just leave the readable version of the code, but commented.
I would argue (as many do) against code that needs comments to explain how it works.
So, for real work, most of the time easily readable > concise (of course, if speed is your big concern, there's that to consider, but most of the time this time of speed gain is not what you need).
From my beginner perspective, I'd say that depends on whether someone else has to read and understand it. The short version may be pretty unintelligible. Using descriptive variable names with intermediate steps, for example, could lengthen the code but also strengthen the understanding.
That sounds right. I have also heard people talking about efficiency, that shorter code means higher efficiency but I do not know about that.
Yeah, I imagine once the compiler compiles it, the original code doesn't matter too much, especially in cases where the longer version and the shorter version actually represent the same algorithm. Gains in efficiency would come from the algorithm itself, and not the length of the code as determined by what syntax was used or how many steps.
In theory there can be a marginal difference but it's not enough to be worthwhile.
Also, in any language that has any sort of compile step (which includes not just traditional compiled languages like C, but interpreted languages like PHP or Python that cache the compiled bytecode), then what is executed is the compiled results, so things like shorter variable names won't make any difference to what actually runs. And obviously if you run JavaScript through a minifier, then the length of the source code isn't going to be as much of an issue.
This is not necessarily true. In Javascript, using Array.forEach() might result in smaller code but it is not as performant as a for loop. Since the argument to forEach() is a function, you have the overhead of a function call in each iteration. I would also argue that the code for using forEach() is less readable than a simple loop.
One thing I've noticed in myself is that it's very easy to intuitively think that shorter code does less and therefore performs better. And even when we should know better, writing a short one-liner in a scripting language sometimes just feels like a lot less is happening, than writing the equivalent code in a lower-level language.
To me this is specially apparent when I go back and forth between writing Ruby and Lua; where a snippet of code feels good in Ruby, because it's easy to express, but in Lua it feels terrible, because I often have to first implement stuff that Ruby does out of the box, so I get to actually see all the performance implications some code has.
Suddenly, calling a method can become looping over ancestor classes, doing a hash lookup for each of them and ultimately calling the subroutine.
As for readability, it's hard to say. People sometimes obsess over brevity, and I think it's not a bad thing in general. As you start shortening code, it often becomes more readable at first, until you reach a tipping point where shortening the code further ends up making it less readable again.
Generally speaking, if your code looks complicated, long and messy, it's almost always one of two cases:
1) Your code is more complex than the inherent complexity of the problem and you should probably work on simplifying it further, so it becomes clear what it does to someone who understands the task it's trying to solve.
2) The problem you are trying to solve is inherently very complex, and reducing the code further would just hide the complexity by spreading it around arbitrary abstractions that don't really help much. In this case, the best solution is usually to add comments explaining how the code reflects the solution.
Keep in mind though, that most online coding exercises will rarely have problems that fit into category 2, for a variety of reasons.
I'd say shorter as long as it's readable.
Simple example:
can be simplified to
=> shorter but still highly readable.
If you have a highly optimized piece of code inside a function with a good name then it's totally fine.
Example from "Perl Golf" of a short but difficult to read one-liner:
It cannot be shorter but it cannot be less explicit either. Put it inside a
printFibonacciNumbers
function and it becomes clearer.Your short code is backwards. It should be:
Indeed. I changed my mind mid post and forgot to update. Thanks!
As long as it's not sacrificing readability, it's ok. However, readability can depend on the conventions of the language.
Perl is an interesting example. The language is very terse and if you're not familiar with the language it's hard to follow. However, once you understand the relevant parts, such as the use of the default variable and the reliance of regexes for string handling it makes perfect sense.
Is soup made from a soup-starter better soup than soup created from raw ingredients?
"better" is always relative.
If I want to impress my inlaws I will make my own soup.
If I need to feed 3 hungry children tonight, I will use a soup-starter
I recommend better code.
Shorter code is not important. The most important thing is scalable, readable, well-optimized.
Even though the code is short, if its performance is bad, it's just useless code.
it depends on the definition of 'shorter'. is it just lines of code? for instance, would you consider:
to be 'shorter' than
even though it's the exact same number of statements?
i think counting lines of code is always a dangerous metric. i can easily (and, , often do) write very terse code that is difficult for others to read. there are better measures of complexity, ie 'cyclomatic complexity' (which isn't great. but is still better than just counting lines)
blog.ndepend.com/understanding-cyc...
Better for what? Unless you specify that, the question is too ambiguous to allow for a useful answer.
For smaller bundle sizes? Definitely. For performance? Depends. For maintainability? There's a sweet spot before maximal conciseness, where you put at most three functionalities in one line, so they could be understood in a normal reading flow.
As a rule of thumb, if you need to comment the what and not the why to make the code understandable, you're beyond that sweet spot. Only go there if it is a required optimization.
From a real life example, I once wrote a lease tracking module for an accounting package right after suffering a horrible injury. I was taking a great deal of morphine at the time that I wrote the core of the calculation engine. Turns out it was a single line of code. It passed every test I threw at it, could calculate lease interest and payments out to fifty years to 5 decimal places.
To this very day, I still have no idea how the f*ck it works...
Oh wow, that is amazing! 😲 Thank you for sharing with us!
Some comments have been hidden by the post's author - find out more