I have just completed a test for a method that parses a forward-slash delimited String:
private static final String PROJECTID_STR_1 = "";
private static final String PROJECTID_STR_2 = "101/103/102/104/105/106/107";
private static final String PROJECTID_STR_3 = "///103/104";
private static final String PROJECTID_STR_4 = "a/b/102/104/105/106/107";
@Test
public void testParseProjectIds1() {
List<integer> projectIdList1 =
getViewBillingReportController().parseProjectIds(PROJECTID_STR_1);
assertTrue(projectIdList1.size() == 0);
}
@Test
public void testParseProjectIds2() {
List<integer> projectIdList2 =
getViewBillingReportController().parseProjectIds(PROJECTID_STR_2);
assertTrue(projectIdList2.size() == 7);
}
@Test
public void testParseProjectIds3() {
List<integer> projectIdList3 =
getViewBillingReportController().parseProjectIds(PROJECTID_STR_3);
assertTrue(projectIdList3.size() == 2);
}
@Test
public void testParseProjectIds4() {
List<integer> projectIdList4 =
getViewBillingReportController().parseProjectIds(PROJECTID_STR_4);
assertTrue(projectIdList4.size() == 5);
}
This test initially failed all but one of the assertions (it passed the happy path).
The initial method looked like this:
public List<integer> parseProjectIds(String projectIdsStr) {
ArrayList<integer> result = new ArrayList<integer>();
int lastDelimiterLoc = -1;
boolean done = false;
while (!done) {
int delimiterLoc = projectIdsStr.indexOf('/', lastDelimiterLoc + 1);
if (delimiterLoc >= 0) {
String idStr = projectIdsStr.substring(lastDelimiterLoc + 1, delimiterLoc);
Integer id = new Integer(idStr);
result.add(id);
lastDelimiterLoc = delimiterLoc;
} else {
delimiterLoc = projectIdsStr.length();
String idStr = projectIdsStr.substring(lastDelimiterLoc + 1, delimiterLoc);
Integer id = new Integer(idStr);
result.add(id);
done = true;
}
}
return result;
}
I don’t know why the developer on this would have done it this way, since we already had Commons Lang available in the classpath. But after a quick refactoring I came up with this:
public List<integer> parseProjectIds(String projectIdsStr) {
ArrayList<integer> result = new ArrayList<integer>();
if(StringUtils.isNotBlank(projectIdsStr)) {
String[] parsedList = StringUtils.split(projectIdsStr, "/");
for( int i =0; i < parsedList.length; i++) {
if( StringUtils.isNotEmpty(parsedList[i])){
if( StringUtils.isNumeric(parsedList[i])) {
result.add(new Integer(parsedList[i]));
}
}
}
}
return result;
}
This passed all my tests, and seems much more readable. This is how StringUtils rocks!
PS- StringUtils.isNotBlank also handles null values.
Post a Comment