Addendum
Types Composition
Creating new types
Algebraic data types do not support inheritance
They cannot inherit from a base class.
They are
sealed: they cannot be inherited.But they can implement interfaces.
Algebraic types are created by composition:
Aggregation into a product type (Record, Tuple)
"Choice" in a sum type (Union)
Combine 2 unions?
Consider the 2 unions below dealing with French-suited cards (β β£ β₯ β¦):
type Black = Pike | Club
type Red = Heart | TileHow do you combine them to create a union of Pike, Club, Heart or Tile?
By flattening unions, as in TypeScript β
β It's not the expected result: Color is an enum-style union, with 2 cases Black and Red, totally disconnected from the Black and Red types!
By creating a brand new union β οΈ
Warnings
Can create confusion:
Pikerefers toColor.PikeorBlack.Pike?Need to write mappers between the 2 models:
(Black, Red) <-> Color
By composition β
β The new union Color is composed based on the 2 previous types:
Blackunion is used as data for theColor.BlackcaseRedunion is used as data for theColor.Redcase
Note
It's common in Fβ― to write union cases like Black of Black where the case name matches the case field type.
Union (FP) vs Object Hierarchy (OOP)
π A union can usually replace a small object hierarchy.
Explanations
Behaviors/operations implementation:
OO: virtual methods in separate classes
FP: functions relying on pattern matchings
exhaustivity
avoid duplication by grouping cases
improve readability by flattening split cases in a single
match..with
FP vs OOP
How we reason about the code (at both design and reading time)
FP: by functions β how an operation is performed for the different cases
OO: by objects β how all operations are performed for a single case
Abstraction
Objects are more abstract than functions
Good abstraction is difficult to design
The more abstract a thing is, the more stable it should be
π FP is usually easier to write, to understand, to evolve
FP vs OOP: Open-Closed Principle
It's easier to extend what's open.
OO: open hierarchy, closed operations
Painful to add an operation: in all classes π
Easy to add a class in the hierarchy π
FP: open operations, closed cases
Easy to add an operation π
Painful to add a case: in all functions π
Still, it's usually easier in Fβ―: only 1 file to change
βοΈ Notes:
Adding a class = new concept in the domain β always tricky β οΈ
Adding an operation = new behavior for the existing domain concepts
Last updated
Was this helpful?