I was working with some code recently that needed to print reports. To do that, it needed to traverse some object structures. During the traversal, it was doing two things. First, it was writing out the report specifying things like font size, text color, border width and spacing. Second, it was accumulating subtotals and collecting summaries to report on later. This approach fell apart when I was asked to implement a new reporting mechanism. With this new mechanism, the report's format was supplied by an external style sheet and didn't need to be specified by the software. I still needed the subtotals and summaries, however. By combining these into one loop, I couldn't run the subtotalling code without also running the formatting code. When you have two distinct pieces of work to do, you should try to separate them and not try to do them together. In this case, I was able to caculate the subtotals as a stand-alone task then produce the report in either the old way or the new way using the pre-computed subtotals. If you can separate the work into distinct concerns, you make it easier to separate those concerns in the future.
Download