Cognitive Complexity for Coders to Code Like Hemingway

Share on facebook
Share on twitter
Share on linkedin
Share on reddit

Run-through

Git Workflow Best Practices for Teams

Git Workflow Best Practices for Your Team

A lot of teams use Git, and nearly everything we do revolves around what you do on Git, too. However, not everyone who uses Git knows all of the ins-and-outs of using it and that can cause software engineering managers a headache or two. So, let’s get everyone aboard with Git workflow best practices and moving in the same direction with Git, regardless of the size of your development team!

Read More »

“For sale: baby shoes, never worn.” This six-word story is attributed to Ernest Hemingway. As a software developer, the code you write will never make it onto the New York Times “Best Sellers” list. Your code will never receive the critical acclaim of a Shakespeare, Dickinson, Poe, or an Orwell. Using cognitive complexity as a coding metric can help your developers write better quality code. They’ll be able to read and understand it faster and find bugs easier, so they can spend more time actually writing code.

What is Cognitive Complexity?

Cognitive complexity for software code is a metric formulated by G. Ann Campbell from Switzerland’s SonarSource SA. You can download Code Complexity: A new way of measuring understandability for a complete technical overview of how it works. Cognitive complexity measures how difficult code is for a human to read and understand. Devised in 2018, it’s a comparatively new, but very insightful measurement for software developers. The concept of cognitive complexity in psychology goes back to 1955 with the work of James Bieri.

It’s sort of like the Flesch reading ease score, but for coders. Improving cognitive complexity will make it easier for other coders to understand. Writers of articles and books use Flesch to write so their audience will understand them. That means short sentences and simple words for young students. University graduates can (usually) understand multi-syllable words and longer sentences. Even so, simpler is better.

Cognitive Complexity is quite different from Cyclomatic Complexity. Cyclomatic Complexity is a metric used to how complex a program is, particularly for testing. There is no inherent correlation between the two. A program’s code can be difficult to test, but easy to understand, and vice versa.

Why is Cognitive Complexity a Useful Metric?

Only people who write code actually read code. Mostly. While it’s not for entertainment, code sometimes includes elements of humor, horror, and mystery. Most coders would agree that good code doesn’t include any of that. The simpler it is, the better, because:

  • More time is spent reading code than writing it.
  • Software typically has a lifespan of 6-8 years, sometimes more.
  • Software may see 3-4 complete team rotations.
  • Each developer has their own specialties in programming languages and otherwise.
  • Programming languages, tools, and techniques rise and fall in popularity, even die over time.

You’re really writing code for everyone else who follows in your footsteps. You don’t know how skilled or experienced they are with the programming language you’re using. For these reasons, best practice is to write code that explains itself.

What Increases Cognitive Complexity?

Per the complete technical details, Cognitive Complexity is calculated according to three rules:

1. Ignore structures that allow multiple statements to be readably shorthanded into one
2. Increment (add one) for each break in the linear flow of the code
3. Increment when flow-breaking structures are nested

There are four types of increments: Nesting, Structural, Fundamental, and Hybrid. Each type of increment adds one to the Cognitive Complexity score. Paying attention to the type of increment can be helpful in understanding how complexity is accruing and how it can be simplified.

The following screenshot from the Cognitive Complexity pdf showing the same amount of code for the same basic purpose can vary quite dramatically in its ease to understand.

The same amount of code for the same basic purpose can vary quite dramatically in its ease to understand
Cognitive Complexity: A new way of measuring understandability by G. Ann Campbell

Use Comments to Clarify and Focus on Simplicity

Always write what you’re trying to achieve as a comment before you start writing the actual code. Keep it simple, focused, and localized by applying to the Single Responsibility Principle. That principle states, “every class in a computer program should have responsibility for a single part of that program’s functionality.” Comments can keep your coding objective crystal clear – “This portion of code needs to do this.” It’s actually quite a helpful technique and it’s one that writers use, too. Writers use abstracts to itemize everything that an article should cover, each item being like a comment. It’s easy to overthink or try to write code that handles two (or more) related things. Keeping this focus, however, makes it easier to see complexity trying to sneak in – “This portion of code needs to do this and that.”

Minimize the number of parameters used in methods

It’s best to have no more than 2-3 parameters for a method. If you need more, you can include all of them in a class – and pass the object.

{

//Logic to update Customer

}

public void updateCustomer (String customerName, Integer CustomerId, String customerNiche, Double customerSalary)

Try to use no more than 2-3 elements for the method

{

//Logic to update Customer

}

public void updateCustomer (Customer customer)

Use Object of Customer class

Maintain the Flow

Fortunately, nearly every programming language code is written and reads from left to right, then down. But, if we were to suddenly shift to how it’s not always that simple in design – we’d be breaking the flow. That’s not to say that we can’t, only that doing so adds complexity to the discussion. And, if we were to get into the languages that read right to left, or top-down and left to right, it would get even more complex.

Simple Complex
Java Java
if (env.debugMode()) { System.out.println(“Hello, world!”); } while(theWorldTurns) { if(isMorning) { try { if (env.debugMode()) { System.out.println(“Hello, world!”); } } catch (BadDay e) { System.out.println(“Yikes!”); } } }

Avoid Deep Nesting

Nesting conditionals and loops, and other components like goto or if adds complexity and makes the issue harder for other developers to find.

Putting Cognitive Complexity to Use

Cognitive Complexity has several uses, even if it won’t make you into a Hemingway. For team development, it is worth addressing in your coding standards. Three inherent benefits immediately spring to mind.

  • It helps measure how easy it is for developers to understand code. The faster they can read and understand code, the easier it is to find bugs, the more time they can spend writing code.
  • It provides a consistent way to structurally evaluate how, where, and why complexity is being added. Efforts to promote easy to understand code can be handled in code reviews and reinforced by
  • The complexity of different portions of code can be evaluated for the sake of prioritizing refactoring efforts.

So, even if it doesn’t turn developers into world-renowned writers like Hemingway, it will help improve their skills and the quality of their code. Besides, software developers make more than the vast majority of writers.

About Gitential

Gitential is like “Google Analytics” for software development. Our automated analytics helps software engineers and software project managers track developer performance to measure efficiency, identify, and correct trends contributing to technical debt. If you have any questions about how Git analytics can help you, please let us know at gitential@gitential.com. We welcome you to sign up for a free trial, no credit card is needed.

Git Workflow Best Practices for Teams

Git Workflow Best Practices for Your Team

A lot of teams use Git, and nearly everything we do revolves around what you do on Git, too. However, not everyone who uses Git knows all of the ins-and-outs of using it and that can cause software engineering managers a headache or two. So, let’s get everyone aboard with Git workflow best practices and moving in the same direction with Git, regardless of the size of your development team!

Read More »
The Best Places to Source Top Tech Talent

The Best Places to Source Top Tech Talent

As technology continues to develop, the workforce is going to see widespread disruption. The skills and expertise to be demanded of employees will result in a drastic change within all industries, regardless of whether they are based on tech or not. A byproduct of this will be a change in how recruiting is performed. What are the best places today to source top tech talent?

Read More »

Did you like our content?

Spread the word

Share on facebook
Share on twitter
Share on linkedin
Share on reddit

Subscribe to Our Newsletter

Don't miss our latest updates.
All About Software Engineering Best Practices, Productivity Measurement, Performance Analytics, Software Team Management and more.

Did you like our content?

Spread the word

Share on facebook
Share on twitter
Share on linkedin
Share on reddit

Subscribe to Our Newsletter

Don't miss our latest updates. All About Software Engineering Best Practices, Productivity Measurement, Performance Analytics, Software Team Management and more.