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?
array1string
andarray2string
will never be equal tonull
; you're giving them each a value near the start of the code segment. They might result in empty strings, but they're notnull
. \$\endgroup\$