DEV Community

David Lambauer for run_as_root GmbH

Posted on • Edited on

Software Quality Metrics: No Sorcery, Just Simple Math!

Greetings, PHP Padawans and Code Craftsmen!

You've arrived at the right place if you're in search of the One Ring to rule your PHP code! The magical journey we're embarking on today involves a fantastical beast with a forbidding name - Software Quality Metrics.

Dramatic gasp

Relax, they're not as scary as they sound. In fact, they're your loyal allies, ready to add a Midas touch to your code. They're as easy to measure as counting the stripes on your tabby. So let's dive in, shall we?

1. The Code Maintainability Index: Is your code a Marathon Runner or a Couch Potato?

The Code Maintainability Index is like a fitness check-up for your code. It provides a score from 0 to 100, where 100 implies your code is ready to run a marathon (with no panting), and 0... well, let's say it's in love with the couch.

Maintainability Index calculates scores using three primary ingredients:

  1. Halstead Volume – It's like the manual of your code. If you've got more operators and operands than you can shake a stick at, your volume is high.
  2. Cyclomatic Complexity – More on this spicy ingredient later, promise.
  3. Lines of Code – Aka, your code's not-so-secret diary. More isn't always merrier here.

Consider this PHP snippet:

function findMedian($arr, $n) {
    sort($arr);
    if ($n % 2 != 0)
        return (double)$arr[$n / 2];
    return (double)($arr[($n - 1) / 2] + $arr[$n / 2]) / 2.0;
}
Enter fullscreen mode Exit fullscreen mode

It's lean, mean, and ready for the screen. It does one thing, and does it well - finds the median of an array. The complexity and volume are low. It would score pretty high on the Maintainability Index.

2. Cyclomatic Complexity: The Tangled Web We Weave

Next up, we have the Cyclomatic Complexity metric - which, despite its ominous name, is not a new Transformer villain. Instead, it measures the complexity of your code based on the number of independent paths through it. It’s like counting the possible routes you can take in your city. The more paths there are, the more complex the city... or in our case, the code.

Check this PHP example:

function sortArray($arr) {
    $size = count($arr);
    for ($i = 0; $i < $size; $i++) {
        for ($j = 0; $j < $size; $j++) {
            if ($arr[$j] > $arr[$i]) {
                $temp = $arr[$i];
                $arr[$i] = $arr[$j];
                $arr[$j] = $temp;
            }
        }
    }
    return $arr;
}
Enter fullscreen mode Exit fullscreen mode

Ouch! That's a double "for" loop sorting an array. With each "if" and "for," our Cyclomatic Complexity shoots up. It's like a city where every street corner has a dozen alleys leading off. Too many options can make the city - or your code - hard to navigate.

3. Code Duplication: Deja vu, or Copy-Paste Catastrophe?

Lastly, we have Code Duplication. Remember that cringe moment when you arrived at a party, and someone was wearing the same dress? Code doesn't like that, either. Code Duplication means how many times we've got the same or very similar blocks of code in different places.

Here's a guilty snippet:

function calculateDiscountA($price) {
    return $price - ($price * 0.1);
}

function calculateDiscountB($price) {
    return $price - ($price * 0.1);
}
Enter fullscreen mode Exit fullscreen mode

Yikes! Same dress at the party! This is a classic example of unnecessary code duplication, where calculateDiscountA and calculateDiscountB are doing the same thing.

To Sum It Up

If you treat these three metrics like your trusty ol' Marauder's Map, they will reveal your PHP code's secrets, quirks, and areas for improvement. Remember, understanding these metrics isn't about nitpicking your code. It's about making it healthier, sturdier, and more flexible.

Because at the end of the day, we want our code to be like that perfect piece of software - eloquent, efficient, and easier than Sunday morning!

Happy Coding! May your bugs be minimal, and your coffee cup be always full!

Until next time,
Your Friendly Code Whisperer

Top comments (2)

Collapse
 
fpsd profile image
Francesco

Nice intro to the problem of keeping track the complexity of your code base!

At work we use sonarsource.com/ which integrates nicely with Gitlab's CI/CD pipelines and gives us a report on each build, covering code quality and test coverage.

A followup post with a list of tools to automate the process of keeping track of the code quality would be great!

Collapse
 
dlmbr profile image
David Lambauer

Absolutely! I'll write more about metrics and code quality in my next posts :) Don't miss 'em and follow me!