I\'m kinda waiting for a \'no\' answer on this question.
I was interested if you can save a variable at the same time when you checking it in an if-clause.
From the department "My Programming Language is Better Than Your Programming Language": In Groovy, you can use the "?." operator:
Bar bar = foo?.bar
if (bar != null) {
}
In Java, this is good pattern(*):
Bar bar = foo == null ? null : foo.getBar();
if (bar != null) {
}
*: Something you can save in your fingertips.
if you want to limit the scope of Bar bar I'd add { and } around the code that Michael posted.
void foo() { // some code ... // this block limits the scope of "Bar bar" so that the rest of the method cannot see // it. { Bar bar; if(foo!=null && (bar = foo.getBar())!=null){ System.out.println("Success: " + bar); } else { System.out.println("Failiure."); } } }
You might also want to check into the null object pattern if it makes sense. I personally try to avoid things being null if I can... really think about if you want null to be allowed or not.
Actually I think that is a way to do this using Java Optional, here's an example:
Optional.ofNullable("text").ifPresent( $0 -> {
System.out.println($0.toUpperCase());
});
Or in your case:
if(foo != null){
Optional.ofNullable(foo.getBar()).ifPresent(bar -> {
System.out.println("Success: " + bar);
});
}
This is the closest you can get:
Bar bar;
if(foo!=null && (bar = foo.getBar())!=null){
System.out.println("Success: " + bar);
} else {
System.out.println("Failiure.");
}
Three points that completely fail to answer the question:
null
is evil. Don't write methods that return it. Your example problem would then disappear.
I think you might be missing out on encapsulation. Instead of foo.getBar()
could the interface of foo
be made such that you perform a "tell don't ask" operation?
Side-effects in expression tends to cause bad code. Prefer more, simpler lines to fewer, buggy lines. The usual exception if using ++
to increment an index when accessing a buffer, or similar iterator style algorithms.
I have used that technique when iterating over lines from a BufferedReader:
BufferedReader br = // create reader
String line
while ((line = br.readLine()) != null) {
// process the line
}
So yes, you can do an assignment, and the result off that will be the left hand side variable, which you can then check. However, it's not legal to declare variables inside a test, as they would then only be scoped to that expression.