Search code examples
phpoopinheritancecode-metrics

What is exactly is the average hierarchy metric, and how do I reduce the score?


I've been using PHPDepend to validate the quality of the code I'm writing. The one metric where I'm not in the low/average column is the average hierarchy height metric.

The definition on pdepend.org is

The Average Hierarchy Height metric is a average depth of the inheritance hierarchy. In a system of ten classes, a AHH-value of 1 can be interpreted in different ways, for example: Five classes inherit from five other classes within the analyzed application or five classes inherit from a single root class.

My head just isn't grasping what that sentence is saying, which means I'm struggling to figure out how I would go about reducing the score given.


Solution

  • class A{}
    
    class A1 extends A{} // 1 depth
    
    class A11 extends A1{} // 2 depth
    class A12 extends A1{} // 2 depth
    
    class B{}
    
    class B1 extends B{} // 1 depth
    
    class C{}
    
    class D{}
    

    There are 4 root class A, B, C, D

    • A hierarchy has 2 depth
    • B hierarchy has 1 depth
    • C hierarchy has 0 depth
    • D hierarchy has 0 depth

    Sum of it is 3.

    AHH = 3/4 = 0.75

    From code

    if (($count = count($this->rootClasses)) > 0) {
        $this->ahh = array_sum($this->rootClasses) / $count;
    

    To reduce this score you could add more root classes without children at all(or lower than the deepest). Or reduce depth of hierarchy.