HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Improve my if-statement to prevent double checks

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
preventchecksstatementimprovedouble

Problem

I write the following version of an if-statement very often. And every time, I hate the way that I make it, but I don't know how to improve it.

For example, I have two ArrayList's. If one of them is not empty, then I convert it to a StringBuilder and send it per mail. The problem is, first I check if one of them is not empty to know if I should send a mail, and then I check it again to know which of them is not empty. Example code:

if(!array1.isEmpty() || !array2.isEmpty()){
   // I need to distinguish the StringBuilder
   StringBuilder array1string = new StringBuilder();
   StringBuilder array2string = new StringBuilder();
   // so one of them is not empty. but which? now I must double check it
   if(!array1.isEmpty()){
      for(String string : array1){
         array1string.append(string);
      }
   }
   if(!array2.isEmpty()){
      for(String string : array2){
         array2string.append(string);
      }
   }
   mail.sendMail("Array1: " + array1string == null?"-":array1string.toString() 
      + ", Array2: " + array2string == null?"-":array2string.toString());
}


So is there a way to prevent this double check?

Solution

Your code can be shortened to:

if(!array1.isEmpty() || !array2.isEmpty()) {
    mail.sendMail("Array1: " + getContent(array1) + ", Array2: " + getContent(array2));
}


When you have:

String getContent(ArrayList list) {
    if(!list.isEmpty()) {
        StringBuilder sb = new StringBuilder();
        for(String string : list) {
            sb.append(string);
        }
        return sb.toString();
    }
    return "-";
}

Code Snippets

if(!array1.isEmpty() || !array2.isEmpty()) {
    mail.sendMail("Array1: " + getContent(array1) + ", Array2: " + getContent(array2));
}
String getContent(ArrayList<String> list) {
    if(!list.isEmpty()) {
        StringBuilder sb = new StringBuilder();
        for(String string : list) {
            sb.append(string);
        }
        return sb.toString();
    }
    return "-";
}

Context

StackExchange Code Review Q#35584, answer score: 13

Revisions (0)

No revisions yet.