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 int
s 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:
x
y
z
Looks twisted, isn't it?
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