Open overcache opened 4 years ago
JavaScript is a sort of weird language. It has features from both the OOP world and the FP world. Its OOP is also a bit special (historically, JavaScript is built on top of prototypical inheritance which is already a special form of OOP). Yet, the language itself it one thing. The way it is used is another. JavaScript can be used to write purely functional code and that is true of pretty much any language; some languages simply makes it easier than others.
Classes in JavaScript are the closest thing we have to interfaces. So it makes sense to use them to capture the interfaces and the contracts for defining an algebraic data structure such as Maybe
or Either
. Now, if you look carefully into these class definitions you'll see that they are very much self-contained and do not have any implicit states that are mutated. So, when you map on a Maybe
object, you do not mutate the value inside that Maybe
object as you would in traditional OOP, but instead, you get a hand on a new object without altering the previous one.
Each function returns an entirely new object and there's no mutation going on. Data are passed around and transformed along the way. That, is the very essence of functional programming.
Plus, there's no inter-twining of classes together. Each class is used to represent one and only one data structure. They capture the behavior of a particular structure in the form of a set of methods. Then, these basic structures can be combined into others by using more complex data-structures with generic types but there's no moment where these are referencing each others nor building any complex relationships between each others.
thanks for your reply, so:
@KtorZ A simple factory function is template enough. The use of classes is completely unnecessary, and the fact that hacks like .of are being used as an expedient further exacerbates the issue.
If need be, you can also not utilize any form of inheritance. With functions a simple Object.assign or functional inheritance will do the trick.
Classes in Haskell are fine because they're more like interfaces rather than complete object blueprints. Classes in js should always be avoided.
In Chapter 3, you said:
But I saw a lots of class in the next chapters, Maybe/Either/IO are all show as class, they use
this
keyword, and create instance withnew
.I am so confused, do I miss something?