Skip to content

Commit 86f24b3

Browse files
committed
docs: generate the composition diagram
Signed-off-by: Otavio Santana <otaviopolianasantana@gmail.com>
1 parent c7e9bd6 commit 86f24b3

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
= 🍰 Composition Over Inheritance
2+
Otávio Santana
3+
:icons: font
4+
:source-highlighter: rouge
5+
:toc:
6+
7+
== ❌ Inheritance Gone Wrong
8+
9+
A cake has salt.
10+
The sea has salt.
11+
But a cake **is not** a sea. Yet some code tries to do this:
12+
13+
[source,java]
14+
----
15+
class Sea {
16+
boolean hasSalt() { return true; }
17+
}
18+
19+
class Cake extends Sea {
20+
// 🤯 Makes no semantic sense
21+
}
22+
----
23+
24+
== ✅ Composition Done Right
25+
26+
Use `has-a` instead of `is-a`:
27+
28+
[source,java]
29+
----
30+
class Salt {}
31+
32+
class Sea {
33+
Salt salt = new Salt();
34+
}
35+
36+
class Cake {
37+
Salt salt = new Salt();
38+
}
39+
----
40+
41+
== 🎨 Diagram
42+
43+
[source,mermaid]
44+
----
45+
classDiagram
46+
class Salt
47+
48+
class Sea {
49+
+Salt salt
50+
}
51+
52+
class Cake {
53+
+Salt salt
54+
}
55+
56+
Sea --> Salt : has-a
57+
Cake --> Salt : has-a
58+
----
59+
60+
== 💡 Key Takeaway
61+
62+
* Use inheritance only when `A is a B` is semantically correct.
63+
* Use composition when `A has a B` or `A uses B`.

0 commit comments

Comments
 (0)