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

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

  •  04-07-2021
  •  | 
  •  

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?

有帮助吗?

解决方案

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.

其他提示

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());

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?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top