DEV Community

Discussion on: How has your opinion on "clean code" changed throughout your career?

Collapse
 
avalander profile image
Avalander • Edited

In my early years I had no idea that clean code was even a thing.

Then I started thinking about good variable names and short functions and those things that clean code prescribes without thinking too much about the reasons behind it.

Nowadays, I think more about keeping cognitive complexity low than clean code. Cognitive complexity tries to approximate how many things the reader has to keep in mind to understand a given piece of code. The fewer things to keep track of, the easier to follow the code.

A few things that I've found to reduce cognitive complexity:

  • Few intermediate variables: I have developed a distaste for intermediate variables, as they just clutter the scope and I need to keep track of them. I try to skip intermediate variables by composing functions instead of saving the output of a function to send it into another function. Also, when declaring a variable, I always put it in the smallest scope possible, and avoid mutating it as much as possible.
  • Composability: composable code is code that is made of smaller, independent parts that are composed together. Therefore, to understand a bigger part, I can look at the smaller parts independently and take it bit by bit. Much easier to understand a composition of ten pure functions than a 100-lines long function with a dozen and a half intermediate variables and several blocks of indentation.
  • Purity and referential transparency: there are two big dimensions that we need to keep track of when reading code. First, what is the code doing, and second, how have previous executions changed the internal state. A pure function will always yield the same output with the same input, so I don't need to keep track of what has happened before to see how it will affect the current execution.
  • Avoid/abstract conditional flow: ideally, there should be a single flow to follow. Multiple conditional statements, especially when nested, make it harder to understand what will be the output of a function. A conditional flow can be easily abstracted with Maybe and Either monads.
Collapse
 
elmuerte profile image
Michiel Hendriks

Keeping cognitive complexity low is part of clean code. Clean code isn't just about naming and formatting. It's also about sizes (method arguments, bodies, ...), control flow depth, etc.

Although proper naming also keeps cognitive comexity low. So both terms are highly co-related.