jeudi 16 juin 2016

Avoid multiple if else

I have the following scenario where,

A String arr[] as input which can have Integer values,null or empty as string. (e.g) {"230",null,"6",""}

Now,

1. If a null or empty string present in first two entries of arr , it is a invalid scenario print nothing.

2. If a null or empty is present in last two entries of arr, and first two entries are not null and not empty print first two entries.

(e.g) If arr[] is {"2","77",null,"5"} output will be 2,77.

3. If no entry in arr[] is neither null nor empty check if all entries are numeric. If not print nothing.

Now my code goes like this,

       simple validation(){
       onlyFirstTwoNotNullOrNotEmpty = false;
       if(//Check if first two param are null){
               "print nothing" and return
        }else if(check if third **or** fourth param is null){
          onlyFirstTwoNotNullOrNotEmpty = true; // setting a boolean 
        }

        //Proceed to check empty string
        if(//Check if first two param are empty){
               "print nothing" and return
        }else if(!onlyFirstTwoNotNullOrNotEmpty) //checking if null 
            if(check if third **or** fourth param is empty){
          onlyFirstTwoNotNullOrNotEmpty = true; // setting a boolean 
        }

       //if all values are not null and not empty      
      //onlyFirstTwoNotNullOrNotEmpty  will be still false

      String result;
      if(onlyFirstTwoNotNullOrNotEmpty ){
      result = checkIfNumeric(0,1); // only first two entries
      }else{
      result = checkIfNumeric(0,arr[arr.length-1]); // for all entries
      }
      if(!result.equals("success")){
      return and print nothing
      }
      if(onlyFirstTwoNotNullOrNotEmpty){
      print only first two and return;
      }
      print all entries and return;

How can i better optimize this code with less if and else loops. Am new to java 8 are there any possibilities via lambda expressions?

I don't want to use a third party API for null or Empty check of a string.

Aucun commentaire:

Enregistrer un commentaire