I have several classes with raw data, for example:
public interface Transaction {
public double getAmount();
public Date getDate();
}
I need to output formatted versions of this data in several places. For example, I might display the amount as $1,000 on a web page, or 1000.00 on an Excel download. I also want to be able to reuse the same formatting code in different places. Some of it will be simple (like displaying a date in a certain format), but some will be more complex (like displaying different values for one field depending on the value of another field).
My question is: where should I put the formatting code? I can think of a few places:
Add methods to the data object like
getAmountHTML()orgetAmountExcel(). Convenient, but does it make the model and view too closely related?Do the formatting in the template, when displaying the data. Flexible, but since it isn't in a method, I can't easily reuse the same formatting in different places.
Create a formatting class for each data class, and give it a reference to the original data object.
I'm going to have a lot of data objects to format, so I'd like to come up with a good approach. Is there anyone with some relevant experience to share?