Composition over Inheritance
Composition over Inheritance is the preference to compose behaviour from object rather inherit behaviour from objects.
Rationale
The preference to use composition derives from the flexibility it encourages, allowing for code to be refactored and changed more easily.
Examples
Example that uses inheritance
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
class Product {
public Product(String name, BigDecimal price) {
this.name = name;
this.price = price;
}
public String getName() { return this.name; }
public BigDecimal getPrice() { return this.price; }
}
class SpecialProduct extends Product {
public SpecialProduct(String name, BigDecimal price, List<Variant> variants) {
super(name, price);
this.variants = variants;
}
public List<Variant> getVariants() { return this.variants; }
}
|
Example that uses composition
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
class Product {
public Product(String name, BigDecimal price) {
this.name = name;
this.price = price;
}
public String getName() { return this.name; }
public BigDecimal getPrice() { return this.price; }
}
class SpecialProduct {
public SpecialProduct(Product product, List<Variant> variants) {
this.product = product;
this.variants = variants;
}
public String getName() { return this.product.name; }
public BigDecimal getPrice() { return this.product.price; }
public List<Variant> getVariants() { return this.variants; }
}
|
References