Skip to main content

Depth of Inheritance Tree (DIT)

v1.3.0
short name: DIT
effort: 10m
default threshold: 5

Depth of inheritance tree is a metric that measures the maximum inheritance path, referring to the number of levels a class is from the root class in an inheritance hierarchy (expressed in Dart via the extends keyword).

A deeper class hierarchy indicates a greater number of inherited methods and variables, which can contribute to increased complexity.

The base depths of inheritance tree is 1 (when a class inherits directly from Object and/or has no extends).

Additional resources: Chidamber-Kemerer metrics paper.

note

This metric is calculated only for non-abstract classes.

Why Be Cautious

Deep inheritance tree can lead to:

  • Increased Complexity: A deep inheritance tree increases complexity and can make understanding the code more difficult.
  • Maintainability Challenges: Deeper trees can make maintenance harder due to the larger number of inherited methods and variables.
  • Fault-Proneness: Deep hierarchies can be more prone to faults as changes in base classes can have wide-reaching effects.

How to Address Deep Inheritance Trees?

  • Limit Inheritance Levels: Try to keep the inheritance tree shallow to reduce complexity.
  • Use Composition Over Inheritance: Prefer composition to inheritance where possible to avoid deep hierarchies.
  • Refactor: Regularly refactor the class hierarchy to reduce unnecessary inheritance levels.
  • Design Reviews: Conduct regular design reviews to maintain a clean and maintainable inheritance structure.

Config Example

analysis_options.yaml
dcm:
metrics:
depth-of-inheritance-tree:
threshold: 5

To set multiple threshold or other common config options, refer to the Configuring Metrics page.

Example

info

To view what contributes to the metric value, generate an HTML report.

❌ Bad: High Depth of Inheritance Tree

class Animal {
void eat() {}
}

class Mammal extends Animal {
void breathe() {}
}

class Canine extends Mammal {
void bark() {}
}

class Dog extends Canine {
void fetch() {}
}

class ServiceDog extends Dog {
void assist() {}
}

// DIT: 6, which is higher than the recommended DIT of 5.
class GuideDog extends ServiceDog {
void guide() {}
}

✅ Good: Low Depth of Inheritance Tree

class Animal {
void eat() {}
}

class Mammal extends Animal {
void breathe() {}
}

class Dog extends Mammal {
void bark() {}
}

// DIT: 4, adhering to the recommended DIT of 5 or less.
class ServiceDog extends Dog {
void assist() {}
}