Skip to content

Commit f665265

Browse files
committed
review of OOP vs FP
1 parent f70474b commit f665265

File tree

7 files changed

+195
-8
lines changed

7 files changed

+195
-8
lines changed

.vscode/settings.json

Lines changed: 0 additions & 8 deletions
This file was deleted.

Assets/Composition.png

757 KB
Loading

Assets/Inheritance.png

973 KB
Loading

Assets/PartialApplication.png

16.8 KB
Loading

FunctionalProgramming.md

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,5 +176,106 @@ curriedMultiplyBy5(6) // -> 30
176176
curriedMultiplyBy5(10) // -> 50
177177
```
178178

179+
<br>
180+
181+
## Partial Application
182+
183+
![Partial Application](./Assets/PartialApplication.png)
184+
185+
Partial Application is a technique of fixing a number of arguments to a function, then producing another function of smaller arguments i.e binding values to one or more of those arguments, and using closures to later be called with the rest of the arguments.
186+
187+
```javascript
188+
function addition(x, y) {
189+
return x + y;
190+
}
191+
192+
const plus5 = addition.bind(null, 5)
193+
194+
plus5(10) // -> 15
195+
```
196+
197+
<i>Note: this value does not matter for the (non-method) function addition which is why it is null above.</i>
198+
199+
<br>
200+
201+
### Difference between Currying & Partial Application
202+
203+
- Currying always produces nested unary (1-ary) functions. The transformed function is still largely the same as the original.
204+
- Partial application produces functions of arbitrary number of arguments. The transformed function is different from the original — it needs less arguments.
205+
206+
---
207+
<br>
208+
209+
## Difference between Parameters & Arguments
210+
211+
Function parameters are placeholders that are used to access data input (arguments) to that function. The following function defines two parameters `x` and `y`:
212+
213+
```javascript
214+
function addition(x, y) {
215+
return x + y;
216+
}
217+
```
179218

219+
Arguments are the actual values passed to a function when the function is called. We can say that function defines parameters and it takes arguments.
220+
221+
```javascript
222+
addition(5,10)
223+
```
224+
225+
### Arity
226+
227+
Arity of a function simply refers to the number of arguments that the function takes.
228+
229+
---
230+
<br>
231+
232+
### Exercise:
233+
234+
Implement a cart feature using functional programming:
235+
1. Add items to cart
236+
2. Add 10% tax to item in cart
237+
3. Buy item: cart --> purchases
238+
4. Empty cart
239+
240+
```javascript
241+
// create our own compose function
242+
const compose = (f,g) => (...args) => f(g(...args));
243+
244+
const user = {
245+
name: 'Corey',
246+
active: true,
247+
cart: [],
248+
purchases: []
249+
}
250+
251+
const purchaseItem = (...funcs) => funcs.reduce(compose);
252+
253+
purchaseItem(emptyCart, buyItem, applyTax, addToCart)(user, {name: 'laptop', price: 600})
254+
255+
function addToCart(user, item) {
256+
const updateCart = user.cart.concat(item)
257+
return Object.assign({}, user, { cart: updateCart })
258+
}
259+
260+
function applyTax(user) {
261+
const {cart} = user;
262+
const taxRate = 1.1;
263+
const updatedCart = cart.map(item => {
264+
return {
265+
name: item.name,
266+
price: item.price * taxRate
267+
}
268+
})
269+
return Object.assign({}, user, { cart: updatedCart })
270+
}
271+
272+
function buyItem(user) {
273+
return Object.assign({}, user, { purchases: user.cart })
274+
}
275+
276+
function emptyCart(user) {
277+
return Object.assign({}, user, { cart: [] })
278+
}
180279

