How To Reduce Cyclomatic Complexity: A Complete Guide
Software engineers are always looking for ways to improve their code. Fortunately for them, there is a reliable way to gauge the health of a codebase and project, and that is through the use of metrics. Today’s post is all about one particular metric. You will learn how to reduce cyclic complexity and more importantly why you want to do it. We’ll start by defining the cyclic complexity. Then you’ll learn what the problem with having a high cyclic complexity value is and why you need to reduce it. After the “what” and the “why”, we finally come to the “how”: We will show you the tactics you can adopt to reduce the cyclical complexity of your code friend. Let’s start. Read: how to reduce cyclic complexity
Cyclomatic Complexity: A Brief Definition
Contents
Cyclomatic complexity is an important software metric. It refers to the number of possible execution paths within a given piece of code — for example, a function. The more decision structures you use, the more possible branches for your code. For example, by calculating the cyclic complexity of a function, you know the minimum number of test cases that you will need to achieve the full branch coverage of that function. So we can say that cyclic complexity can be a prediction of how difficult it is to test a given piece of code.
An example of dead simple Cyclomatic complexity
Consider the following function written in pseudocode: void sayHello (name) {print (“Hello, ${name}!”); } Since it has a single statement, it’s easy to see its cyclic complexity of 1. Now, let’s change things up a bit: void sayHello (name, sayGoodbye = false) { print ( “Hello, ${name}!”); if (sayGoodbye) {print (“Goodbye, ${name}!”); }} The second version of the function has a branch in it. The function caller can pass real as value for say goodbye parameter, although the default value is wrong. If that happens, the function prints a goodbye message after saying hello. On the other hand, if the caller does not provide a value for the parameter or chooses wronggoodbye message will not be displayed.
Why is Cyclomatic Complexity Bad?
In essence, cyclical complexity is not bad. For example, you might have a piece of code with a somewhat high value of cyclic complexity, which is super easy to read and understand. In general, however, we can say that having high cyclical complexity is either a symptom of problems with the codebase or a potential cause of future problems. Let’s cover some of the reasons why you want to reduce it in more detail.
Cyclic complexity may contribute to cognitive complexity
Cognitive complexity refers to how difficult it is to understand a certain piece of code. Although not always, cyclical complexity can be one of the drivers of cognitive complexity. The higher the perceived complexity of a piece of code, the harder it is to navigate and maintain.
Cyclic complexity makes code harder to test
Read more: fallout 4 ways to change resolution | In the top Q&AAs we mentioned, higher cyclic complexity values lead to the need for a higher number of test cases to comprehensively test a block of code — for example, a function. So if you want to make your life easier when writing tests, you might want to reduce the cyclical complexity of your code.
Cyclic complexity contributes to increased defect risk
You are more likely to introduce defects to an area of the codebase that you change than an area you rarely touch. Also, the more complex a certain piece of code is, the more likely you are to misunderstand it and give it an error. . By reducing cyclic complexity — and ideally, obfuscated code as well — you minimize those risks.
How to reduce Cyclomatic complexity: 6 practical ways
We will now look at some practical tips that you can use to ensure the cyclical complexity of your code is as low as possible.
Prefer smaller functions
What must you do? All else being equal, smaller functions are easier to read and understand. They are also less likely to contain errors due to their length. If you don’t have a lot of codes, you don’t have much chance for error codes. The same reasoning applies to cyclical complexity: You’re less likely to have complex code if you spend less time coding it. So the advice here is to prioritize smaller functions. Doing? For each function, define their core responsibilities. Extract what’s left for functions and their own modules. Doing that also makes code reuse easier, which is a point we’ll revisit soon.
Avoid flag argument in function
What must you do? Flag arguments are boolean parameters that you add to a function. People often use them when they need to change the way a function works while keeping the old state intact. In short, you can use strategies that achieve the same result without high complexity. For example, you can create a new function, keep the old function, and extract the common parts into its own function. to utilize decorative pattern to achieve the same purpose.
Reduce the number of decision structures
You might consider this a no-brainer. If decision structures — especially if other and switch cases — are the causes of code having more branches, which is why you should reduce them if you want to keep cyclical complexity low. has just been seen that may contribute to the reduction in the number of if statement in your code. For example, instead of using flag arguments and then using a if to test you can use decorator pattern. Instead of using a switch case to look at multiple possibilities and decide which code to execute, you can leverage the strategy model. Sure, at some point in the code you’ll still need a switch box. After all, someone has to decide which actual implementation to use. However, that point becomes the only point in the code that needs that decision structure.
Remove duplicate code
What must you do? Sometimes you have functions/methods that do almost the same thing. Keeping both will increase the total cyclic complexity of your class or module. If you can limit your duplicate codes, you can limit complexity.
- extract common bits of code into their own dedicated methods/functions.
- Leverage design patterns – such as patterns – that encourage code reuse.
- extract common utility functions into packages — gems, npm modules, NuGet packages, etc. — that can be reused throughout the organization.
Remove obsolete codes
What must you do? There are many reasons why you should remove obsolete – i.e. dead – code from your application. For our context, suffice it to say it’s a “free” way to improve code coverage and reduce cyclical complexity. —And then delete it mercilessly.
Don’t reinvent the wheel
What must you do? Let a developer who has never written a function — or even several functions — do the first stone creation date format! It’s almost like a text transfer ritual. Writing simple code that copies the functionality your language’s standard library or your framework already provides is a surefire way to unnecessarily increase complexity. If the code is a debt, you just want to write the right amount of it. How to perform?
Reduce Cyclomatic Complexity, Increase Code Clarity
Cyclomatic complexity is one of the most valuable metrics in software engineering. It has important implications for code quality and maintainability, not to mention testability. High cyclical complexity can be both a signal of current problems and a predictor of future problems. So keeping the value of this metric under control is definitely something you want to do if you want to achieve a sane codebase. Keeping it under control is exactly what you learned with our post. Before parting, take a final note. Remember that no metric is a panacea when it comes to isolation. Often, what you really want to do is track and improve a group of metrics that, together, can give you a bird’s-eye view of the health of your team and your project. Best way to do that? Download LinearB demo.Read more: How to get centipedes out of your bedWant to improve process engineering and cut cycle times? Get started with LinearB today!
Last, Wallx.net sent you details about the topic “How To Reduce Cyclomatic Complexity: A Complete Guide❤️️”.Hope with useful information that the article “How To Reduce Cyclomatic Complexity: A Complete Guide” It will help readers to be more interested in “How To Reduce Cyclomatic Complexity: A Complete Guide [ ❤️️❤️️ ]”.
Posts “How To Reduce Cyclomatic Complexity: A Complete Guide” posted by on 2021-11-03 13:57:16. Thank you for reading the article at wallx.net