Skip to content

Commit d95c679

Browse files
committed
docs: update money pattern
1 parent 076fc21 commit d95c679

File tree

5 files changed

+84
-134
lines changed

5 files changed

+84
-134
lines changed

Diff for: money/README.md

+74-103
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,13 @@
22
title: "Money Pattern in Java: Encapsulating Monetary Values with Currency Consistency"
33
shortTitle: Money
44
description: "Learn how the Money design pattern in Java ensures currency safety, precision handling, and maintainable financial operations. Explore examples, applicability, and benefits of the pattern."
5-
category: Behavioral
5+
category: Structural
66
language: en
77
tag:
8-
- Encapsulation
8+
- Business
9+
- Domain
10+
- Encapsulation
11+
- Immutable
912
---
1013

1114
## Also known as
@@ -14,147 +17,115 @@ tag:
1417

1518
## Intent of Money Design Pattern
1619

17-
The Money design pattern provides a robust way to encapsulate monetary values and their associated currencies. It ensures precise calculations, currency consistency, and maintainability of financial logic in Java applications.
20+
Encapsulate monetary values and their associated currency in a domain-specific object.
1821

1922
## Detailed Explanation of Money Pattern with Real-World Examples
2023

21-
### Real-world example
24+
Real-world example
2225

23-
> Imagine an e-commerce platform where customers shop in their local currencies. The platform needs to calculate order totals, taxes, and discounts accurately while handling multiple currencies seamlessly.
26+
> Imagine an online gift card system, where each gift card holds a specific balance in a particular currency. Instead of just using a floating-point value for the balance, the system uses a Money object to precisely track the amount and currency. Whenever someone uses the gift card, it updates the balance with accurate calculations that avoid floating-point rounding errors, ensuring the domain logic stays consistent and accurate.
2427
25-
In this example:
26-
- Each monetary value (like a product price or tax amount) is encapsulated in a `Money` object.
27-
- The `Money` class ensures that only values in the same currency are combined and supports safe currency conversion for global operations.
28-
29-
### In plain words
28+
In plain words
3029

3130
> The Money pattern encapsulates both an amount and its currency, ensuring financial operations are precise, consistent, and maintainable.
3231
33-
### Wikipedia says
32+
Wikipedia says
33+
34+
> The Money design pattern encapsulates a monetary value and its currency, allowing for safe arithmetic operations and conversions while preserving accuracy and consistency in financial calculations.
35+
36+
Mind map
3437

35-
> "The Money design pattern encapsulates a monetary value and its currency, allowing for safe arithmetic operations and conversions while preserving accuracy and consistency in financial calculations."
38+
![Money Pattern Mind Map](./etc/money-mind-map.png)
39+
40+
Flowchart
41+
42+
![Money Pattern Flowchart](./etc/money-flowchart.png)
3643

3744
## Programmatic Example of Money Pattern in Java
3845

39-
### Money Class
46+
In this example, we're creating a `Money` class to demonstrate how monetary values can be encapsulated along with their currency. This approach helps avoid floating-point inaccuracies, ensures arithmetic operations are handled consistently, and provides a clear domain-centric way of working with money.
4047

