DEV Community

Cover image for Is Shorter Code, Better Code?

Is Shorter Code, Better Code?

Anita Olsen on December 03, 2023

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

Collapse
 
juliuskoronci profile image
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

Collapse
 
rojre1979 profile image
Robert J. Regalado

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.

Collapse
 
pxlmastrxd profile image
Pxlmastr

As a Rust dev learning/switching to Go, I love to have shorter code. However, some of the biggest libraries have more readable functions. I believe that sometimes longer code is more readable, and is therefore maybe better. However, if you work by yourself, (like me) you like to have shorter development time because you know your code front and back.

Collapse
 
anilsingh profile image
Anil Singh

Not always, but it's often a good goal. Shorter code can be more readable and easier to maintain, but it shouldn't sacrifice clarity or efficiency. Aim for a balance between brevity and clarity, and always prioritize code that is easy for others (or yourself in the future) to understand.

Collapse
 
efpage profile image
Eckehard • Edited

Image description

Go, marry someone... It's just one bit:

YES or NO?

Probably the shortest code you can do.

Collapse
 
prsaya profile image
Prasad Saya

This only brings more questions.

I have read somewhere that a programming language's most basic constructs are the most efficient and the most reliable code. But, these constructs can be verbose (not short?) when compared to some "advanced" constructs.

So, what is the definition of better code? Readable and maintainable code, or performant code or code that can be written fast or the ones highly upvoted on certain programming forums?

Collapse
 
giuliano1993 profile image
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!

Collapse
 
kehoecj profile image
Clayton Kehoe

As long as the code is DRY it comes down to developer/project preference. Personally I find clever solutions that are shorter (like python lambda) much harder to maintain than their more verbose equivalents.

Collapse
 
geektrainer profile image
Christopher Harrison

Code is, ironically, read many more times than its written. It'll be read by other developers for code reviews, contributions, and bug fixes. It'll be read by you as you return to it to add new features and (of course) fix bugs. So the primary focus should be on readability.

Collapse
 
ben profile image
Ben Halpern

It depends 😄

Collapse
 
nasheomirro profile image
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.

Collapse
 
aatmaj profile image
Aatmaj

In my sense, more readable code is better code.

If you want to improve the compiler's efficiency for certain parts of code, then you can use techniques that shall speed up the operations, eg using inbuilt functions. The key here is to analyze those parts and optimize them only. Also if the optimization is going to reduce readability, then do add some useful comments to counter it.

But otherwise, for parts of code that don't need to be optimized, I feel the length of the code doesn't matter. It is not a metric that can be used to measure code quality or efficiency.

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Readability is subjective

Collapse
 
ryantjo profile image
ryantjo

In my experience, shorter code can be sweet, but it's not a golden rule. Clarity and readability matter too. Sometimes a bit of extra length can make your code way easier for others (or even future you) to understand.

Collapse
 
tandrieu profile image
Thibaut Andrieu • Edited

Yes, definitly. But not talking about condensing an "if" statement using ternary operator or small stuff like that. I'm talking about the overall software.

If you can have the same level of feature in 300 lines of code instead of 3000, the 300 lines version will be easier to read and to maintain.

I actually had a case where a 3000 lines service were completly rewritten into only 300 lines. 90% of the code were useless abstraction layer to travers before reaching the actual logic.

Never underestimate the cost of overengineering...

Collapse
 
codewithcaen profile image
CodeWithCaen

Code that does less is usually better. This means that you often want as few operations as possible as that reduces the overall logic and complexity. Something simple is usually something better than something complex. This does not mean that your lines of code should be physically shorter. Don't abbreviate variable names for example. That was useful many decades ago when people physically printed code out on paper and had to punch stuff on cards. We now have the luxury of being able to fit in descriptive names of variables, and extract helper functions to make code more readable.

But having the mindset that your code should contain as few characters as possible will just make it harder to understand as you and other people reading your need to guess what that weird abbreviated variable name is.

Collapse
 
anitaolsen profile image
Anita Olsen

You got some very good points there. Thanks!

Collapse
 
imri profile image
heyimsunflower

I wouldn't say so specifically;

I would rank readability higher than length most of the time. The best example would be that 1 liner leetcode question solution that nobody can understand besides who wrote it

Collapse
 
shubhadip_bhowmik profile image
Shubhadip Bhowmik

The debate on whether shorter code equates to better code is a nuanced one, and I believe it largely "depends on" the context and specific circumstances.

Shorter code indeed has its merits. It often leads to improved readability and maintainability, making it easier for developers to comprehend and modify. A concise codebase can also minimize the chances of bugs, reduce complexity, and enhance efficiency in terms of execution time and memory usage.

However, the pursuit of brevity shouldn't compromise readability or clarity. Sometimes, excessively compact code can sacrifice readability, making it challenging for others (or even yourself in the future) to understand its logic. This might result in reduced maintainability and hinder collaboration within a team.

