Standing on the shoulders (well, maybe feet) of giants
[ start | index | login or register ]
start > Value Object Motivation v2

Value Object Motivation v2

Created by Dirk Riehle. Last edited by Dirk Riehle, 2 years and 110 days ago. Viewed 734 times. #1
[edit] [rdf]
labels
attachments
Consider a financial services application for handling deposits and withdrawals to and from accounts. You are dealing with monetary amounts like ‘$42’ or ‘€107’. Let’s assume you need to maintain the balance for some account. It is tempting then to represent the balance using a currency symbol and a BigDecimal for the monetary amount.

public class Account {

protected char currency = '$'; protected BigDecimal balance = BigDecimal.ZERO; …

}

After a short consideration, you decide it is better to create a dedicated Money class to hold both the currency symbol and the monetary amount. The Money class will have methods for getting and setting the currency symbol, as well as methods for doing some arithmetic with the monetary amount, like adding or subtracting money.

public class Money {

public static final Money ZERO =