DEV Community

Cover image for 9 Must-Know Rules for Writing Clean Code

9 Must-Know Rules for Writing Clean Code

Saurabh Dashora on January 30, 2023

Are you tired of staring at a mess of code that even your cat wouldn’t touch? Look no further. In this post, I will tell you 9 rules to turn your ...
Collapse
 
fasaas profile image
fasaas • Edited

One quick reflection, if you need to write comments it means the code is not self explanatory. You should avoid writing comments because it means the code takes more to read and also comments can fall out of sync. The code should be the sole documentation of the logic.

Collapse
 
pilcrowonpaper profile image
pilcrowOnPaper • Edited

Self documenting code is a lie. Documentation isn't just about explaining what the code does, it's for explaining the "why" part as well. Why is this code needed, why is this implementation better than other solutions?

Also, if you're implementing an algorithm, it's usually a good idea to comment the algorithm name, links how it works, and maybe some quick notes on it.

Collapse
 
dashsaurabh profile image
Saurabh Dashora

A really valid point! Documentation can be utilized in quite useful ways.

Collapse
 
tinussmit profile image
Tinus Smit

I agree. The mere fact that there's nothing compelling the developer to update the comment when the code changes means it will mostly go out of sync as time and developers move on. This doesn't mean there should be no comments at all. But I treat commenting more like an apology. Allow me to explain...

An apology for:

  • A specific hack / workaround that needed to be implemented.
  • A complex piece that's hard to break down into smaller parts.
  • Potential side-effects that might occur when changing this bit of code.

Notice how all of the reasons are around less-than-ideal bits of code? One doesn't always have the luxury of starting from a clean slate, and even more often you're extending someone else's legacy code. Often times you also don't have the time available to "fix it properly", so you have to make do with what you have.

Collapse
 
dashsaurabh profile image
Saurabh Dashora

Hi Tinus, A really nice perspective on the debate about code commenting...thanks for bringing it up

Collapse
 
luisferfranco profile image
Luis F. Franco

As with almost anything... it depends. In most cases I completely agree with you, but sometimes business logic is so complex (maybe "strange" would be a better word than complex) that you NEED to add comments

Collapse
 
dashsaurabh profile image
Saurabh Dashora

Yes...i have also found that to be the case many times..."strange" is the right word and that's when I feel a quick comment can add a lot of value...

Collapse
 
siwhelan profile image
Simon Whelan

What you may think is ‘self-explanatory’ might make no sense at all to someone else. Comments allow more seamless work between groups.

Collapse
 
thexdev profile image
M. Akbar Nugroho

It's remind me 3 years ago. Even when you think it's "self-explanatory", but after one years, I believe you can't understand what the codes mean.

Collapse
 
dashsaurabh profile image
Saurabh Dashora

yes...i have seen that type of code...made perfect sense to the one who wrote it...but not so much to the others

Collapse
 
dashsaurabh profile image
Saurabh Dashora

I believe sometimes it is also a matter of following the conventions of the team or product...but yes, if you are getting a chance to start a blank-slate project, it's better to avoid comments

Collapse
 
syeo66 profile image
Red Ochsenbein (he/him)

I think no and redundant comments are bad. Write readable code and add comments about why the code exists when needed.

Thread Thread
 
dashsaurabh profile image
Saurabh Dashora

Nice point...adding comments should be the last resort unless your job is on the line bcz of some sort of team culture that i have seen in certain orgs :)

Collapse
 
pierrewahlberg profile image
Pierre Vahlberg • Edited

Another reeeeelly strong point for enums/constants instead of harscoded values is how well it reads. This together with pure functions is a huge win. Compare these examples (and notice how comments arent needed.. 😏)

// poor
const total = cartItems.map( p => p.price × 1.25);

// better
const taxRateFactorial = 1.25;
const cartTotal = cartItems.map( product => product.price × taxRateFactorial);

// More readable option

// clear constant name intent
const TAX_RATE = 0.25;

// use of pure functions
function getTaxesForPrice( price: number) {
  return price × TAX_RATE;
}
function addTaxesToPrice( price: number) {
   return price + getTaxesForPrice(price);
}
function getProductPrice(product) {
    return product.price;
}

// actual logic reads well and is easy to follow without comments

const products = cartItems; 
const prices = products.map(getProductPrice);

const totalIncludingTaxes = prices.map(addTaxesToPrice);

Enter fullscreen mode Exit fullscreen mode
Collapse
 
mickmelon profile image
MickMelon

Nice article. I couldn't agree more about the important of writing clean code. It goes a long way in making the code easier to understand and maintain, even when you are the only one working on the project.

I'd also add that consistency is better than correctness. If you are coming onto a well-established project, then you should follow the existing code styles and conventions, even if there are no specific guidelines. If every developer follows their own preferred coding style, then it could quickly lead to confusion and reduce overall code quality.

Collapse
 
dashsaurabh profile image
Saurabh Dashora

Absolutely agree with your point! Following project conventions is very important. Changes, if needed, should be brought in over time with a proper agreement...

Collapse
 
arsalannury profile image
ArsalanNury

hi 😊👋 thanks for sharing this great article.

Collapse
 
jhelberg profile image
Joost Helberg

Grouping (#1) should be based upon abstraction level. Further, code is a byproduct of the documentation (what why, how), see literate programming.

Collapse
 
harryrefact profile image
Makarov

There are tools that help you write good, unique code. Use AppRefactoring or Sourcery AI