Moreover, focusing solely on code length might divert attention from crucial aspects like robustness, scalability, and extensibility. A longer, well-documented code that's modular and adheres to best practices might serve the project better in the long run, despite its length.

EXAPUNKS illustrates the significance of optimizing code for performance, where shorter code often translates to fewer cycles. However, in real-world scenarios, the emphasis should be on striking a balance between brevity and clarity, ensuring that code remains understandable, maintainable, and efficient.

Hence, I'd say the quality of code shouldn't be solely judged by its length. It's about crafting code that meets requirements efficiently while being comprehensible and maintainable for the developers working with it.

What's your take on this intriguing topic?

Cheers,
Shubhadip Bhowmik

Image description

Collapse
 
mellen profile image
Matt Ellen-Tsivintzeli • Edited

do you read ".min.js" or ".js"?

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Shorter is objective, better is subjective.

From you description above, it seems like EXAPUNKS is aiming at faster, more efficient code, rather than 'shorter' code (which implies less source code). Maybe you're conflating shorter code with faster code?

Collapse
 
alaindet profile image
Alain D'Ettorre

Code that explains itself (at least to fellow programmers) is readable and mantainable, thus it is much better than clever code, short code or even performant code (given performance is not a strict requirement). The only requirements for me, given no other stricter requirements are given, are

  • Reduce cognitive load as much as possible
  • Simplicity is the ultimate sophistication (Leonardo da Vinci)
Collapse
 
cnastasi profile image
Christian Nastasi • Edited

Probably the game uses the number of iterations of your code as a metric in order to calculate a score for all the players.

And from a computational point of view, that's correct.
When you study algorithms at a Computer Science University, you learn that the quality of an algorithm depends on its efficiency in function of time and occupied space, in relation to the amount of input received.

The Big O notation is used to calculate mathematically which is better than which and compare each algorithm.

But from a programmer's point of view, not always an efficient algorithm means good design or good code.
There are a lot of code qualities, internal and external, that permit one to state if a code is good or not.

That is:

External Quality Characteristics: Correctness, Usability, Efficiency, Reliability, Integrity, Adaptability, Accuracy, and Robustness.

Internal Quality Characteristics: Maintainability, Flexibility, Portability, Re-usability, Readability, Testability, and Understandability.

And, unfortunately, measuring these qualities can be quite challenging.

Collapse
 
lnahrf profile image
Lev N.

Shorter as in syntax-wise? No. The number of characters in the code has nothing to do with it’s efficiency.

Collapse
 
anitaolsen profile image
Anita Olsen

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

Collapse
 
mrdulin profile image
official_dulin

Shorter code is better code while ensuring readability, maintainability, extensibility, and reusability

Collapse
 
bernardv profile image
Bernard

It could be even shorter:

return i & 1 ? "Odd" : "Even";
Enter fullscreen mode Exit fullscreen mode
Collapse
 
monkeyduzumaki10 profile image
NK

This might not always be true. Shorter code is fine as long as it's readable. If the code is short but looks cryptic and no one understands it at first glance, it is pointless to write shorter code.

Collapse
 
akobashikawa profile image
Rulo Kobashikawa • Edited

I think, first clean code is better code, then shorter clean code is better. If shorter code is not clean then it is not better.
And better for whom must be clear. For a developer, I guess.

Collapse
 
anitaolsen profile image
Anita Olsen

Well said! I agree with you!

Collapse
 
robsontenorio profile image
Robson Tenório

Legible code is better code. ✅

Collapse
 
abbasc52 profile image
Abbas Cyclewala • Edited

rather than short code, i believe simple code = better code.
you can write obfuscated code to make it short but if it is not simple, you will run into more issues.

Collapse
 
anitaolsen profile image
Anita Olsen

That makes perfect sense.

Collapse
 
saji37 profile image
Sajith Thomas • Edited

I will go with readable codes rather than choosing shorter codes :)

Collapse
 
vivek09thakur profile image
Vivek Thakur

It depends , if you can do something better with just 2 lines of code then why waste your time to do that same thing with 10 or more lines of code. Codes are not about quantity its about quality.

Collapse
 
anitaolsen profile image
Anita Olsen

True and I totally agree on that code is about quality!

Collapse
 
tellurovich profile image
Tellur

Thx bro

Collapse
 
console_x profile image
F. Güngör

it depends

Collapse
 
edisonpappi profile image
Edison Augusthy

Readable code == better code

Collapse
 
razahosyain123 profile image
Info Comment hidden by post author - thread only accessible via permalink
razahosyain

Latest Jobs in Pakistan where one can find new upcoming career opportunites 2024 from all top companies in Pakistan including multinational, private, government, NGOs,overseas and others. [Jobz pk](https://www.jobz.pk/) is Pakistans top job search website where job seekers can get access to latest jobs opportunites

Collapse
 
podxmas profile image
podxmas

woww

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