Recently, I needed to generate a file with a specific format based on information in the database. My first tendency was to implement a method like writeOn for each of my domain objects and pass the file stream as a parameter. I quickly found that this technique was going to be difficult. Often times, you don't know what information to write until you're past the point where you had the ability to write it. Sometimes the order that you traverse the domain objects isn't the best order to write them. What I find works better in those cases is to traverse the domain objects to create an intermediate form then traverse the intermediate form to write the final file. This way, you have the option to augment, change or rearrange the information before you finally write it out.
Download