Java Tip #8: Use StringUtils for concatenating Strings from Arrays or Lists
And we're continuing with our next Java Tip. Back on using frameworks for our convenience, I present another often useful possibility to let the StringUtils handle lots of work for you.
Advice
Use Apache StringUtils for concatenating Strings from Arrays or Lists, also when you need to delimit them with an arbitrary string.
Code-Example
Before
...
SQL_WHERE += " AND V.cat_display_name IN (";
boolean addComma = false;
for (String category : filter.getCategories()) {
if (addComma) {
SQL_WHERE += ", ";
}
SQL_WHERE += "'" + category + "'";
addComma = true;
}
SQL_WHERE += ") ";
...
...
String SQL = "";
for(String category: filter.getCategories()) {
SQL += val + ", ";
}
SQL = SQL.substring(0, SQL.length()-2);
....
After
...
SQL_WHERE += " AND V.cat_display_name IN (";
SQL_WHERE += "'" + StringUtils.join(filter.getCategories(), "', '") + "'";
SQL_WHERE += ") ";
...
Benefit
Huge readability gain and a safety gain. The code and intention is much clearer and the possibility to hide bugs in the loop-logic (which I have seen often) is not present. Also, depending on the length of the Array or List, it may also present a small performance gain (see Java Tip #2) but that's in most such cases neglibigle.
Remarks
None.