Jump to content

Code readability vs length

Hi P
Go to solution Solved by DevBlox,

I definitely prefer readable over short. You end up reading it faster than trying to decipher something. Also, nasty stuff can hide in the complexity, which you will not notice one day or another and bork something (legacy code like that with no unit tests is a "blessing"). Short and readable is ideal (and often possible), but otherwise, definitely readable. I second @trag1c, if you do something disposable/one-off it does not matter one bit if it's beautifully crafted.

I'd like to read your input on this :)

 

On one hand I've seen code in YouTube videos and books that were short but so messed up to understand... but then again they were short, though on the other hand I've read articles about how code readability is important, as explicit and obvious as possible, so which one would you prefer?

 

Which would you rather read:

- 35 lines of cryptic code

- 100 lines of explicit code

 

It's a serious question, because there are actually pros and cons, for example, while cryptic code might be messed up to understand it would still be fewer lines, isn't it? whereas you could get lost in hundreds of lines of explicit code.

Link to comment
Share on other sites

Link to post
Share on other sites

Ultimately depends on the context of the situation for me. If i am going to reuse code at any point i will spend the time to do it right and make it maintainable. If its a one off piece that i am not going to touch again I will make the most hacked together nastiest code in the shortest time possible. Basically fire and forget.

 

But regarding amount of lines it should be documented regardless or the code should document it self. Doesn't matter if 15 lines or 15000 comments exist in languages for a reason...

CPU: Intel i7 - 5820k @ 4.5GHz, Cooler: Corsair H80i, Motherboard: MSI X99S Gaming 7, RAM: Corsair Vengeance LPX 32GB DDR4 2666MHz CL16,

GPU: ASUS GTX 980 Strix, Case: Corsair 900D, PSU: Corsair AX860i 860W, Keyboard: Logitech G19, Mouse: Corsair M95, Storage: Intel 730 Series 480GB SSD, WD 1.5TB Black

Display: BenQ XL2730Z 2560x1440 144Hz

Link to comment
Share on other sites

Link to post
Share on other sites

I definitely prefer readable over short. You end up reading it faster than trying to decipher something. Also, nasty stuff can hide in the complexity, which you will not notice one day or another and bork something (legacy code like that with no unit tests is a "blessing"). Short and readable is ideal (and often possible), but otherwise, definitely readable. I second @trag1c, if you do something disposable/one-off it does not matter one bit if it's beautifully crafted.

Link to comment
Share on other sites

Link to post
Share on other sites

3 hours ago, Hi P said:

Which would you rather read:

- 35 lines of cryptic code

- 100 lines of explicit code

Depends on the language.

Write in C.

Link to comment
Share on other sites

Link to post
Share on other sites

while its definitly fun to shorten a complete function into a single line i have to say i prefer the longer version. 

i write mostly c#

its just more readable and IDEs like Visual Studio offer you to collapse any and all structures you want to so i write it all out and then just collapse the if clause or whatever have you so i dont have to look and scroll through the whole thing all the time.

also theres no trophy for using the least lines

so i go for reabability as much a possible. also more lines can also be a neccessary eil for better performance sometimes.

 

"You know it'll clock down as soon as it hits 40°C, right?" - "Yeah ... but it doesnt hit 40°C ... ever  😄"

 

GPU: MSI GTX1080 Ti Aero @ 2 GHz (watercooled) CPU: Ryzen 5600X (watercooled) RAM: 32GB 3600Mhz Corsair LPX MB: Gigabyte B550i PSU: Corsair SF750 Case: Hyte Revolt 3

 

Link to comment
Share on other sites

Link to post
Share on other sites

