DEV Community

Adrian Carter
Adrian Carter

Posted on

Open Discussion: What Tips Do You Have For Writing Clean Code?

Recently, I read an Article where the author, Jerry Low, suggested that developers write their CSS properties in alphabetical order. I think this is a great idea, and it got me thinking what some other tips for writing clean and readable code? Feel free to share your suggestions.

Latest comments (36)

Collapse
 
eecolor profile image
EECOLOR

My advise would be to ask the following two questions repeatedly after you are 'done' writing your code:

  1. "Can I do this with less code?"
  2. "Can I improve the readability / understandability of the code?"

If you repeat this often enough you will get to a point where these steps would remove and add the same piece of code. Stop at the more readable version.

The great thing about this cycle is that it scales with your experience and is applicable to all programming languages.

Collapse
 
generalvippp123 profile image
Generalvippp123

التكثيف من كتابة التعليمات البرمجة لتسهيل مهمه الباحث المهتم لعلم البرمجيات
واتمنى ان تكون الخيارات حاضرة لمساعدة المبتدئين في علم البرمجة شكرا لكم

Collapse
 
gass profile image
Gass • Edited

hmm.. I don't like that approach. I've never tried it but I feel like that would slow me down. I preffer modular and small css files. Another thing I like doing is using the id attribute to distinguish the different sections. So I can write styles like so #info_card .title which makes it easier to find the section I need to work in.

Collapse
 
mephi profile image
mephi

To me, a clean code rule has to be something that is worth the effort in the end.
I'm not that fast at alphabetical sorting, so I would take a lot of extra time and it would exceed the benefits it could provide.
My favourite type of sorting is the one my IDE does on autoformat.

 
jeremyf profile image
Jeremy Friesen

Borrow away!

 
jeremyf profile image
Jeremy Friesen

We're definitely coming at this from adjacent approach vectors. Namely: beware of rules and guidelines for the universe includes them but is not them.

Collapse
 
jcolag profile image
John Colagioia (he/him)

I have a simple, modest suggestion: Almost every programming ecosystem has tools (pretty-printers, code formatters, or code beautifiers, depending on how old your language is...) to enforce a style. Just do what they say for new code, instead of arguing about style. Don't like that style? Use the same tool, configured to whatever style that you would prefer to look at.

Seriously, after sixty years of code, we need to stop wasting time arguing over style preferences. Let cb, prettier, gofmt, rustfmt, or whatever do that thinking. The format doesn't matter, as long as everybody commits to the same standard. An exception, as hinted above: Leave the pre-beautifier code alone, until you need to change it. Nobody needs a ticket to automatically fix the indentation on a million lines of code written before they were born...

And then the time saved on arguing about format can go to fixing all the warnings that the linter keeps complaining about that you either don't know about because you're not running your linter, or have been ignoring because "it's only a warning."

 
jeremyf profile image
Jeremy Friesen

I have struggled for find the study/observation that I once read; the study/observations looked at teaching folks to code. They also wanted to minimize the number of guidelines for these new programmers. And they found that with the one guideline/rule of methods length many other best practices began to emerge.

Collapse
 
titowisk profile image
Vitor R. F. Ribeiro

Try to create a function with a readable name whenever you want to better describe a piece of logic on your code.
Also try to bring together code that are "speaking" about the same topic.

If you struggle in doing the above, write some comment to describe the code. I don't think 100% that the code should be self-documented, but I believe that we should try our best to avoid comments :)

Collapse
 
pinotattari profile image
Riccardo Bernardini

Writing CSS properties in alphabetical order? I fail to see how this can make the code clearer; maybe it helps when you are searching for a property, but Ctrl-F (or Ctrl-s if you are an emacsian) works fine too.

To me "clean code" means code that makes it easier to understand what its goal is and how it achieves it. In this respect, I find that using meaningful names for variables, functions, etc. helps a lot. Using some comment to explain the goal of the function, module, etc, and the "conceptual model" behind it helps a lot too (and this is a kind of comment that is unlikely to get stale, since it is related to the overall architecture). Comments explain the algorithm can be helpful if the algorithm is not trivial and/or to explain some choices that seem strange at first sight (e.g., "We use this structure instead of the more obvious ... because later we need to ...")

 
jeremyf profile image
Jeremy Friesen

A good writer knows the rules and when and why to break them.

Collapse
 
po0q profile image
pO0q 🦄 • Edited

To me, it's usually a triangle: Efficiency, readability, abstraction.
However, it's rarely the same distribution, as it can vary from one project to another, depending on the context. I can't give a general rule but this how I see the project in terms of clean code.

You can't neglect performances but you have to avoid micro-optimization, especially when the code becomes too "ninja", a.k.a. less readable and maintainable. If you're the only one who can modify the script, it can become a problem quickly.

Too much abstraction is not really good in my experience. It can jam code reviews significantly. Besides, you can get a lot of unwanted side effects, so more stress for maintenance, etc.

Collapse
 
taijidude profile image
taijidude • Edited

Imagine while coding the colleague who has to maintain the code after you is a violent psychopath who knows where you live. 😅

Collapse
 
gustavofsantos profile image
Gustavo Santos

About the article, I feel that is more personal taste than some pragmatic thing. There is a big difference between opinion (which everyone has) and well-known metrics such as SLOC, Cyclomatic Complexity and so on.

As tips, I suggest reading those books:

As a general rules of thumb that I like to follow:

  • Follow Tell, Don't Ask when possible, but not become too dogmatic about that
  • Law of Demeter is not a law, but it helps drive the code to a good and maintainable future
  • Start writing acceptance (e2e) tests, then write unit/integration tests, then write the code. This helps a lot organizing ideas and communication between the parts, without writing all the base classes upfront.
  • ReadMe driven development help organize what to do first and this impact directly to the code organization
  • Know your tools, this help you to use your tools to write your code.
  • Use dependency injection, even if it needs to be done in a manual way.
  • Write code for humans, not for machine.
  • (questionable taste) Switch/case isn't evil. Use it in factories to help to use polymorphism
  • (questionable taste) Do not put repeated prefixes or suffixes, like "UseCase", "I", "Service", "Entity" and so on (unless if needed to work, like the prefix use in React Hooks). Each object should tell a story, each object should deserve its place in the source code by the story that it tells, not by its name.
Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️
  1. Don't be lazy about typing. Abbreviations harm readability.
  2. Don't encode data in your control flow. switch/case is evil.
  3. Don't implement what you need right now. Think in abstracts.
Collapse
 
mephi profile image
mephi

I don't get the problem with switch case. Can you provide an example?

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

switch/case is often abused to express data that should be a map as control flow instead. Then people wonder why their code is so hard to extend.

Thread Thread
 
mephi profile image
mephi

Ok... but if I don't use Python, I can't put everything in a map.

Thread Thread
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

Yes, you can? What programming language doesn't support maps these days?