Search code examples
oopprogramming-languagesfunctional-programmingparadigms

Can someone explain to me why I would need functional programming instead of OOP?


Possible Duplicate:
Functional programming vs Object Oriented programming

Can someone explain to me why I would need functional programming instead of OOP?

E.g. why would I need to use Haskell instead of C++ (or a similar language)?

What are the advantages of functional programming over OOP?


Solution

  • One of the big things I prefer in functional programming is the lack of "spooky action at a distance". What you see is what you get – and no more. This makes code far easier to reason about.

    Let's use a simple example. Let's say I come across the code snippet X = 10 in either Java (OOP) or Erlang (functional). In Erlang I can know these things very quickly:

    1. The variable X is in the immediate context I'm in. Period. It's either a parameter passed in to the function I'm reading or it's being assigned the first (and only—c.f. below) time.
    2. The variable X has a value of 10 from this point onward. It will not change again within the block of code I'm reading. It cannot.

    In Java it's more complicated:

    1. The variable X might be defined as a parameter.
    2. It might be defined somewhere else in the method.
    3. It might be defined as part of the class the method is in.
    4. Whatever the case is, since I'm not declaring it here, I'm changing its value. This means I don't know what the value of X will be without constantly scanning backward through the code to find the last place it was assigned or modified explicitly or implicitly (like in a for loop).
    5. When I call another method, if X happens to be a class variable it may change out from underneath me with no way for me to know this without inspecting the code of that method.
    6. In the context of a threading program it's even worse. X can be changed by something I can't even see in my immediate environment. Another thread may be calling the method in #5 that modifies X.

    And Java is a relatively simple OOP language. The number of ways that X can be screwed around with in C++ is even higher and potentially more obscure.

    And the thing is? This is just a simple example of how a common operation can be far more complicated in an OOP (or other imperative) language than in a functional. It also doesn't address the benefits of functional programming that don't involve mutable state, etc. like higher order functions.