I've been convinced for awhile now that some strategies in functional programming are better suited to a number of computations (i.e immutability of data structures). However, due to the popularity of imperative languages, its unlikely that I will always be working on projects that are functionally implemented. Many languages (Matlab, Python, Julia) support using a functional paradigm, but it feels tacked on in many cases (looking at you, anonymous functions in Matlab). That being said, what are functional methods and strategies that I can use even in OOP/Imperative code? How can I write solid functional code that does not allow side effects even in languages that have mutable state and global variables?
|
Mutable state is easily avoidable using immutable objects. In the same way, global variables are usually the choice of the developer (or a poorly implemented framework). This being said, you may also want to use additional functional paradigms in non-functional languages. It's all about the expressiveness of your code. If you see that a list comprehension in Python makes your code easy, go for it. If you find it more readable in a particular case to have an immutable structure used through method chaining, great. But don't forget, some people find imperative variants easier than functional ones, even if it means writing three times the original LOC and risking to introduce subtle bugs. More importantly, some programmers don't understand the basic concepts. Many C# programmers struggle with lazy evaluation and are completely unable to explain why, if you take an Also, don't worry that you won't work with functional languages. Non-functional languages tend to be inspired the last few years by functional ones. C# is a great example. Python and JavaScript are two other mainstream languages which tend to introduce more and more functional aspects in them. In essence, any language which support lazy evaluation and lambda expressions is a good candidate for functional-style code. |
|||||||||
|
The simple answer is, do not use global or mutable variables, or just because you can mutate them does not mean you have to. Consider a class like this:
That class is immutable and even thread-safe. There is no way to mutate the state after it is constructed, even though the field is technically mutable. |
|||||||||
|
Prefer pure functions and immutable variables/objects. Apart from that, keep in mind the limits and the conventions of the language you are using. Don't forget:
In my experience, except for a few |
|||
|