Refactor this method to reduce its Cognitive complexity

What you will learn here about SonarQube

  • Refactor this method to reduce its cognitive complexity
    1. What is Cognitive complexity?
    2. Why Cognitive complexity issue comes?
    3. How to solve Cognitive complexity issue?
    4. Refactor this method to reduce its Cognitive complexity example

Refactor this method to reduce its Cognitive complexity

Here we will try to understand what is cognitive complexity, why cognitive complexity comes, what we can do to solve cognitive complexity issue and example of refactor this method to reduce its cognitive complexity issue example.

What is Cognitive complexity?

Cognitive complexity means how difficult to understand your code. Higher the Cognitive complexity means more difficult is your code to understand and lower the Cognitive complexity means your code is easy to understand.

Why cognitive Complexity issue comes?

Cognitive complexity comes when your method or function code has more statements within another statements.
For example: ->(represents within)
if() -> if() -> for() -> if() and So on

How to solve Cognitive complexity issue?

Its very easy to solve the Cognitive complexity issue. First understand where Cognitive complexity issue comes and answer is Cognitive complexity issue always comes at the method level. Means if our method is too big and it has so many statements within the statements then only Cognitive complexity issue comes.

    Solution

  1. Always write method with maximum 20-25 lines of code
  2. And create small small method for each functionality to achieve your desired functionality

Refactor this method to reduce its Cognitive complexity example

Refactor this method to reduce its Cognitive complexity example is given below

1)In the below code I have so many statements within statements which is shown below
Refactor this method to reduce its Cognitive complexity example

2)The Cognitive complexity of above method is solved by creating small small methods which is shown below
Refactor this method to reduce its Cognitive complexity

You may also like...