Short code doesn't necessarily mean fast code, and making code shorter isn't beneficial in itself (shorter code can be more understandable, or it can be faster, but on its own it isn't necessarily either of those).

 

Readability and clarity are usually the most important things when writing code that you will ever want to maintain, so I would lean towards slightly longer code where necessary. It is occasionally necessary to optimise some code (for performance) as much as possible, in which case making it less clear but adding clarifying comments is a valid solution too.

 

If you're just writing a one-off script though, it doesn't matter how long the code is, just that it works, so just write the first (correct) thing that you come up with.

HTTP/2 203

Link to comment
Share on other sites

Link to post
Share on other sites

If the programmers have to spend an hour working out what stuff does every time they fix a bug it's not a good situation. However your programmers should also be able to quickly see what basic "short code" does as well. It's a fine line to find the best solution.

 

For example a programmer should be easily able to read:

 

variable = (cash >= 0) ? "no kids 3 money" : "no money 3 kids";

as

if (cash >= 0)
{
   variable = "no kids 3 money";
}
else
{
   variable = "no money 3 kids";
}

without any issues at all.

 

If that's the sort of thing we are talking about then yes, shorter code is better, but only in simple situations like this. If the conditional statement was more than calling one function or performing one assignment then it should be the full fat version.

 

If we are talking about the people that would write "short code" by doing:

 

if (cash >= 0) { variable = "no kids 3 money"; } else { variable = "no money 3 kids"; }

Then, well, you need a PFY branded cattle prod in your desk. 

Link to comment
Share on other sites

Link to post
Share on other sites

4 hours ago, Hi P said:

Which would you rather read:

- 35 lines of cryptic code

- 100 lines of explicit code

Depends, would the app be open source. If not I would chose the easiest one, If it is 100 lines of explicit code would be best I say

Link to comment
Share on other sites

Link to post
Share on other sites

1 hour ago, FlappyBoobs said:

If we are talking about the people that would write "short code" by doing:

 


if (cash >= 0) { variable = "no kids 3 money"; } else { variable = "no money 3 kids"; }

Then, well, you need a PFY branded cattle prod in your desk. 

A person does this once, ok no biggie. He does it everywhere then he will obviously be fingerless the next day for sure ?

 

6 hours ago, Hi P said:

Which would you rather read:

- 35 lines of cryptic code

- 100 lines of explicit code

I does depend on to many factor to me. But the biggest factor are the language and what this method does.

 

Language is simply because some have very clear small, short and sweet instruction they are both readable and short.

Those i obviously don't want to see longer than needed code.

 

And based on what the methods does or what it's purpose well that depend on other factors. Is this method called 1.5 millions times or need uther most performance because that's the bottleneck. If the answer is yes then i don't care for shorter code as long as it perform better. Less assignation, playing with variables, less cpu cycle and memory footprint will win. If the code is more complex and has many manipulation i prefer more explicit as it's most likely a place we will tweak often so having it split into actual steps clear as day is more suitable.

Link to comment
Share on other sites

Link to post
Share on other sites

8 hours ago, Hi P said:

It's a serious question, because there are actually pros and cons, for example, while cryptic code might be messed up to understand it would still be fewer lines, isn't it? whereas you could get lost in hundreds of lines of explicit code.

No, because you'd split up the "hundreds of lines" into more functions still, each of which is small and manageable. And you'll find lots of the complexity magically disappears. Whereas cryptic code will always be cryptic by definition.

Link to comment
Share on other sites

Link to post
Share on other sites

10 hours ago, Hi P said:

Which would you rather read:

- 35 lines of cryptic code

- 100 lines of explicit code

The former implies you're trying to be smart with code and doing optimizations by hand. Something the compiler is supposed to do.

 

I live with the philosophy that you don't write code in a way that computers understand what you want it to do. You write code in a way that other humans can understand what you want the computer to do.

Link to comment
Share on other sites

Link to post
Share on other sites

22 hours ago, Hi P said:

Which would you rather read:

- 35 lines of cryptic code

- 100 lines of explicit code

 

 

 

What you think is "explicit" someone else would call "cryptic", and vice versa, since how you write code depends A LOT on your level of experience and expertise. How I write code would be "cryptic" to those fresh out of college or otherwise new to programming or who just don't know the language and its concepts as well as they should to be working with the code they're trying to modify.

 

The best way to increase your reading speed is by reading more. If you want to learn a foreign language, you need to immerse yourself in it. The best way to make all code in a language less cryptic is by reading and writing more code in that language. Generally the more experience you have, the more likely you are to take advantage of advanced language and framework features that someone else may not understand all that well. So, then,  should one write code to the "least common denominator" programmer who might modify it? I don't think one should. As you learn the advanced techniques largely to save time and produce more stable code.

 

If you find code to be "cryptic", that's likely your inexperience lending itself to that interpretation. For example, I find Perl cryptic. But I never use it. And don't understand why anyone would want to. Someone who works with Perl on a regular basis, however, would have a much easier time than someone who works with it very little. The same with every other language, including assembler.

Wife's build: Amethyst - Ryzen 9 3900X, 32GB G.Skill Ripjaws V DDR4-3200, ASUS Prime X570-P, EVGA RTX 3080 FTW3 12GB, Corsair Obsidian 750D, Corsair RM1000 (yellow label)

My build: Mira - Ryzen 7 3700X, 32GB EVGA DDR4-3200, ASUS Prime X470-PRO, EVGA RTX 3070 XC3, beQuiet Dark Base 900, EVGA 1000 G6

Link to comment
Share on other sites

Link to post
Share on other sites

14 hours ago, Unimportant said:

No, because you'd split up the "hundreds of lines" into more functions still, each of which is small and manageable.

Oh if only that were actually true in the real world.

 

Sometimes you just don't really have the time to be able to do that. I can't tell you how many times I've seen conditional statements - not methods, but one conditional statement - that was a lot longer than it needed to be. And it just kept getting added to because that was the easiest and quickest way to implement what was being requested. Either because the code originated from a time when more advanced features didn't exist, and no one wanted to refactor it to use the more advanced language features, or because someone was either just being lazy or didn't know any better.

 

And then, yeah, there are the methods that are far longer than they need to be. That really should be broken up into other methods. But then there's the risk of actually doing that - "if it ain't broke, don't fix it". Since you risk introducing bugs doing that if you don't do it right. And then there's also the time that'll be spent that you'll need to sell to management as worthwhile before you start...

 

Things are definitely far from ideal...

Wife's build: Amethyst - Ryzen 9 3900X, 32GB G.Skill Ripjaws V DDR4-3200, ASUS Prime X570-P, EVGA RTX 3080 FTW3 12GB, Corsair Obsidian 750D, Corsair RM1000 (yellow label)

My build: Mira - Ryzen 7 3700X, 32GB EVGA DDR4-3200, ASUS Prime X470-PRO, EVGA RTX 3070 XC3, beQuiet Dark Base 900, EVGA 1000 G6

Link to comment
Share on other sites

Link to post
Share on other sites

21 minutes ago, brandishwar said:

Should one write code to the "least common denominator" programmer who might modify it? I don't think one should.

Got you, that's actually an interesting point of view :)

 

For me Yurizaki's comment made a lot of sense:

"You write code in a way that other humans can understand what you want the computer to do."

 

Wouldn't that be the ideal thing to do?
Is that far from being the case in real world jobs?

Link to comment
Share on other sites

Link to post
Share on other sites

More than anything, the code should be optimized for performance and modularity, with plenty of documentation. I used to make lots of applications for the Wii. While I was never a great programmer, I was pretty good at optimizing and organizing code. Since most projects in the community were open source, most of my work was in cleaning up sloppy projects, as well as documenting functionality in case someone else wanted to jump in and further improve on the work.

Make sure to quote or tag me (@JoostinOnline) or I won't see your response!

PSU Tier List  |  The Real Reason Delidding Improves Temperatures"2K" does not mean 2560×1440 

Link to comment
Share on other sites

Link to post
Share on other sites

34 minutes ago, Hi P said:

Wouldn't that be the ideal thing to do?
Is that far from being the case in real world jobs?

 

If you have the time to do it the "ideal" way, then obviously you should. If you don't, then you have to sacrifice the ideal for what works within the time frame you have.

Wife's build: Amethyst - Ryzen 9 3900X, 32GB G.Skill Ripjaws V DDR4-3200, ASUS Prime X570-P, EVGA RTX 3080 FTW3 12GB, Corsair Obsidian 750D, Corsair RM1000 (yellow label)

My build: Mira - Ryzen 7 3700X, 32GB EVGA DDR4-3200, ASUS Prime X470-PRO, EVGA RTX 3070 XC3, beQuiet Dark Base 900, EVGA 1000 G6

Link to comment
Share on other sites

Link to post
Share on other sites

11 hours ago, Hi P said:

Wouldn't that be the ideal thing to do?

Is that far from being the case in real world jobs?

My philosophy is born from this: the whole point of software is to make tools that people use. If the tool doesn't work, nobody cares. They're going to go to someone else who does have a working tool.

 

Part of what works is not only making sure the software is error-free as possible when running, but error-free as possible when developing. If it's hard to maintain the software or understand what it's doing because it was written in a way that isn't intuitive, then you're just making it harder for the next person who's has to touch the code. And often times, the next person is you. And just because you wrote it, doesn't mean a month or two from then  you'll remember exactly what was going on.

 

Once you prove your design works, then you can worry about making improvements on the performance end. And even then, you should be aware of what's actually an improvement and what appears to be an improvement and instead is actually worse: https://devblogs.microsoft.com/oldnewthing/20041216-00/?p=36973

Link to comment
Share on other sites

Link to post
Share on other sites

12 hours ago, brandishwar said:

Oh if only that were actually true in the real world.

 

Sometimes you just don't really have the time to be able to do that. I can't tell you how many times I've seen conditional statements - not methods, but one conditional statement - that was a lot longer than it needed to be. And it just kept getting added to because that was the easiest and quickest way to implement what was being requested. Either because the code originated from a time when more advanced features didn't exist, and no one wanted to refactor it to use the more advanced language features, or because someone was either just being lazy or didn't know any better.

 

And then, yeah, there are the methods that are far longer than they need to be. That really should be broken up into other methods. But then there's the risk of actually doing that - "if it ain't broke, don't fix it". Since you risk introducing bugs doing that if you don't do it right. And then there's also the time that'll be spent that you'll need to sell to management as worthwhile before you start...

 

Things are definitely far from ideal...

Perhaps I expressed myself poorly.

 

What I meant was that I feel it's impossible to have a block of hundreds of lines of code that is clean and elegant.

It's the splitting up of things into functions and creating abstractions, in the process naming things, that's the main thing what makes code clean, elegant and readable.

 

Imagine having a function with 25 lines of code that pulls something from a database, then 20 lines of code that mutates the thing and then another 20 lines that put it back.

Even when written properly and without any clever tricks, that probably still looks pretty cryptic at first glance and might take a bit of time just to figure out you're doing three things. It's when you split things up and name them that it becomes readable:

auto employee = RetrieveFromDB(key);
employee.SetAddress(newAddress);
SaveToDB(employee, key);

And in each of these three functions you do the same, until - as you'll often find - the complexity magically goes away.

 

The concepts are inseparable. So to me, there is no choice. It's either "cryptic" or it's easily readable, and the latter implies small and manageable pieces/abstractions.

 

As for "having no time". I've found it to be a bogus argument. Doing it correctly actually saves you time. You create functions and useful abstractions and after a while you'll find yourself re-using them over and over.

For example - while writing code to draw a grid you might create a "StepValue<T>" class that takes a "from", "to" and "stepSize" - which as can be gathered from the names with no comments required - steps a value from some start value to some destination value. And before you know it you'll find yourself re-using that thing throughout the entire application because it's something that's done surprisingly often.

 

It also saves on debugging because once the "StepValue<T>" class is tested and bug free it's bug free, no matter how many times you reuse it.

Link to comment
Share on other sites

Link to post
Share on other sites

All code that I have (shy of "why the hell is this not working.... " quick if/stop/breakpoint/debug outputs that look like crap but are obviously there for that), has comments and is named so you at least know what it's for.

 

This is actual "Debugging code for a test app" that I have:

            // Debug code
            WMICalls wmi = new WMICalls();
            string[] servers = ConfigurationManager.AppSettings["servers"].ToString().Split(',');
            for (int i = 0; i < servers.Count(); i++)
            {
                wmi.GetDriveFreeSpace(WMIModules.Win32_LogicalDisk, servers[i].Trim(' '));
            }
            wmi.SendMail("myemail@mydomain.com");

Inside the script I have functions called "AddToBody" (for the e-mail body--but there's only one body, and it's a variable, so obvious).

 

Now shy of one program that has a class of over 2000 lines (that makes 2 pdfs that is a mission critical app--so it's a bit harder to "clean up" as it doesn't follow my current module-based function for reusable code--it STILL does in an extent.  But it's a {insert word of choice} trying to figure out what lines do, even with commenting just because it's a cluster of calculaations of cross-database values modifying locations on a pdf, calling multiple classes.... Basically it was a "test program" that "omg it works like we want!" and ended up being live.... so... yea... don't recommend that happening.

 

But you get the point hopefully.  

Link to comment
Share on other sites

Link to post
Share on other sites

It is harder to debug code than it is to write it.

 

Therefore if you right the smartest code you are capable of writing, you are not capable of debugging it.

To quote "The Zen of Python":

Quote

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.

 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×