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?

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

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:]))

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.

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

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.

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.

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.

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.

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.

Julien Dephix • Edited

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

Simple example:

return empty(\$someVar) ? true : false;

can be simplified to

return empty(\$someVar);

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

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

gweinfurther

Your short code is backwards. It should be:

return empty(\$someVar);

Julien Dephix

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

π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.

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

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.

Craftingbugs

I have two perspective for this question,
In my field, while attempting coding question, shorter code help compiler to evaluate solution faster and allow user to lead ahead from others.

but from learning and understanding point of view, shorter code are not good at all.

For example:

if(i % 2 == 0) {
cout<<"Even number";
}
else {
cout<<"Odd Number";
}

who have shorter version like

return i % 2 == 0 ? "Even" : "odd";

Bernard

It could be even shorter:

return i & 1 ? "Odd" : "Even";

Anita Olsen

You got some very good points and provided some excellent examples there!

Shorter code isn't always better, but concise and readable code is often preferable.

While brevity can improve readability and comprehension by reducing clutter and unnecessary repetition, excessively terse code might sacrifice clarity. Code readability is crucial for maintainabilityβmaking it easy for others (or your future self) to understand, modify, and debug.

Igsem

not always, can you understand the purpose of the code easier than with longer code? Is it declarative or imperative, who are your colleagues etc. For example I believe functional style of programming is way easier to read but the first 6 months on a team who preferred functional style I was thinking what the hell is wrong with them :) ..so shorter reduces visual clutter and sometimes thats important as we developers usually focus on the story, what the feature does and not how a function is implemented but for a juniorish developer this is not true anymore

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

Anita Olsen

Oh wow, that is amazing! π² Thank you for sharing with us!

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;

to be 'shorter' than

if(\$j >= 1) {
\$j = 1;
}
else {
\$j = 0;
}

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

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.

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.

Giuliano1993

Clean and correct code is best. Shorter doesn't always is better; if you're writing some very short code, but after some time nor you or any of your colleagues can really say what it does, or you can tell but with a really bad headache born while trying, then that code is not so good even if it is really short.
I like writing short code too, but I always give priority to cleanliness, performance over shortness; that is a bonus!

Nashe Omirro

In the context of project size, I've recently been playing with classes and basic OOP with the upcoming update for svelte and one thing I noticed is that my code had become more and more robust, and consequently more larger and even a little overwhelming.

But quickly I realized it's not about how large the codebase becomes that makes a project better or worse, it's about how simple the whole structure of your application is, good encapsulation for each feature/part, and how those parts provide an intuitive API to communicate with other parts. Don't get me wrong though, a large codebase is still a large codebase and can unnecessarily be large for bad reasons.

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