how to avoid multiple if-else statements for vaildation in Java

190
March 22, 2018, at 5:38 PM

I have lots of multiple if-else statements. For code optimization, I need to write one function for all if else logic. As of now my code structure is in below.

input request is in JSONObject(org.json.simple.JSONObject), which have more than 10 values.

  String s = (String) inputObj.get("test");
  String s1 = (String) inputObj.get("test");
  String s2 = (String) inputObj.get("test");
  String s3 = (String) inputObj.get("test");
        if (s != null && s.trim().isEmpty()) {
            if (s1 != null && s1.trim().isEmpty()) {
                if (s2 != null && s2.trim().isEmpty()) {
                    if (s3 != null && s3.trim().isEmpty()) {
                        if (s4 != null && s4.trim().isEmpty()) {
                           ........
                        } else {
                          return;
                        }
                    } else {
                        return;
                    }
                } else {
                     return;
                }
            } else {
               return;
            }
        } else {
           return;
        }

How to avoid this kind of looping and throw an error message in common method.

Advance thanks.

Answer 1
public class YourClass{
    private boolean isBlankDataPresent(JSONObject inputObj, String[] keys) throws Exception {
        for (String key : keys) {
            String input = (String) inputObj.get(key);
            if( input == null || input.trim().isEmpty())
                throw new Exception(key +" is Empty");
        }
        return false;
    }
    public boolean validateData(JSONObject inputObj, String[] keys) throws Exception {
        boolean isBlankDataPresent= isBlankDataPresent(inputObj, keys);
        if (!isBlankDataPresent) {
            // do Your Stuff and return true
        } 
    }
}
Answer 2

Consider adding all your strings to array or ArrayList of string, and looping thru each entry in it, and check them for null or emptiness.

Answer 3
    public Integer checkIsEmapty(String checkingString){
        if(checkingString != null && !checkingString.trim().isEmpty()){
            return 1;
        }
        return 0;
    }
    public String method(){
        String s ="";
        String s1 = "hi";
        String s2 = "java";
        String s3 = null;
        String s4 = null;
       Integer s1i = checkIsEmapty(s);
       Integer s2i = checkIsEmapty(s1);
       Integer s3i = checkIsEmapty(s2);
       Integer s4i = checkIsEmapty(s3);
       Integer s5i = checkIsEmapty(s4);
       Integer total = s1i + s2i + s3i + s4i + s5i;
       switch (total){
           case 1 :
               // To DO
           case 2 :
               // To DO

       }
    }
    in switch used to checking the value, U can pass binary and Integer also 
Answer 4

Like @Emre Acre mentioned,

List<String> sList = new ArrayList<>();
sList.add(inputObj.get("test"));
sList.add(inputObj.get("test"));
sList.add(inputObj.get("test"));
sList.add(inputObj.get("test"));
boolean allDataValid = sList
        .stream()
        .allMatch(s -> s != null && s.trim().isEmpty());
if(allDataValid) {
    ......
} else {
    return;
}
Answer 5

You can try this.

void main() {
    List<String> sList = new ArrayList<>();
    sList.add(inputObj.get("test"));
    sList.add(inputObj.get("test"));
    sList.add(inputObj.get("test"));
    sList.add(inputObj.get("test"));
    for(String s : sList){
        try {
            checkString(s);
        }catch (Exception e){
            //log or print the exception, however you like
        }
    }
}
void checkString(String s) throws Exception{
    if(s!= null && !s.trim().isEmpty()){
        //doStuff
    }else{
        throw new Exception("String is null or empty !!!");
    }       
}

You should also check this out.

Rent Charter Buses Company
READ ALSO
how to persist fos_user data from java desktop application

how to persist fos_user data from java desktop application

We are five students in a team working on a project using SCRUM methodeOur first sprint was WEB application

180
How to identify project type from project folder

How to identify project type from project folder

Recently i have received a project as a zipI have unzipped and now i want to import the same in eclipse

265
Array Converted to Stack

Array Converted to Stack

How can you take an array and put it into a stack???? I have a card array with a deck of cards that gets shuffled then I need to change it to a stack and print the first number on topAnyway anyone can help?

202
MessagePack performance seems bad over serialization time

MessagePack performance seems bad over serialization time

I am trying to figure out the best way to store my java POJO in redis to reduce memory usageRight now I am saving object directly in JSON format after stringyfy pojos to JSON using Jackson

207