4148
```java
42-
43-
/**
44-
* Represents a monetary value with an associated currency.
45-
* Provides operations for basic arithmetic (addition, subtraction, multiplication),
46-
* as well as currency conversion while ensuring proper rounding.
47-
*/
49+
@AllArgsConstructor
4850
@Getter
4951
public class Money {
50-
private @Getter double amount;
51-
private @Getter String currency;
52+
private double amount;
53+
private String currency;
5254

53-
public Money(double amnt, String curr) {
54-
this.amount = amnt;
55-
this.currency = curr;
56-
}
55+
public Money(double amnt, String curr) {
56+
this.amount = amnt;
57+
this.currency = curr;
58+
}
5759

58-
private double roundToTwoDecimals(double value) {
59-
return Math.round(value * 100.0) / 100.0;
60-
}
60+
private double roundToTwoDecimals(double value) {
61+
return Math.round(value * 100.0) / 100.0;
62+
}
6163

62-
public void addMoney(Money moneyToBeAdded) throws CannotAddTwoCurrienciesException {
63-
if (!moneyToBeAdded.getCurrency().equals(this.currency)) {
64-
throw new CannotAddTwoCurrienciesException("You are trying to add two different currencies");
64+
public void addMoney(Money moneyToBeAdded) throws CannotAddTwoCurrienciesException {
65+
if (!moneyToBeAdded.getCurrency().equals(this.currency)) {
66+
throw new CannotAddTwoCurrienciesException("You are trying to add two different currencies");
67+
}
68+
this.amount = roundToTwoDecimals(this.amount + moneyToBeAdded.getAmount());
6569
}
66-
this.amount = roundToTwoDecimals(this.amount + moneyToBeAdded.getAmount());
67-
}
68-
69-
public void subtractMoney(Money moneyToBeSubtracted) throws CannotSubtractException {
70-
if (!moneyToBeSubtracted.getCurrency().equals(this.currency)) {
71-
throw new CannotSubtractException("You are trying to subtract two different currencies");
72-
} else if (moneyToBeSubtracted.getAmount() > this.amount) {
73-
throw new CannotSubtractException("The amount you are trying to subtract is larger than the amount you have");
70+
71+
public void subtractMoney(Money moneyToBeSubtracted) throws CannotSubtractException {
72+
if (!moneyToBeSubtracted.getCurrency().equals(this.currency)) {
73+
throw new CannotSubtractException("You are trying to subtract two different currencies");
74+
} else if (moneyToBeSubtracted.getAmount() > this.amount) {
75+
throw new CannotSubtractException("The amount you are trying to subtract is larger than the amount you have");
76+
}
77+
this.amount = roundToTwoDecimals(this.amount - moneyToBeSubtracted.getAmount());
7478
}
75-
this.amount = roundToTwoDecimals(this.amount - moneyToBeSubtracted.getAmount());
76-
}
7779

78-
public void multiply(int factor) {
79-
if (factor < 0) {
80-
throw new IllegalArgumentException("Factor must be non-negative");
80+
public void multiply(int factor) {
81+
if (factor < 0) {
82+
throw new IllegalArgumentException("Factor must be non-negative");
83+
}
84+
this.amount = roundToTwoDecimals(this.amount * factor);
8185
}
82-
this.amount = roundToTwoDecimals(this.amount * factor);
83-
}
8486

85-
public void exchangeCurrency(String currencyToChangeTo, double exchangeRate) {
86-
if (exchangeRate < 0) {
87-
throw new IllegalArgumentException("Exchange rate must be non-negative");
87+
public void exchangeCurrency(String currencyToChangeTo, double exchangeRate) {
88+
if (exchangeRate < 0) {
89+
throw new IllegalArgumentException("Exchange rate must be non-negative");
90+
}
91+
this.amount = roundToTwoDecimals(this.amount * exchangeRate);
92+
this.currency = currencyToChangeTo;
8893
}
89-
this.amount = roundToTwoDecimals(this.amount * exchangeRate);
90-
this.currency = currencyToChangeTo;
91-
}
9294
}
95+
```
9396

94-
## When to Use the Money Pattern
95-
96-
The Money pattern should be used in scenarios where:
97+
By encapsulating all money-related logic in a single class, we reduce the risk of mixing different currencies, improve clarity of the codebase, and facilitate future modifications such as adding new currencies or refining rounding rules. This pattern ultimately strengthens the domain model by treating money as a distinct concept rather than just another numeric value.
9798

98-
1. **Currency-safe arithmetic operations**
99-
To ensure that arithmetic operations like addition, subtraction, and multiplication are performed only between amounts in the same currency, preventing inconsistencies or errors in calculations.
100-
101-
2. **Accurate rounding for financial calculations**
102-
Precise rounding to two decimal places is critical to maintain accuracy and consistency in financial systems.
103-
104-
3. **Consistent currency conversion**
105-
When handling international transactions or displaying monetary values in different currencies, the Money pattern facilitates easy and reliable conversion using exchange rates.
99+
## When to Use the Money Pattern
106100

107-
4. **Encapsulation of monetary logic**
108-
By encapsulating all monetary operations within a dedicated class, the Money pattern improves maintainability and reduces the likelihood of errors.
101+
* When financial calculations or money manipulations are part of the business logic
102+
* When precise handling of currency amounts is required to avoid floating-point inaccuracies
103+
* When domain-driven design principles and strong typing are desired
109104

110-
5. **Preventing errors in financial operations**
111-
Strict validation ensures that operations like subtraction or multiplication are only performed when conditions are met, safeguarding against misuse or logical errors.
105+
## Real-World Applications of Monad Pattern in Java
112106

113-
6. **Handling diverse scenarios in financial systems**
114-
Useful in complex systems like e-commerce, banking, and payroll applications where precise and consistent monetary value handling is crucial.
107+
* JSR 354 (Java Money and Currency) library in Java
108+
* Custom domain models in e-commerce and accounting systems
115109

116-
---
117110
## Benefits and Trade-offs of Money Pattern
118111

119-
### Benefits
120-
1. **Precision and Accuracy**
121-
The Money pattern ensures precise handling of monetary values, reducing the risk of rounding errors.
122-
123-
2. **Encapsulation of Business Logic**
124-
By encapsulating monetary operations, the pattern enhances maintainability and reduces redundancy in financial systems.
125-
126-
3. **Currency Safety**
127-
It ensures operations are performed only between amounts of the same currency, avoiding logical errors.
112+
Benefits
128113

129-
4. **Improved Readability**
130-
By abstracting monetary logic into a dedicated class, the code becomes easier to read and maintain.
114+
* Provides a single, type-safe representation of monetary amounts and currency
115+
* Encourages encapsulation of related operations such as addition, subtraction, and formatting
116+
* Avoids floating-point errors by using integers or specialized decimal libraries
131117

