Remember that patterns are not magical recipes. There's no pattern for every single problem. And not every problem respond to a pattern.
In this specific case, as @Mike Nakis already pointed out, the problem could be the way you are expressing the concept Price
. It lacks on meaningful information and valuable resources. For example, even the Webservice's consumer might need to know the currency or the amount in its read-only format. Isn't it?
Right now, Price
is only wrapping a float.
What if we provide it with some more relevant information?1. For example
public class Prize {
BigDecimal amount;
Locale locale;
public BigDecimal getAmount(){ ... }
public String getCurrencyCode(){
return Currency.getInstance(locale).getCode();
}
public String getCurrencySymbol(){
return Currency.getInstance(locale).getSymbol();
}
public String getFormattedAmount(){
return DecimalFormat.getCurrencyInstance(locale).format(amount);
}
}
Now, Price
is capable of transferring any piece of info that users / webservices might need to know. For example, sending getAmount
alongside with getCurrencyCode
allow consumers to do currency conversions. On the other hand, If we don't want consumers to modify the amount
or its representation, we could send only the getFormattedAmount
.
Back to the main question, due to the Price
itself is capable of transferring its representantation in different ways, we don't need to copy-paste the transformations all over the code.
1: This approach could take you to save the locale or the currency too.
According to the Java API, Locale seems to me a more valuable info to persist than currency code. Or save both.
For further information about Currency, check out the API Doc.