Where can I put formatting logic?

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 can display the amount either $1,000on a web page or 1000.00when loading Excel. I also want to be able to reuse the same formatting code in different places. Some of them will be simple (for example, displaying a date in a specific format), but some of them will be more complex (for example, 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 several places:

  • Add methods to the data object, such as getAmountHTML()or getAmountExcel(). Convenient, but does it make the model too tightly coupled?

  • Format in the template when displaying data. Flexible, but since it is not in the method, I cannot easily reuse the same formatting in different places.

  • Create a formatting class for each data class and give it a link to the source data object.

I will have many data objects to format, so I would suggest a good approach. Is there anyone who has the relevant experience?

+3
source share
2 answers

Vivin , . , .

, , - , . Transaction :

public String getFormattedString(Formatter f);

, , . , .

+4

IMO, . JSTL, <fmt:formatNumber>.

1, , . - (, 5 - ?).

3, , - , 1.

2. 3 2. FormattingService, . , .

+2

Source: https://habr.com/ru/post/1761820/


All Articles