Grokking SOLID Design Principles
Vote

0% completed

Using Composition to Follow Liskov Substitution Principle (LSP)

In the previous lesson we fixed a Liskov violation by changing the inheritance tree. There is a second way to fix these violations, and it often works better: stop using inheritance for the part that varies.

That second way is composition.

Inheritance and Composition Are Different Relationships

Both let one class use another class. They connect them in different ways.

  • Inheritance is an is-a relationship. Sparrow extends Bird means a sparrow is a bird. The subclass receives every method the parent has, whether it suits the subclass or not.

.....

.....

.....

Like the course? Get enrolled and start learning!
Rohit Bhanot

Rohit Bhanot

· 13 days ago

This is completely wrong and misleading and there is No Composition happening here !! You are just inherting from a different base class. Composition is when you include a class directly within a class and not when you inherit from it. Here is a composition example from one of previous lesson

class Invoice: def __init__(self, invoice_type *args, **kwargs): self.invoice_type = InvoiceType(invoice_type)

The fundamental difference is Composition says "Class B has Class A" whereas Inheritance says "Class B is a Class B".

This is the 3rd chapter in a row where I am seeing some fundamental conceptual flaws which can give completely wrong idea to someone who is new to these. I believe this course needs some re-work.

Show 1 reply
Amit Kumar

Amit Kumar

· 4 months ago

This whole composition thing seems misleading as shown in the example. it actually feels like interface segregation example.

Show 1 reply
S

shivamparke

· 2 years ago

The given example only uses interface-based design, but it doesn't actually demonstrate composition in any way. Interfaces help segregate behaviors, they don’t use composition—they only provide a contract, especially in this example.

Specifically, composition means using object relationships (has-a) instead of inheritance (is-a). But that relationship doesn't exist in this example!

Show 2 replies

Reading Progress

0%