Functional Programming Strategies in Imperative Languages

design-patternsfunctional programminglanguage-agnosticlanguage-designobject-oriented-design

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?

Best Answer

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 IEnumerable<T> which returns a bunch of elements from the database and you first count the number of elements, then loop through them, there would be not one, but two queries to the database. I'm not even talking about monads and other concepts which are mostly unused in mainstream non-functional languages.

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.