280+
// -> { name: 'Corey', active: true, cart: [], purchases: [{ name: 'laptop', price: 660 }]}
281+
```

OOPvsFP.md

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
# OOP vs FP
2+
3+
In all programs there are two primary components, *data* and *behaviors*.
4+
5+
Object Oriented Programming says bring together the data and the behavior in a single location called *object* or *class*. This allows us to easier understand our program and be more organized.
6+
7+
Functional Programming says that *data* and *behaviors* are distinctly different things and should be kept separate for clarity.
8+
9+
<br>
10+
11+
## Key Differences
12+
13+
| OOP | FP |
14+
| :------------ |:------------- |
15+
| Few operations on common data | Many operations on fixed data |
16+
| **Stateful** - State is modified | **Stateless** - State is immutable |
17+
| **Side effects** - Methods manipulate internal state | **Pure** (no side effects) - Functions don't modify outside code |
18+
| **Imperative** - How we want it done | **Declarative** - What we want to be doing |
19+
20+
<br>
21+
22+
---
23+
<br>
24+
25+
## Inheritance vs Composition
26+
27+
Inheritance is a superclass that is extended to smaller pieces that add or overwrite things. We used this in our OOP example where we had the `elf` and `ogre` classes that extended the functionality of the `character` superclass.
28+
29+
Composition is creating a series of small pieces which collectively create something bigger. We used this in our FP example to compose a series of functions that gave the `purchaseItem` function many different abilities to process data differently.
30+
31+
Inheritance is when you design your types after what they are, while composition is when you design your types after what they do.
32+
33+
### Issues with Inheritance:
34+
35+
- <b>Fragile base-class & Tight Coupling:</b>
36+
Individual changes made to programs built using inheritance can often create unforseen ripple effects which can break code. For example, you might add in a new function to a base class which will create conflicts with the inheriting sub classes. For this reason it can be difficult to write code which plans for the future using inheritance.
37+
38+
- <b>Hierarchy:</b>
39+
A range of issues can arise relating the the heirarchy structure of elements using inheritance, particularly when changes are made. For example, new sub classes may by default inherit a heap of properties and data they don't need. It's also difficult to make changes to subclasses' hierarchy once they're set and referencing each other.
40+
41+
### How can this be fixed with composition?
42+
43+
Instead of defining the attack method inside the character class (like our OOP example) we will create a separate function to give attack to a character.
44+
45+
```javascript
46+
function getAttack(character) {
47+
return Object.assign({}, character, { attackFn: () => {} })
48+
}
49+
50+
function Elf(name, weapon, type) {
51+
let elf = {
52+
name,
53+
weapon,
54+
type
55+
}
56+
return getAttack(elf)
57+
}
58+
```
59+
60+
This way we're composing instead of just inheriting. We're giving the elf a set of basic abilities and then adding additional abilities as we like.
61+
62+
<br>
63+
64+
### To review:
65+
66+
Inheritance is a superclass that is extended to smaller pieces that add or overwrite things.
67+
68+
Although you can be careful with inheritance and make sure that the base class is very general so that you don't overload our subclasses, it can easily get out of hand as you go deeper down the inheritance chain. And once you need to change something it becomes really difficult.
69+
70+
![Inheritance](./Assets/Inheritance.png)
71+
72+
On the other hand composition is about smaller pieces that are combined to create something bigger.
73+
74+
You combine the boxes based on what you need to create the desired output. And if you need to add something later on you just add another box and recompose, and if you don't need something anymore you just simply remove it.
75+
76+
![Composition](./Assets/Composition.png)
77+
78+
For this reason it is widely accepted that composition is a better long term solution than inheritance. This doesn't mean that inheritance is always bad. There are ways that you can still write great code with inheritance, but the problems which typically arise, related to predicting future changes, becomes difficult to manage.
79+
80+
So composition is a good tool for you to use when creating software because it helps you create code that is more stable and easier to change in the future.
81+
82+
---
83+
<br>
84+
85+
## To Review
86+
87+
Object oriented programming and functional programming are both paradigms, and a programming paradigm is simply a set of rules and conventions for writing code. For example, organizing code into units would be called Object Oriented Programming. And avoiding side effects and writing pure functions would be called Functional Programming.
88+
89+
In object oriented programming an object is a box containing information and operations that are supposed to refer to the same concept, grouping it together as an object. These pieces of information inside the object are called attributes or state, and the operations that can happen to the state are known as methods.
90+
91+
In functional programming the code structure is essentially a combination of functions. Data is immutable which leads to writing programs with no side effects, because functions can't change the outside world and the output value of a function simply depends on the given arguments. This allows functional programming to really have control over a program flow.

ObjectOrientedProgramming.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,9 @@ sayAge() // -> my age is 26
276276

277277
## Inheritance
278278

279+
![Inheritance](./Assets/Inheritance.png)
280+
281+
279282
Here we're going to create a base (super) class of Character and then create a sub class of Elf which will extend Character, inheriting it's properties. Elf will now have a prototype of Character.
280283

281284
The constructor within the Elf class exists only within Elf. If we want to set any properties within this constructor using the `this` keyword, we have to use the `super` keyword to call the superclass first. In doing so `super` will run the constructor and give us an instance of the Character base class. The `this` keyword will now refer to that instance, and we can now add on additional properties for the Elf subclass.

0 commit comments

Comments
 (0)