DEV Community

Cover image for Is Shorter Code, Better Code?
Anita Olsen
Anita Olsen

Posted on

Is Shorter Code, Better Code?

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)

Collapse
 
kurealnum profile image
Oscar

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.

res = 0
for i in range(len(points) - 1, 0, -1):
       y_diff = abs(points[i][1] - points[i - 1][1])
       x_diff = abs(points[i][0] - points[i - 1][0])
       res += max(y_diff, x_diff)
return res
Enter fullscreen mode Exit fullscreen mode

And here's a version that runs a little bit faster due to inbuilt functions, but is much less readable:

return sum(max(abs(x1-x2), abs(y1-y2)) for (x1, y1), (x2, y2) in zip(p, p[1:]))
Enter fullscreen mode Exit fullscreen mode

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.

Collapse
 
janmpeterka profile image
Jan Peterka

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).

Collapse
 
montyharper profile image
Monty Harper

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.

Collapse
 
anitaolsen profile image
Anita Olsen

That sounds right. I have also heard people talking about efficiency, that shorter code means higher efficiency but I do not know about that.

Collapse
 
montyharper profile image
Monty Harper

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.

Collapse
 
matthewbdaly profile image
Matthew Daly • Edited

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.

Collapse
 
gweinfurther profile image
gweinfurther

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.

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

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.

Collapse
 
joolsmcfly profile image
Julien Dephix • Edited

I'd say shorter as long as it's readable.

Simple example:

return empty($someVar) ? true : false;
Enter fullscreen mode Exit fullscreen mode

can be simplified to

return empty($someVar);
Enter fullscreen mode Exit fullscreen mode

=> 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:

$a=1;print$a-=$b+=$a*=-1,$/for 0..31
Enter fullscreen mode Exit fullscreen mode

It cannot be shorter but it cannot be less explicit either. Put it inside a printFibonacciNumbers function and it becomes clearer.

Collapse
 
gweinfurther profile image
gweinfurther

Your short code is backwards. It should be:

return empty($someVar);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
joolsmcfly profile image
Julien Dephix

Indeed. I changed my mind mid post and forgot to update. Thanks!

Collapse
 
matthewbdaly profile image
Matthew Daly

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.

Collapse
 
dannyengelman profile image
Danny Engelman

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

Collapse
 
aidenwong812 profile image
aidenwong812

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.

Collapse
 
gbhorwood profile image
grant horwood

it depends on the definition of 'shorter'. is it just lines of code? for instance, would you consider:

$j  = $j >= 1 ? 1 : 0;
Enter fullscreen mode Exit fullscreen mode

to be 'shorter' than

if($j >= 1) {
    $j = 1;
}
else {
    $j = 0;
}
Enter fullscreen mode Exit fullscreen mode

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...

Collapse
 
lexlohr profile image
Alex Lohr

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.

Collapse
 
crazycga profile image
James

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...

Collapse
 
anitaolsen profile image
Anita Olsen

Oh wow, that is amazing! 😲 Thank you for sharing with us!

Some comments have been hidden by the post's author - find out more