In a C++ book, the author says we no longer need a function with a long parameter list because most of the parameters can be refactored into state variables in a class. On the other hand, a functional programming book says state variables are evil because it causes side-effects which cause bug-prone and hard to parallelize code. I'm getting puzzled. Should the code avoid relying on state variables as much as possible by moving its state variable into the function parameter list?
- Anybody can ask a question
- Anybody can answer
- The best answers are voted up and rise to the top
Depends if you are programming in a
You can apply single assignment and other functional techniques to imperative procedural languages, immutable state makes concurrent programming more deterministic, but making every object immutable in a language like Java or C++ is almost impossible because their memory models don't easily support this paradigm.
If I understand your question right, you are questioning what conditions qualify either the use of a parameter or class variable/member/field/etc? I'm assuming you're referring to a method, and not a function. If this is about C++ specifically, I suggest moving your question to stack overflow.
A long parameter list may be a sign that you might need to refactor your method into a set of more granular ones. Generally, using parameters will make your code more loosely coupled. I'm not sure if this is true for most modern OO languages anymore, but object creation can be expensive, especially if there are many class variables involved; so, if your class variables were objects and were referenced frequently in a program, then they may be justified as being class variables.
No, state variables per se do not cause side effects.
Calling a setter method (on a data structure that is visible elsewhere) is a side effect.
You can have data structures to hide long parameter lists ansd yet avoid side effects if you construct them accordingly. Here is a small example (in Java, untested):
Of course, the constructor of ManyParams will still have a long parameter list this way. But its hidden.