Introduction
In Fβ―, object-oriented is sometimes more practical than functional style.
Object-oriented building blocks in Fβ―:
Members
Methods, properties, operators
Attach functionalities directly to the type
Encapsulate the object's state (particularly if mutable)
Used with object dotting
my-object.my-member
Interfaces and classes
Support abstraction through inheritance
The four pillars of object-oriented programming
Abstraction
Encapsulation
Inheritance
Polymorphism
With the exception of inheritance, the other 3 concepts also apply to functional programming, especially in Fβ―, but to a lesser extent.
Abstraction
In OO, especially in Cβ―, abstraction is implemented using:
Types: classes or enums
Abstract classes and interfaces
In FP, abstraction is implemented using:
Types: algebraic data types are more powerful to model domain concepts
Functions: although equivalent to an interface with a single method, a function has a lower level of abstraction than an interface
Encapsulation
Encapsulation means 2 things:
Hide elements:
This feature is easy in Fβ―:
privatekeyword, expression nesting, partial application,.fsifiles...
Prevent a state from being invalid = Protect application invariants
If the state is mutable, it's definitely object-oriented.
If the state is immutable, it should be encapsulated only when it's possible to create an instance or copy and update an instance up to an invalid state.
Inheritance
Inheritance is an object-oriented technique. Still, Fβ― supports it, with just some limitations compared to Cβ―.
Polymorphism
In fact, there are several polymorphisms. The main ones are:
By sub-typing: the one classically associated with object-orientation β Base type defining abstract or virtual members β Subtypes inheriting and implementing these members
Ad hoc/overloading β overloading of members with the same name
Parametric β generic in Cβ―, Java, TypeScript
Structural/duck-typing β SRTP in Fβ―, structural typing in TypeScript
Higher-kinded β type classes in Haskell
Fβ― supports the 4 first polymorphisms.
Last updated
Was this helpful?