solven-eu / cleanthat

Github App opening automatically cleaning PR
56 stars 16 forks source link

LambdaIsMethodReference mutator could introduce side effects #847

Open mches opened 1 week ago

mches commented 1 week ago

An expression lambda like s -> b.append("/").append(s) can't be converted to a method reference because b.append("/") has a side effect

String a = null;
StringBuilder b = new StringBuilder();
Optional.ofNullable(a).ifPresent(s -> b.append("/").append(s));
System.out.println(b);

Output:

↓↓↓

String a = null;
StringBuilder b = new StringBuilder();
Optional.ofNullable(a).ifPresent(b.append("/")::append);
System.out.println(b);

Output:

/

Seems safer to assume a call chain produces a side effect and give up on converting such a lambda expression to method reference.

blacelle commented 1 week ago

Fixed in https://github.com/solven-eu/cleanthat/pull/849

mches commented 1 week ago

Bravo! 👏🏻