Often, when I look at code written by juniors, I see a lot of nested code. In this article, I’ll try to articulate why it is problematic and what to do instead.
Let’s look at a trivial example together:
This function is simple enough; it either receives an input, or it does not. As it stands, almost all of the code of this function is “protected” by an
if statement. That is, almost none of the code will execute if the condition is not met. If it isn’t, then there’s a single log statement to execute.
For such a simple function, this isn’t a big issue, but it is an issue nevertheless. Why?
Functions such as the previous one are problematic because they nest code that doesn’t need to be nested. Nested code is harder to read/understand.
Whenever you have the opportunity to remove needless nesting, do it, you’ll reduce the complexity of the code.
There’san interesting code quality metric called Cyclomatic Complexity that evaluates the complexity of a program based on the control flow graph. If there are no conditional statements / decision points, then the complexity is “1”, since there’s a single path through the code.
If there’s an
if, then there are now two different paths and the complexity rises to “2”. And if there’s a conditional statement or decision point within that
if, then the complexity goes up to “3”, etc.
So, fundamentally, the idea is that the less “nesting” there is, the less complex the code is. And, to me, less complex code is almost _always _a win, whether a function is small/simple or not.
The example that I gave may be trivial, but the principle already applies. The more complex parts of a codebase will certainly have two levels of nesting or more, leading to the infamous pyramid of doom. The same happens when you chain callbacks for example, so there are different occurrences of the same basic issue: as nesting levels increase, so does the complexity.
So what can we change to reduce the complexity of such code?
Tip: Both [TSLint_](https://palantir.github.io/tslint/rules/cyclomatic-complexity/) and [ESLint_](https://eslint.org/docs/rules/complexity)_ have built-in rules that can check the cyclomatic complexity of your code, so make sure that those are enabled._
With the rapid development in technology, the old ways to do business have changed completely. A lot more advanced and developed ways are ...
You name the business and I will tell you how web development can help you promote your business. If it is a startup or you seeking some...