3 ms·
> Consider implementation of a hash map. Isn't it nice that the state is accessible only to {contains, get, set}? After auditing these three functions you can b
by andrenth 7y ago
> Consider implementation of a hash map. Isn't it nice that the state is accessible only to {contains, get, set}? After auditing these three functions you can be sure that the invariant is never violated. How would you ensure that in FP?
You can have the same with an abstract data type and a set of functions that operate on it.
Only functions defined in the same module as the ADT can access its internals, so inspecting those functions would yield the same assurance you’d have in the OOP version.
Arguably the FP version would be easier to inspect, because all data would be local (passed as a parameter), while the OOP version could have “semi-globals” in the form of instance variables.
- protomolecule 7y agoBut what I described IS an abstract data type and the concept of abstract data types appeared in CLU which is an OO language. What's more, encapsulation (data-hiding) don't seem to be an integral part of FP and Haskell's modules seem more like an exception than a rule. For example, listen [0] to the author of Clojure: "Fogus: Following that idea—some people are surprised by the fact that Clojure does not engage in data-hiding encapsulation on its types. Why did you decide to forgo data-hiding? Hickey: Let's be clear that Clojure strongly emphasizes programming to abstractions. At some point though, someone is going to need to have access to the data. And if you have a notion of "private", you need corresponding notions of privilege and trust. And that adds a whole ton of complexity and little value, creates rigidity in a system, and often forces things to live in places they shouldn't. This is in addition to the other losing that occurs when simple information is put into classes. To the extent the data is immutable, there is little harm that can come of providing access, other than that someone could come to depend upon something that might change. Well, okay, people do that all the time in real life, and when things change, they adapt. And if they are rational, they know when they make a decision based upon something that can change that they might in the future need to adapt. So, it's a risk management decision, one I think programmers should be free to make." [0] https://gist.github.com/rduplain/c474a80d173e6ae78980b91bc92f43d1 https://gist.github.com/rduplain/c474a80d173e6ae78980b91bc92...
- andrenth 7y agoSure, not all FP languages provide encapsulation, and neither do all OO languages (e.g. in Ruby there's always some way to access an object's private parts). My point was simply that the nice property you described can be achieved by using ADTs, and you don't need OO to have that.
- protomolecule 7y agoI think there is a difference between having a way to bypass encapsulation and deliberately not having encapsulation at all. Otherwise I agree with you.