I want to reduce the nesting of if statements in java.

Asked 2 years ago, Updated 2 years ago, 27 views

If there is a nested if statement like the one below, is there a good way to make it depth 1?

 if(a==null){
    if(b=="Ahhhhhhhhhhhhhhhhhhhh
        running text
    }
    if(c=="good"){
        running text
    }
}

java

2022-09-30 10:47

3 Answers

If there is no further action, it simply returns as follows.

 if(a!=null){
  return;
}
if(b=="Ahhhhhhhhhhhhhhhhhhhh
  running text
}
if(c=="good"){
  running text
}

If there is subsequent action, you may be able to reduce nesting of if statements by using break in do-while statements.

do{
  if(a!=null){
    break;
  }
  if(b=="Ahhhhhhhhhhhhhhhhhhhh
    running text
  }
  if(c=="good"){
    running text
  }
} while(false);


2022-09-30 10:47

Hello, nice to meet you.

I think the example you gave me is an easy-to-understand code.
In my opinion, it is better not to fix it for readability.

However, use equals for string comparison in Java without exception.

 if(a!=null){
  if(b.equals("Ah"){
     running text
   }
 if(c.equals("good")}
     running text
  }
}

Connect & (a!=null&&b.equals("Ahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

Also, if the variable a is an argument for a function, you can use the @NotNull annotation to check the compilation check.It's definitely this direction these days.

public void yourCoolFunction(@NotNullfinalStringa){
 if(b.equals("Ah"){
   // Implementation
 }
 if(c.equals("good")}
   // Implementation
 }
}


2022-09-30 10:47

Example code to reduce nesting.

 if(a==null&b=="Ahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
    running text
}
if(a==null&c=="good"){
    running text
}

It's not the point of the question, but I think it's better to use the equals method to compare whether the contents of the string are the same.
b.equals("Ah")


2022-09-30 10:47

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.