When the code flow is like this:
if(check())
{
...
...
if(check())
{
...
...
if(check())
{
...
...
}
}
}
I have generally seen this work around to avoid this messy code flow:
do {
if(!check()) break;
...
...
if(!check()) break;
...
...
if(!check()) break;
...
...
} while(false);
What are some better ways that avoid this workaround/hack so that it becomes a higher-level (industry level) code?
Are there maybe constructs that come from Apache commons or Google Guava?
Note: this is a copy of the same question for C++. The best answers there are truly functions pointers and the GOTO command. Both doesn't exist in Java. I am eagerly interested in the same thing for Java.
Putting it into a new function and using return is in my opinion not a good solution, because return quits the method. So if my class has 20 methods with these constructs, I would have to add 20 additional methods to get this done. That's why GOTO was the best answer for C++.
What is this "while(false)" nonsence? Use a label!
myLabel: {
if(!check()) break myLabel;
...
...
if(!check()) break myLabel;
...
...
if(!check()) break myLabel;
...
}
It's core Java: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
To reduce the cyclomatic complexity, you can separate the logics into submethods:
public void go() {
first();
}
public void first() {
if(check()) {
// #1
second();
}
}
public void second() {
if(check()) {
// #2
third();
}
}
public void third() {
if(check()) {
// #3
}
}
Because you can have this 20 times in a function to pass 20 serial steps. If I do it like this, the final if slides already 20 tabs to the right, which makes the code unreadable.
This comment of yours shows the issue: you are imagine the wrong code structure.
For example your code is like this
if (bool) {
// do something
if (anotherBoolean) {
//do even more
if (thirdBoolean) {
// here we go! I spare deeper structure...
}
}
}
This can be refactored easily to:
public void method() {
if (bool) {
doSomeStuff();
}
}
public void doSomeStuff() {
if (anotherBoolean) {
doThirdStuff();
}
}
public void doThirdStuff() {
if (thirdBoolean) {
doEvenMore();
}
}
public void doEvenMore() {
// deeper structure
}
That kind of code structure would be a good sample of Clean Code as the methods are doing their "single purpose" stuff, you don't do a while-loop hack plus you even might reuse the methods somewhere.
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