Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to program without side-effects in Java?

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).

like image 900
Bastl Avatar asked Dec 05 '11 13:12

Bastl


People also ask

How do I stop side effect in Java?

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".

What are the side effects of java?

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.

Do functional programs have side effects?

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.

What is meant by no side effects in functional programming?

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.


2 Answers

  1. Make every method, field, and class either abstract or final.
  2. Make every variable and method parameter final.
  3. If you use mutable structures like Array, or i/o resources like files and database connections, never let them escape the scope in which they are constructed.
like image 63
Apocalisp Avatar answered Oct 31 '22 04:10

Apocalisp


See Functional Java.

like image 26
Daniel C. Sobral Avatar answered Oct 31 '22 05:10

Daniel C. Sobral