DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Code Graphs: A Guide for Testers
  • Testing the Untestable and Other Anti-Patterns
  • Two Cool Java Frameworks You Probably Don’t Need

Trending

  • Automating Data Pipelines: Generating PySpark and SQL Jobs With LLMs in Cloudera
  • AI-Based Threat Detection in Cloud Security
  • Teradata Performance and Skew Prevention Tips
  • A Guide to Container Runtimes

How Readable Is Your Code? Part 1

Let's write a simple application and create its flowchart. Application logic is not important. Find out more about code readability!

By 
Dmitry Egorov user avatar
Dmitry Egorov
DZone Core CORE ·
Updated Dec. 17, 20 · Opinion
Likes (15)
Comment
Save
Tweet
Share
11.6K Views

Join the DZone community and get the full member experience.

Join For Free

There Is No Perfect Implementation?

Every developer has his own preferences and vision about problem-solving. Any problem can be solved in my différent ways following know practices like SOLID, KISS, etc. But how to compare 2 different implementations? Smaller is better? Only Object-Oriented? How practically evaluate notions like code maintainability, readability, transparency? Well, I'm not sure that there is absolute truth in such questions, but in this article, you will find a metric that can help you find out. 

Cyclomatic Complexity — Number of Scenarios in Code.

Cyclomatic complexity is a metric invented to find out the number of tests to cover the given code fully. This metric also can be used to measure the readability of your code.  Cyclomatic Complexity shows how many scenarios consist of your code (or how many independent ways inside its graph)

Cyclomatic Complexity Example

Let's write a simple application and create its flowchart. Application logic is not important. Application iterates applicants and calculates their salary. For java developers salary is increased by 2 times. 

Java
 




x


 
1
public static void main(String[] args) {
2
  //statement 1
3
  List<Applicant> applicants = Arrays.asList(new Applicant("John", 5, true),
4
                                             new Applicant("Mary", 10, true));
5
  for (Applicant applicant : applicants) { //Condition 1
6
    //statement 2
7
    int salary = 0;
8
    if (applicant.isJavaDev()) { //condition 2
9
      //statement 3
10
      salary = 2 * 10 * applicant.getYearOfExperience();
11
      log.info(applicant.getName() + " salary is : " + salary);
12
    } else {
13
      //statement 4
14
      salary = 10 * applicant.getYearOfExperience();
15
      log.info(applicant.getName() + " salary is : " + salary);
16
    }
17
  }
18
}
19

          
20
@Data
21
@AllArgsConstructor
22
static class Applicant {
23
  private String name;
24
  private int yearOfExperience;
25
  private boolean isJavaDev;
26
}



Calculating Cyclomatic Complexity

To calculate Cyclomatic Complexity, we need to create the code's flowchart. 

statement

In the image, you can see that code contains 7 nodes and 8 edges. The following expression calculates cyclomatic complexity (CYC):

CYC = (Number of Edges) — (Number of Nodes) + 2 * (Number of Exit Nodes)

For our case, CYC is:

CYC = 8 — 7 + 2 * 1 = 3

Cyclomatic complexity is 3. But what does it mean? This number describes how many independent scenarios in our code. Let's find all of them:

1. There are no applicants — so we skip iteration and exit application (Greenway)

2. Applicant is not a java developer (So 4th statement is performed- Blue way)

3. Applicant is java developer (So 3rd statement is performed — Red way)

conditions and statements

The factor that increases complexity:

  • If/Switch/Recursion/Label jumps/
  • Iterations (For each, While)
  • Complex conditions increase complexity eg (condition1 || condition2) add 2 score.

Can We Recognize Cyclomatic Complexity as Readability Metric?

Well, in some sort. If an implementation can reduce cyclomatic complexity without losing functionality, it means that it has extra instructions. In general relation between code readability/maintainability and CYC are described in the next table:

CYC SCORE LEVEL OF READABILITY
1-10 Maintainable code  
10-20 Difficult to support
20-40 Very difficult to support
>40 Unmaintainable code 

But What About Better Metrics? Find in the Second Part

Cyclomatic Complexity metric doesn't cover human aspects in code readability. In the next chapter, I'll introduce different metrics that might be more practical. 

Cyclomatic Complexity

Opinions expressed by DZone contributors are their own.

Related

  • Code Graphs: A Guide for Testers
  • Testing the Untestable and Other Anti-Patterns
  • Two Cool Java Frameworks You Probably Don’t Need

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!