Перейти к содержимому

Composition vs Inheritance — Explained in Detail

software-engineer-blog

0:00 / 0:00

Composition vs Inheritance — Explained in Detail

60 просмотров · 5 дней назад
software-engineer-blog
147 подписчиков
60 просмотров · 5 дней назад
Somebody bumps a library from 2.0.0 to 2.1.0. The release note says "removed some duplication" — one line. And a test that has been green for eight months, in a class nobody has touched, starts failing. Three items go into the basket. The counter says six. This is the fragile base class problem, and it is the clearest demonstration of what the word "extends" actually signs you up for. This video walks the real code, line by line: the ordinary library class, the perfectly reasonable subclass built on it, the single line upstream that breaks it, and then the same class wired the other way — holding a collaborator instead of inheriting from one — which survives both versions unchanged. We also do the honest side: composition is not free. You write forwarding methods by hand, you lose the free "is a" check, and you have to decide what you actually need from the thing you are holding. And there is a real, narrower job that inheritance still does well. The verdict: inherit to BE, compose to HAVE. Written for someone who has never heard the phrase "fragile base class". No prior object-oriented theory needed — every term is glossed the first time it appears. 0:00 The bug nobody introduced 0:43 What this is actually about 1:34 The mixer: clipped in, or welded on 2:26 What "extends" really signs you up for 3:13 The library class — nothing clever 3:49 The perfectly reasonable subclass 4:28 One line, upstream, eight months later 5:10 3 added, 6 counted, 1 line changed 5:39 The fragile base class problem 6:29 The same class, wired the other way 7:08 Why the parent has no way back in 7:52 What you get back: it is an argument now 8:30 The honest cost of composition 9:11 When "extends" IS the right answer 10:05 Inherit to BE, compose to HAVE 10:46 Wrap up WHAT YOU WILL SEE · A boring library class, and the one internal detail nobody documented · A subclass that is correct on Monday and wrong on Tuesday, with no edit in between · The exact call trace: why the tally reads 6 instead of 3 · The same class rebuilt with composition — green on both library versions · Why the parent structurally cannot reach back in · The bill: hand-written forwarding, a lost "is a" check, and one real design decision · When "extends" IS the right answer — the narrower, genuine job it has Code in the video is Python, but nothing here is Python-specific — the same trap exists in Java, C#, C++, Ruby, TypeScript and every other language with class inheritance. More CS and system design: https://software-engineer-blog.com #compositionvsinheritance #oop #softwaredesign #cleancode #systemdesign #programming