Passing several primitive type members vs passing the outer mutable object - does functional programming express any preference?

StackOverflow https://stackoverflow.com/questions/20104941

Question

Functional programming attempts to ensure freedom from side-effects when invoking functions. Passing a mutable object as a parameter that is NOT returned gives a developer the ability to modify a non-returned object. In other words, side-effects are possible. If you pass primitive or immutable types, you are free from this extra layer of complexity when reasoning about a program. So does good Functional Programming practice dictate anything when you have the choice between passing a mutable object vs passing primitive types?

I am aware of the following properties of PURE functional programming:

  • If all your types are immutable, it doesn't matter whether they are object types
  • The mutable object cannot exist outside the scope where it is expected to be mutated

but in reality when you are dealing with huge code bases that have existed prior to Functional Programming gaining a newfound respect, you will often be dealing with data structures that have no corresponding immutable representation, and code will be a mixture of functional and imperative styles.

(Background - I am exposing C++ logic via Java Native Interface and am wondering when to avoid passing objects, but I'm not looking for an answer that directly applies to this use case. I just want some help applying good programming practice in a situation such as this)

Was it helpful?

Solution

I think the only thing that functional programming has to say about this matter is that you should ideally wrap all impure stuff that you expose, in a monad, such as the famous IO monad.

But this is probably too radical for your users.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top