I’m reading a book called Clean Code -A Handbook of Agile Software Craftsmanship written by Robert C. Martin and in his book he gives a lot of useful tips how to write good Java code.
And one of those tips is:
Blocks within if statements, else statements, for statements, and so
on should be one line long. Probably that line should be a function
call. Not only does this keep the enclosing function small, but it
also adds documentary value because the function called within the
block can have a nicely descriptive name
For me that was very strange hint, because from this code:
public Map<String, List<Issue>> mapComponentToIssueList(List<Issue> issues) {
Map<String, List<Issue>> map = new HashMap<String, List<Issue>>();
for (Issue issue : issues) {
String componentName = issue.getComponents().iterator().next().getString("name");
if (map.containsKey(componentName)) {
map.get(componentName).add(issue);
} else {
List<Issue> list = new ArrayList<Issue>();
list.add(issue);
map.put(componentName, list);
}
}
return map;
}
Using this principle I’ve got this:
public Map<String, List<Issue>> mapComponentToIssueList(List<Issue> issues) {
Map<String, List<Issue>> componentNameIssueListMap = new HashMap<String, List<Issue>>();
for (Issue issue : issues) {
populateMapWithComponenNamesAndIssueLists(componentNameIssueListMap, issue);
}
return componentNameIssueListMap;
}
private void populateMapWithComponenNamesAndIssueLists(Map<String, List<Issue>> componentNameIssueListMap, Issue issue) {
String componentName = getFirstComponentName(issue);
if (componentNameIssueListMap.containsKey(componentName)) {
componentNameIssueListMap.get(componentName).add(issue);
} else {
putIssueListWithNewKeyToMap(componentNameIssueListMap, issue, componentName);
}
}
private void putIssueListWithNewKeyToMap(Map<String, List<Issue>> componentNameIssueListMap, Issue issue, String componentName) {
List<Issue> list = new ArrayList<Issue>();
list.add(issue);
componentNameIssueListMap.put(componentName, list);
}
private String getFirstComponentName(Issue issue) {
return issue.getComponents().iterator().next().getString("name");
}
So basically the code has doubled in size.Was it useful? – Maybe.
What code in my example is so called clean? What am I doing wrong? What do you guys think about this?
Frankly, I think the tip is silly because it’s so extreme.
Personally, if I were to do anything to your function, I’d change it like so:
The benefits are:
list.add()call is not duplicated in two places.Now if you wanted to factor something out, the following would be a good candidate:
I would definitely do it if the above appeared in more than one place. Otherwise, probably not (at least not initially).