Well, the FP example looks the same because it is, actually, almost the same. The function returns an object. "bark" is a function with a side effect. In FP world this kind of function would be executed in some IO structure. At least it should return something, e.g.:
constbark=name=>{console.log(`${name} is a good dog!`);// Dirty side effectreturnname;}
This is JS specifics, I don't have other key-value data structure
Note: function returns record data structure (which in JS confusingly named "Object", but we don't use any "objecty" feature we use it as a simple key-value data structure). Variable name privately stored in the scope of a closure, there is no way to access it outside.
"bark" is a function with a side effect
This was for the demo purpose, changed it to return.
constDogFunction=dog=>({map:f=>DogFunction(f(dog));});constwalk=isRaining=>dog=>({...dog,// if there are some other fieldscolor:isRaining||dog.color==='dirty'?'dirty':dog.color,needToWash:dog.needToWash||isRaining,});constbelka=DogFunction({color:'white',needToWash:false});constbelkaAfterWalking=belka.map(walk()).map(walk(true)).map(walk());// belka didn't mutate: { color: 'white', needToWash: false }// belkaAfterWalking: { color: 'dirty', needToWash: true }
DogFunction can have a "walk" method but it is more OOP way. Compare how different it is comparing to the previous more abstract example:
constDogFunction=dog=>({walk:isRaining=>DogFunction({...dog,// if there are some other fieldscolor:isRaining||dog.color==='dirty'?'dirty':dog.color,needToWash:dog.needToWash||isRaining,}),constbelkaAfterWalking=belka.walk().walk(true).walk();// belka didn't mutate: { color: 'white', needToWash: false }// belkaAfterWalking: { color: 'dirty', needToWash: true }});
Still no mutations in between. FP and OOP can be similar only in very simple examples when mutations haven't joined the game.
Well, the FP example looks the same because it is, actually, almost the same. The function returns an object. "bark" is a function with a side effect. In FP world this kind of function would be executed in some IO structure. At least it should return something, e.g.:
Bark in DogFunction becomes a map function:
Then we call it like this:
This is how I see the example with a dog.
Edit: added code parsing
This is JS specifics, I don't have other key-value data structure
This was for the demo purpose, changed it to return.
It is better now w/o a side effect, however, the difference comes with adding more logic, e.g. changing an attribute of it.
Classic OOP way:
FP way based on the example:
DogFunction can have a "walk" method but it is more OOP way. Compare how different it is comparing to the previous more abstract example:
Still no mutations in between. FP and OOP can be similar only in very simple examples when mutations haven't joined the game.
Yes I mentioned this in the post as well