132-
5. **Ease of Extension**
133-
Adding new operations, handling different currencies, or incorporating additional business rules is straightforward.
118+
Trade-offs
134119

135-
### Trade-offs
136-
1. **Increased Complexity**
137-
Introducing a dedicated `Money` class can add some overhead, especially for small or simple projects.
138-
139-
2. **Potential for Misuse**
140-
Without proper validation and handling, incorrect usage of the Money pattern may introduce subtle bugs.
141-
142-
3. **Performance Overhead**
143-
Precision and encapsulation might slightly affect performance in systems with extremely high transaction volumes.
144-
145-
---
120+
* Requires additional classes and infrastructure to handle currency conversions and formatting
121+
* Might introduce performance overhead when performing large numbers of money operations
146122

147123
## Related Design Patterns
148124

149-
1. **Value Object**
150-
Money is a classic example of the Value Object pattern, where objects are immutable and define equality based on their value.
151-
Link:https://martinfowler.com/bliki/ValueObject.html
152-
2. **Factory Method**
153-
Factories can be employed to handle creation logic, such as applying default exchange rates or rounding rules.
154-
Link:https://www.geeksforgeeks.org/factory-method-for-designing-pattern/
155-
---
125+
* [Value Object](https://java-design-patterns.com/patterns/value-object/): Money is typically a prime example of a domain-driven design value object.
156126

157127
## References and Credits
158128

159-
- [Patterns of Enterprise Application Architecture](https://martinfowler.com/eaaCatalog/money.html) by Martin Fowler
160-
- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
129+
* [Domain-Driven Design: Tackling Complexity in the Heart of Software](https://amzn.to/3wlDrze)
130+
* [Implementing Domain-Driven Design](https://amzn.to/4dmBjrB)
131+
* [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)

Diff for: money/etc/money-flowchart.png

56.3 KB
Loading

Diff for: money/etc/money-mind-map.png

149 KB
Loading

Diff for: money/src/main/java/com/iluwatar/Money.java

+4-13
Original file line numberDiff line numberDiff line change
@@ -24,28 +24,19 @@
2424
*/
2525
package com.iluwatar;
2626

27+
import lombok.AllArgsConstructor;
2728
import lombok.Getter;
2829

2930
/**
3031
* Represents a monetary value with an associated currency. Provides operations for basic arithmetic
3132
* (addition, subtraction, multiplication), as well as currency conversion while ensuring proper
3233
* rounding.
3334
*/
35+
@AllArgsConstructor
3436
@Getter
3537
public class Money {
36-
private @Getter double amount;
37-
private @Getter String currency;
38-
39-
/**
40-
* Constructs a Money object with the specified amount and currency.
41-
*
42-
* @param amnt the amount of money (as a double).
43-
* @param curr the currency code (e.g., "USD", "EUR").
44-
*/
45-
public Money(double amnt, String curr) {
46-
this.amount = amnt;
47-
this.currency = curr;
48-
}
38+
private double amount;
39+
private String currency;
4940

5041
/**
5142
* Rounds the given value to two decimal places.

Diff for: money/src/test/java/com/iluwater/money/MoneyTest.java

+6-18
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,7 @@ void testAddMoney_DifferentCurrency() {
6161

6262
assertThrows(
6363
CannotAddTwoCurrienciesException.class,
64-
() -> {
65-
money1.addMoney(money2);
66-
});
64+
() -> money1.addMoney(money2));
6765
}
6866

6967
@Test
@@ -85,9 +83,7 @@ void testSubtractMoney_DifferentCurrency() {
8583

8684
assertThrows(
8785
CannotSubtractException.class,
88-
() -> {
89-
money1.subtractMoney(money2);
90-
});
86+
() -> money1.subtractMoney(money2));
9187
}
9288

9389
@Test
@@ -98,9 +94,7 @@ void testSubtractMoney_AmountTooLarge() {
9894

9995
assertThrows(
10096
CannotSubtractException.class,
101-
() -> {
102-
money1.subtractMoney(money2);
103-
});
97+
() -> money1.subtractMoney(money2));
10498
}
10599

106100
@Test
@@ -120,9 +114,7 @@ void testMultiply_NegativeFactor() {
120114

121115
assertThrows(
122116
IllegalArgumentException.class,
123-
() -> {
124-
money.multiply(-2);
125-
});
117+
() -> money.multiply(-2));
126118
}
127119

128120
@Test
@@ -143,17 +135,13 @@ void testExchangeCurrency_NegativeExchangeRate() {
143135

144136
assertThrows(
145137
IllegalArgumentException.class,
146-
() -> {
147-
money.exchangeCurrency("EUR", -0.85);
148-
});
138+
() -> money.exchangeCurrency("EUR", -0.85));
149139
}
150140

151141
@Test
152142
void testAppExecution() {
153143
assertDoesNotThrow(
154-
() -> {
155-
App.main(new String[] {});
156-
},
144+
() -> App.main(new String[] {}),
157145
"App execution should not throw any exceptions");
158146
}
159147
}

0 commit comments

Comments
 (0)