简体   繁体   English

使用 jdk11 编写多个 if else 条件的更好方法

[英]better approach to write multiple if else conditions using jdk11

I have a code block that redirects a query to different tables based on the logical conditions inside multiple if conditions as shown below.我有一个代码块,它根据多个 if 条件中的逻辑条件将查询重定向到不同的表,如下所示。 Is there a better approach using jdk11 or jdk8 for the below scenario.对于以下场景,是否有更好的方法使用 jdk11 或 jdk8。

List<String> processTable(Rating ratingRequest) {
List<String> ids = new ArrayList(); 
if(ratingRequest.postCode()!=null){
   //ids = querycall
  return ids;
}
if(ratingRequest.getRatingValue()!=null){
  //ids = queryCall
  return ids;
}
if(StringUtils.isNotEmpty(ratingRequest.getPostalName()) && ratingRequest.getRatingValue!=null){
   if(StringUtils.isNotEmpty(ratingRequest.getPostalContractNumber())){
         //ids = businesslogic
          return ids;
}
 if(somecondition..){
       //ids=..
}else{
    // ids=..
}
return ids;
...
}

Rating.java评级.java

Class Rating{
String postCode;
String ratingValue;
String postalName;
Date contractEndDate;
String postalContractNumber;
//getters and setters
}

If you find your self with multiple conditions.如果你发现自己有多种情况。 Then a switch case statement would be your best bet or simplifying your logical input / output那么 switch case 语句将是你最好的选择或简化你的逻辑输入/输出

switch (variable or an integer expression)
{
    case constant:
    //Java code
    ; // just added to to prevent exception, an expression would or operation would be here. Since there's no break it would enter and continue checking for other cases.
    case constant:
    //Java code
    break;
    ;
    default:
    //Java code
    // default switch, if no case are true. Though, not required it's best practice to include.
    ;
}

NOTE : You can have a switch case enter multiple Case statements, or you can break and immediately exit once the operation has completed.注意:您可以让 switch case 输入多个 Case 语句,也可以在操作完成后立即break并退出。

I suppose you can use a function.我想你可以使用一个函数。

static boolean checkIfNull(int a) {
// code to be executed
  return a != null;
}

static boolean checkIfEmpty(int b) {
// code to be executed
  return StringUtils.isNotEmpty(b) != False;
}

List<String> processTable(Rating ratingRequest) {
List<String> ids = new ArrayList(); 
if(checkIfNull(ratingRequest.postCode())){
  //ids = querycall
  return ids;
}
if(checkIfNull(ratingRequest.getRatingValue())){
 //ids = queryCall
 return ids;
}
if(checkIfEmpty(ratingRequest.getPostalName()) && 
 checkIfNull(ratingRequest.getRatingValue){
 if(!checkIfEmpty(ratingRequest.getPostalContractNumber())){
     //ids = businesslogic
      return ids;
}

if(somecondition..){
   //ids=..
}else{
// ids=..
}
 return ids;
 ...
}

NOTE : This just condenses everything.注意:这只是浓缩了一切。 Please bare that in-mind, it does not simplify your logic per-say.请记住这一点,它不会简化您的逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM