From the course: Agile Software Development: Code Quality

What is complexity? - SonarQube Tutorial

From the course: Agile Software Development: Code Quality

Start my 1-month free trial

What is complexity?

- [Instructor] Complex code is hard to work with and understand. This increases the risk that a bug will be introduced the next time the code has to change. When writing a new method, the best way to ensure that it keeps from becoming too complex, it to ensure that the method only has one responsibility. The trick for figuring out how many responsibilities a method has is to answer the question, what is this method doing? If your answer requires that you use the word and then that's a clear indicator that the method is responsible for more than one thing. If you're working with an existing method or function that is too complex, then you'll need to apply refactorings to reduce it. The extract method refactoring is the one that's going to yield the most benefit. The complexity metric gives us a more precise way of quickly assessing how complex a method is. We can use that information to make informed decisions about how to reduce the method's complexity. Complexity metrics come in a variety of flavors. The two that are most common are cyclomatic complexity and cognitive complexity. Each metric uses a different strategy for creating a numerical score for a chunk of code. Cyclomatic complexity counts the number of distinct code paths, and cognitive complexity counts statements which can make code hard to understand, such as complex Boolean logic, and deeply nested control structures. Both metrics use the same scale. Five or less, or zero to five is easy to understand. Greater than five or 10 or less, somewhere between six and 10 is complex. Greater than 10 is too complex. If you want to measure cognitive complexity, you can use a tool called Code Climate. Other tools that you reach for might use cyclomatic complexity. It's common for cognitive complexity and cyclomatic complexity to have drastically different values. This is because of the way the algorithm for cognitive complexity treats different control structures. For example, the score that cyclomatic complexity computes for a K-statement is equal to the number of conditions that are handled, but the score that cognitive complexity uses for such a statement is just one. Cognitive complexity also takes nesting into greater consideration than cyclomatic complexity does. In cognitive complexity, each level of nesting increases the score, but in cyclomatic complexity, nesting is not something that contributes to a score. There's a ton of good info in Code Climates documentation, if you'd like to dig into the differences between the two metrics in more detail. In the next couple of videos, we're going to dig into using Code Climate to measure complexity on your project.

Contents