Depth of Inheritance Tree (DIT)
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.
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
dcm:
metrics:
depth-of-inheritance-tree:
threshold: 5
To set multiple threshold or other common config options, refer to the Configuring Metrics page.
Example
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() {}
}