4 ms·
FP is mostly a state of mind - of course picking the language really helps about incentives, but you can do it even in Java/C# (in fact if you do C# there is th
by ff_ 9y ago
FP is mostly a state of mind - of course picking the language really helps about incentives, but you can do it even in Java/C# (in fact if you do C# there is the great LINQ library that helps).
How to approximate FP in a mostly OOP language:
- use immutable data structures: there is no way around being able to fearlessly modify something. The naive way is to copy the object before touching it, the better way is to use efficient structures, e.g. Clojure data structures from Java.
- you either have data classes (no methods, no private fields), or execution classes (no data fields, only static methods), no mixing
- of you stick to the above, you will find that returning void from a method is very difficult.
Congrats, you're doing FP: the gist of it is that it's all about keeping state explicit; if you pass some A in a function, you will return a B at some point, and that's your result. No implicit state.
Of course, we're missing the whole part about side effects, so to add to the above: if you cannot write a unit test without mocking something in your method, you're doing side effects. They should be done only at the "border" of the application, to (maybe) get you the data you need, so you can bring it and process it in the pure core.
And this is where languages like Haskell help: to understand where the side effects are (because they are included in the types) and to prevent mixing them around (which only gets you an untestable mess in the end).
HTH
- tome 9y agoWhat a great explanation of the "state of mind" of FP!