I need to figure out how to improve following code:
for (DirCategory c1 : categories1) {
c1.setCount(dirEntryService.getDirEntryCategoryCount(c1));
log.debug("c1: "+c1.getCount()+" - "+c1.getName());
dirCategoryService.persist(c1);
List<DirCategory> categories2 = c1.getChildren();
for (DirCategory c2 : categories2) {
c2.setCount(dirEntryService.getDirEntryCategoryCount(c2));
log.debug(" c2: "+c2.getCount()+" - "+c2.getName());
dirCategoryService.persist(c2);
List<DirCategory> categories3 = c2.getChildren();
for (DirCategory c3 : categories3) {
c3.setCount(dirEntryService.getDirEntryCategoryCount(c3));
log.debug(" c3: "+c3.getCount()+" - "+c3.getName());
dirCategoryService.persist(c3);
List<DirCategory> categories4 = c3.getChildren();
for (DirCategory c4 : categories4) {
c4.setCount(dirEntryService.getDirEntryCategoryCount(c4));
log.debug(" c4: "+c4.getCount()+" - "+c4.getName());
dirCategoryService.persist(c4);
List<DirCategory> categories5 = c4.getChildren();
for (DirCategory c5 : categories5) {
c5.setCount(dirEntryService.getDirEntryCategoryCount(c5));
log.debug(" c5: "+c5.getCount()+" - "+c5.getName());
dirCategoryService.persist(c5);
List<DirCategory> categories6 = c5.getChildren();
for (DirCategory c6 : categories6) {
c6.setCount(dirEntryService.getDirEntryCategoryCount(c6));
log.debug(" c6: "+c6.getCount()+" - "+c6.getName());
dirCategoryService.persist(c6);
}
}
}
}
}
}
I would really appreciate any help simplifying this “thing”
This looks like a great job for recursion, since all of the loops have exactly the same structure and content. The recursive idea is to nest all the loops to some depth d, with the recursive structure being
This could be written as
You can then do the exploration by calling
explore.Of course, this approach works with the assumption that the depth is at most five. If you want to eliminate the depth requirement and just explore all the way down to the bottom of the directory, then you can just eliminate the depth parameter like this:
More generally, any time you want to nest an arbitrary number of loops inside of one another, consider recursion as an option. It’s a very general framework for expressing this concept.
Hope this helps!