简体   繁体   中英

How can i refactor multiple if conditions and multiple operators so that i can reduce code complexity in java

I have a java code where i'm calling database function for data insertion. Function may returns error code on the basis of exception in Database. To show those errors on the screen i have written bellow code.

String DBerrorCode=DatabaseReturnErrorCode;//Errorcode from Database

if("RUREF00001".equals(DBerrorCode)){
    throw new DataUpdateException(ErrorRUREF00001);
}else if("RUREF00002".equals(DBerrorCode)){
    throw new DataUpdateException(ErrorRUREF00002);
} else if("RUREF00003".equals(DBerrorCode)){
    throw new DataUpdateException(ErrorRUREF00003);
} else if("RUREF00004".equals(DBerrorCode)){
    throw new DataUpdateException(ErrorRUREF00004);
} else if("RUREF00005".equals(DBerrorCode)){
    throw new DataUpdateException(ErrorRUREF00005);
} else if("RUREF00006".equals(DBerrorCode)){
    throw new DataUpdateException(ErrorRUREF00006);
} else if("RUREF00027".equals(DBerrorCode)){
    throw new DataUpdateException(ErrorRUREF00027);
} else if("RUREF00028".equals(DBerrorCode)){
    throw new DataUpdateException(ErrorRUREF00028);
} else if("RUREF00029".equals(DBerrorCode)){
    throw new DataUpdateException(ErrorRUREF00029);
} else if("RUREF00030".equals(DBerrorCode)){
    throw new DataUpdateException(ErrorRUREF00030);
} else {
  //default error
    throw new DataUpdateException(DATA_INSERT_ERROR);
}

My requirement is to reduce multiple operators, if conditions,no more than 3 operators in on if statement and light weight code where less memory is used.

Kindly suggest if anyone have any creative solution.

for (int i=1; i<=6; i++){
    String s = "RUREF0000" + i;
    //Define your error
    if(s.equals(DBerrorCode)){
            throw new DataUpdateException(your error);
    }

the same for the i = [27,30]

finally you can put a if condition for the cases (i<1, i>6 and i<27, i>30) as the default error

also you can define switch cases https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

but this won't reduce your code length. It depends on what is your task

I'll use a Map.

map.put("RUREF00001",ErrorRUREF00001);
map.put("RUREF00002",ErrorRUREF00002);
map.put("RUREF00003",ErrorRUREF00004);

And then you simply write a line that

throw new DataUpdateException(map.get(DBerrorCode));

Side note : Java variable names starts with lower case letter.

Indeed, you may use a Map like other answers suggest .

Assuming the parameter (eg ErrorRUREF00001 ) you pass to DataUpdateException is a String :

Map<String, String> errorMap = new HashMap<>();

errorMap.put("RUREF00001", ErrorRUREF00001);
// populate other values ....

Then you may have a method to check the mapped message, use that if one is found, use the other value if none is found :

public void manageError(final String dbErrorCode) {

    if (errorMap.containsKey(dbErrorCode)) {

        throw new DataUpdateException(errorMap.get(dbErrorCode));
    } else {

        throw new DataUpdateException(DATA_INSERT_ERROR);
    }
}

Finally instead of you if else statements, just call

   manageError(DatabaseReturnErrorCode);

For omitting if-else statements you can use Enum .

Your logic should be like below:

  • get the string code value
  • iterate over enum values with Enum.values()
  • if string value match some error code -> throw new Exception() with this code, like parameter
  • if no match throw default Error at the end.

Here is small demo:

enum ErrorCodes {
    RUREF_00001("RUREF00001"),
    RUREF_00002("RUREF00002"),
    RUREF_00003("RUREF00003");
    // ...
    private String errorName;

    ErrorCodes(String errorName) {
        this.errorName = errorName;
    }

    public String getErrorName() {
        return errorName;
    }
}

public class ErrorHandler {
    public static void main(String[] args) {
        String dbErrorCode = "ruref00003"; // get the error code from Database

        for (ErrorCodes code : ErrorCodes.values()) {
            if (code.getErrorName().equalsIgnoreCase(dbErrorCode)) {
                throw new DataUpdateException(dbErrorCode);
            }
        }
        //default error
        throw new DataUpdateException(DATA_INSERT_ERROR);
    }
}

Thus all your if-else statements will be replaced with few lines:

   for (ErrorCodes code : ErrorCodes.values()) {
      if (code.getErrorName().equalsIgnoreCase(dbErrorCode)) {
         throw new DataUpdateException(code);
      }
   }

It is much more elegant solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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