Functional Programming vs OOP - alexanderteplov/computer-science GitHub Wiki
- OOP is based on objects as a primary unit.
- FP is based on functions.
- OOP follows an imperative programming model (says how to do).
- FP follows a declarative programming model (says what to do).
- OOP mostly operates mutable objects.
- FP mostly operates immutable objects.
- OOP may be more efficient in memory consumption and performance since we can directly control them.
- FP may be more efficient because of compiler optimizations and caching.
- FP is beneficial in parallel execution since it doesn't have race conditions (due to immutability).
- FP is easier to scale (because of purity, functions without a state can easily be duplicated).
Favor object composition over class inheritance
— the Gang of Four, “Design Patterns: Elements of Reusable Object-Oriented Software”
Software development is mostly about a function composition or an object composition.
Hence we compare it with inheritance let's talk about object composition here. It refers to combining objects into more complex ones.
Cons of inheritance:
- The tight coupling problem: Because child classes are dependent on the implementation of the parent class, class inheritance is the tightest coupling available in object-oriented design.
- The fragile base class problem: Due to tight coupling, changes to the base class can potentially break a large number of descendant classes — potentially in code managed by third parties. The author could break code they’re not aware of.
- The inflexible hierarchy problem: With single ancestor taxonomies, given enough time and evolution, all class taxonomies are eventually wrong for new use-cases.
- The duplication by necessity problem: Due to inflexible hierarchies, new use cases are often implemented by duplication, rather than extension, leading to similar classes which are unexpectedly divergent. Once duplication sets in, it’s not obvious which class new classes should descend from or why.
- The gorilla/banana problem: “…the problem with object-oriented languages is they’ve got all this implicit environment that they carry around with them. You wanted a banana but what you got was a gorilla holding the banana and the entire jungle.” ~ Joe Armstrong, “Coders at Work”
Function composition is very similar to object composition and has its pros over an inheritance.