Skip to content

Commit 088ebdc

Browse files
committed
Prefer composition (#504)
1 parent 3e0cbee commit 088ebdc

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

index.bs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -884,6 +884,48 @@ that authors can use to extend the language
884884
without breaking future native functionality,
885885
to reduce such dilemmas in the future.
886886

887+
<h3 id=prefer-composition>Build complex types by composing simpler types</h3>
888+
889+
Define subtypes that can always be used in place of a supertype.
890+
Avoid interfaces that use inheritance
891+
unless everything that can be said about an instance of the parent
892+
always applies to the child as well.
893+
894+
With inheritance, a subtype creates a type of item
895+
that can stand in for its supertype.
896+
A subtype needs to provide the same attributes and methods as its supertype.
897+
The subtype also needs to maintain consistent behavior.
898+
If the subtype changes the way that an item works,
899+
something that handles the supertype might not work properly.
900+
901+
In the theory of type systems, this is known as the
902+
[Liskov Substitution Principle](https://en.wikipedia.org/wiki/Liskov_substitution_principle).
903+
904+
<div class=example>
905+
The {{Event}} type is a super-type of {{KeyboardEvent}} and {{PointerEvent}}.
906+
Events always have the same basic set of properties and actions that apply,
907+
like whether the event {{Event/bubbles}}.
908+
The subtypes add new properties and actions,
909+
but instances of those subtypes still act in every way as an {{Event}}.
910+
</div>
911+
912+
A simpler approach is often to avoid inheritance
913+
and reuse existing capabilities
914+
by composition.
915+
New items can define properties that hold
916+
any existing components that are needed.
917+
918+
<div class=example>
919+
Form-associated custom elements allow custom elements to interact with form submission.
920+
Specializing {{HTMLInputElement}} would be difficult,
921+
because an <{input}> element is quite complex
922+
and a specialization of {{HTMLInputElement}} would need to maintain that complexity.
923+
Custom elements can attach (i.e., compose) items that are necessary to
924+
interact with a form
925+
without having to deal with the complications of {{HTMLInputElement}}.
926+
</div>.
927+
928+
887929
<h2 id="html">HTML</h2>
888930

889931
This section details design principles for features which are exposed via HTML.

0 commit comments

Comments
 (0)