Being a long-time Java programmer and in recent years a Haskell addict, I am learning Scala now. My question is:
How to program without side-effects in Java ?
i.e. How can I do manually what Scala does for me?
The Scala book from Odersky explains functional concepts in terms of OO-terminology often (e.g. val = final, if = ternary op.).
Is there an accessible guide how to program without side-effects in Java (as few as possible)? I guess one could get many of the known benefits with plain old java and a bit of discipline (e.g. unmodifiable collections, final values, rigid methods that don't modify object/application state).
To prevent side effects, just declare the fields as final . If all fields are final , the values (in case of primitive types) and object references are immutable. In case of an object reference, that object must be immutable as well to achieve "complete immutability".
Java tea might have an effect like a water pill or "diuretic." Taking java tea might decrease how well the body gets rid of lithium. This could increase how much lithium is in the body and result in serious side effects. Talk with your healthcare provider before using this product if you are taking lithium.
More generally, functional programs contain no side effects at all. A function call can have no effect other than to compute its result. This eliminates a major source of bugs, and also makes the order of execution irrelevant—since no side effect can change an expression's value, it can be evaluated at any time.
The two conditions that define a function as pure are as follows: No side effects (i.e. only changes to local scope are allowed) Always return the same output, given the same input.
abstract
or final
.final
.Array
, or i/o resources like files and database connections, never let them escape the scope in which they are constructed.See Functional Java.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With