Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean for an expression to contain "at most one side effect, as its outermost operation"?

Tags:

java

jls

In Java Language Spex 15.7:

Code is usually clearer when each expression contains at most one side effect, as its outermost operation

What does it mean?

like image 837
dhblah Avatar asked Sep 27 '12 10:09

dhblah


3 Answers

It means that each expression should do one task at a time.

Consider the following two declarations:

int a = 10;
int b = 20;

Now the task is to add these two ints and increment b by 1. There are two way to do it.

int c = a + b++;

and

int c = a + b;
b++;

JLS prefers and recommends the latter one.

like image 142
Azodious Avatar answered Nov 20 '22 08:11

Azodious


What this means is that:

int x = someFunction(a, b);

is clearer when someFunction(a, b) doesn't have any side-effect i.e. it doesn't change anything. Rather the only change in the above is the assignment to x.

Another example would be use of prefix/postfix incrementers.

int x = a + b;

is clearer than

int x = (a++) + (++b);

since only x is assigned to. In the second example a and b are changed in the same statement.

By limiting the side effects, you can more easily reason about the functioning of the code, and/or re-order statement invocations, including parallelising them e.g. in the below, if the methods don't have side-effects, then you can invoke the methods a(), b() and c() representing the arguments in any order, and/or in parallel.

int res = f(a(), b(), c());
like image 22
Brian Agnew Avatar answered Nov 20 '22 07:11

Brian Agnew


Side-effect of an expression is mostly an assignment to variable during evaluation of the expression.

Notice the code:

int x = 5, y = 7;
while ((z = x-- + --y) > 0 ) {
    console.out("What is 'z' now? " + z);
    console.out("How many times will this be printed?");
}

Evaluation of the condition has 3 side-effects:

  • decrementing x
  • decrementing y
  • assignment to z

Looks twisted, isn't it?

like image 41
Krzysztof Jabłoński Avatar answered Nov 20 '22 08:11

Krzysztof Jabłoński