mirror of
https://github.com/tiennm99/java-design-patterns.git
synced 2026-10-13 18:15:41 +00:00
docs: update money pattern
This commit is contained in:
1 parent
076fc21e40
commit
d95c6797a4
5 files changed
+85
-135
No files matched your search
+75
-104
@@ -2,10 +2,13 @@
|
|||||||
title: "Money Pattern in Java: Encapsulating Monetary Values with Currency Consistency"
|
title: "Money Pattern in Java: Encapsulating Monetary Values with Currency Consistency"
|
||||||
shortTitle: Money
|
shortTitle: Money
|
||||||
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."
|
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."
|
||||||
category: Behavioral
|
category: Structural
|
||||||
language: en
|
language: en
|
||||||
tag:
|
tag:
|
||||||
- Encapsulation
|
- Business
|
||||||
|
- Domain
|
||||||
|
- Encapsulation
|
||||||
|
- Immutable
|
||||||
---
|
---
|
||||||
|
|
||||||
## Also known as
|
## Also known as
|
||||||
@@ -14,147 +17,115 @@ tag:
|
|||||||
|
|
||||||
## Intent of Money Design Pattern
|
## Intent of Money Design Pattern
|
||||||
|
|
||||||
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.
|
Encapsulate monetary values and their associated currency in a domain-specific object.
|
||||||
|
|
||||||
## Detailed Explanation of Money Pattern with Real-World Examples
|
## Detailed Explanation of Money Pattern with Real-World Examples
|
||||||
|
|
||||||
### Real-world example
|
Real-world example
|
||||||
|
|
||||||
> 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.
|
> 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.
|
||||||
|
|
||||||
In this example:
|
In plain words
|
||||||
- Each monetary value (like a product price or tax amount) is encapsulated in a `Money` object.
|
|
||||||
- The `Money` class ensures that only values in the same currency are combined and supports safe currency conversion for global operations.
|
|
||||||
|
|
||||||
### In plain words
|
|
||||||
|
|
||||||
> The Money pattern encapsulates both an amount and its currency, ensuring financial operations are precise, consistent, and maintainable.
|
> The Money pattern encapsulates both an amount and its currency, ensuring financial operations are precise, consistent, and maintainable.
|
||||||
|
|
||||||
### Wikipedia says
|
Wikipedia says
|
||||||
|
|
||||||
> "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."
|
> 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.
|
||||||
|
|
||||||
|
Mind map
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
Flowchart
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
## Programmatic Example of Money Pattern in Java
|
## Programmatic Example of Money Pattern in Java
|
||||||
|
|
||||||
### Money Class
|
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.
|
||||||
|
|
||||||
```java
|
```java
|
||||||
|
@AllArgsConstructor
|
||||||
/**
|
|
||||||
* Represents a monetary value with an associated currency.
|
|
||||||
* Provides operations for basic arithmetic (addition, subtraction, multiplication),
|
|
||||||
* as well as currency conversion while ensuring proper rounding.
|
|
||||||
*/
|
|
||||||
@Getter
|
@Getter
|
||||||
public class Money {
|
public class Money {
|
||||||
private @Getter double amount;
|
private double amount;
|
||||||
private @Getter String currency;
|
private String currency;
|
||||||
|
|
||||||
public Money(double amnt, String curr) {
|
public Money(double amnt, String curr) {
|
||||||
this.amount = amnt;
|
this.amount = amnt;
|
||||||
this.currency = curr;
|
this.currency = curr;
|
||||||
}
|
|
||||||
|
|
||||||
private double roundToTwoDecimals(double value) {
|
|
||||||
return Math.round(value * 100.0) / 100.0;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void addMoney(Money moneyToBeAdded) throws CannotAddTwoCurrienciesException {
|
|
||||||
if (!moneyToBeAdded.getCurrency().equals(this.currency)) {
|
|
||||||
throw new CannotAddTwoCurrienciesException("You are trying to add two different currencies");
|
|
||||||
}
|
}
|
||||||
this.amount = roundToTwoDecimals(this.amount + moneyToBeAdded.getAmount());
|
|
||||||
}
|
|
||||||
|
|
||||||
public void subtractMoney(Money moneyToBeSubtracted) throws CannotSubtractException {
|
private double roundToTwoDecimals(double value) {
|
||||||
if (!moneyToBeSubtracted.getCurrency().equals(this.currency)) {
|
return Math.round(value * 100.0) / 100.0;
|
||||||
throw new CannotSubtractException("You are trying to subtract two different currencies");
|
|
||||||
} else if (moneyToBeSubtracted.getAmount() > this.amount) {
|
|
||||||
throw new CannotSubtractException("The amount you are trying to subtract is larger than the amount you have");
|
|
||||||
}
|
}
|
||||||
this.amount = roundToTwoDecimals(this.amount - moneyToBeSubtracted.getAmount());
|
|
||||||
}
|
|
||||||
|
|
||||||
public void multiply(int factor) {
|
public void addMoney(Money moneyToBeAdded) throws CannotAddTwoCurrienciesException {
|
||||||
if (factor < 0) {
|
if (!moneyToBeAdded.getCurrency().equals(this.currency)) {
|
||||||
throw new IllegalArgumentException("Factor must be non-negative");
|
throw new CannotAddTwoCurrienciesException("You are trying to add two different currencies");
|
||||||
|
}
|
||||||
|
this.amount = roundToTwoDecimals(this.amount + moneyToBeAdded.getAmount());
|
||||||
}
|
}
|
||||||
this.amount = roundToTwoDecimals(this.amount * factor);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void exchangeCurrency(String currencyToChangeTo, double exchangeRate) {
|
public void subtractMoney(Money moneyToBeSubtracted) throws CannotSubtractException {
|
||||||
if (exchangeRate < 0) {
|
if (!moneyToBeSubtracted.getCurrency().equals(this.currency)) {
|
||||||
throw new IllegalArgumentException("Exchange rate must be non-negative");
|
throw new CannotSubtractException("You are trying to subtract two different currencies");
|
||||||
|
} else if (moneyToBeSubtracted.getAmount() > this.amount) {
|
||||||
|
throw new CannotSubtractException("The amount you are trying to subtract is larger than the amount you have");
|
||||||
|
}
|
||||||
|
this.amount = roundToTwoDecimals(this.amount - moneyToBeSubtracted.getAmount());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void multiply(int factor) {
|
||||||
|
if (factor < 0) {
|
||||||
|
throw new IllegalArgumentException("Factor must be non-negative");
|
||||||
|
}
|
||||||
|
this.amount = roundToTwoDecimals(this.amount * factor);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void exchangeCurrency(String currencyToChangeTo, double exchangeRate) {
|
||||||
|
if (exchangeRate < 0) {
|
||||||
|
throw new IllegalArgumentException("Exchange rate must be non-negative");
|
||||||
|
}
|
||||||
|
this.amount = roundToTwoDecimals(this.amount * exchangeRate);
|
||||||
|
this.currency = currencyToChangeTo;
|
||||||
}
|
}
|
||||||
this.amount = roundToTwoDecimals(this.amount * exchangeRate);
|
|
||||||
this.currency = currencyToChangeTo;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
## When to Use the Money Pattern
|
## When to Use the Money Pattern
|
||||||
|
|
||||||
The Money pattern should be used in scenarios where:
|
* When financial calculations or money manipulations are part of the business logic
|
||||||
|
* When precise handling of currency amounts is required to avoid floating-point inaccuracies
|
||||||
|
* When domain-driven design principles and strong typing are desired
|
||||||
|
|
||||||
1. **Currency-safe arithmetic operations**
|
## Real-World Applications of Monad Pattern in Java
|
||||||
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.
|
|
||||||
|
|
||||||
2. **Accurate rounding for financial calculations**
|
* JSR 354 (Java Money and Currency) library in Java
|
||||||
Precise rounding to two decimal places is critical to maintain accuracy and consistency in financial systems.
|
* Custom domain models in e-commerce and accounting systems
|
||||||
|
|
||||||
3. **Consistent currency conversion**
|
|
||||||
When handling international transactions or displaying monetary values in different currencies, the Money pattern facilitates easy and reliable conversion using exchange rates.
|
|
||||||
|
|
||||||
4. **Encapsulation of monetary logic**
|
|
||||||
By encapsulating all monetary operations within a dedicated class, the Money pattern improves maintainability and reduces the likelihood of errors.
|
|
||||||
|
|
||||||
5. **Preventing errors in financial operations**
|
|
||||||
Strict validation ensures that operations like subtraction or multiplication are only performed when conditions are met, safeguarding against misuse or logical errors.
|
|
||||||
|
|
||||||
6. **Handling diverse scenarios in financial systems**
|
|
||||||
Useful in complex systems like e-commerce, banking, and payroll applications where precise and consistent monetary value handling is crucial.
|
|
||||||
|
|
||||||
---
|
|
||||||
## Benefits and Trade-offs of Money Pattern
|
## Benefits and Trade-offs of Money Pattern
|
||||||
|
|
||||||
### Benefits
|
Benefits
|
||||||
1. **Precision and Accuracy**
|
|
||||||
The Money pattern ensures precise handling of monetary values, reducing the risk of rounding errors.
|
|
||||||
|
|
||||||
2. **Encapsulation of Business Logic**
|
* Provides a single, type-safe representation of monetary amounts and currency
|
||||||
By encapsulating monetary operations, the pattern enhances maintainability and reduces redundancy in financial systems.
|
* Encourages encapsulation of related operations such as addition, subtraction, and formatting
|
||||||
|
* Avoids floating-point errors by using integers or specialized decimal libraries
|
||||||
|
|
||||||
3. **Currency Safety**
|
Trade-offs
|
||||||
It ensures operations are performed only between amounts of the same currency, avoiding logical errors.
|
|
||||||
|
|
||||||
4. **Improved Readability**
|
* Requires additional classes and infrastructure to handle currency conversions and formatting
|
||||||
By abstracting monetary logic into a dedicated class, the code becomes easier to read and maintain.
|
* Might introduce performance overhead when performing large numbers of money operations
|
||||||
|
|
||||||
5. **Ease of Extension**
|
|
||||||
Adding new operations, handling different currencies, or incorporating additional business rules is straightforward.
|
|
||||||
|
|
||||||
### Trade-offs
|
|
||||||
1. **Increased Complexity**
|
|
||||||
Introducing a dedicated `Money` class can add some overhead, especially for small or simple projects.
|
|
||||||
|
|
||||||
2. **Potential for Misuse**
|
|
||||||
Without proper validation and handling, incorrect usage of the Money pattern may introduce subtle bugs.
|
|
||||||
|
|
||||||
3. **Performance Overhead**
|
|
||||||
Precision and encapsulation might slightly affect performance in systems with extremely high transaction volumes.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Related Design Patterns
|
## Related Design Patterns
|
||||||
|
|
||||||
1. **Value Object**
|
* [Value Object](https://java-design-patterns.com/patterns/value-object/): Money is typically a prime example of a domain-driven design value object.
|
||||||
Money is a classic example of the Value Object pattern, where objects are immutable and define equality based on their value.
|
|
||||||
Link:https://martinfowler.com/bliki/ValueObject.html
|
|
||||||
2. **Factory Method**
|
|
||||||
Factories can be employed to handle creation logic, such as applying default exchange rates or rounding rules.
|
|
||||||
Link:https://www.geeksforgeeks.org/factory-method-for-designing-pattern/
|
|
||||||
---
|
|
||||||
|
|
||||||
## References and Credits
|
## References and Credits
|
||||||
|
|
||||||
- [Patterns of Enterprise Application Architecture](https://martinfowler.com/eaaCatalog/money.html) by Martin Fowler
|
* [Domain-Driven Design: Tackling Complexity in the Heart of Software](https://amzn.to/3wlDrze)
|
||||||
- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
|
* [Implementing Domain-Driven Design](https://amzn.to/4dmBjrB)
|
||||||
|
* [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 56 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 149 KiB |
@@ -24,6 +24,7 @@
|
|||||||
*/
|
*/
|
||||||
package com.iluwatar;
|
package com.iluwatar;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -31,21 +32,11 @@ import lombok.Getter;
|
|||||||
* (addition, subtraction, multiplication), as well as currency conversion while ensuring proper
|
* (addition, subtraction, multiplication), as well as currency conversion while ensuring proper
|
||||||
* rounding.
|
* rounding.
|
||||||
*/
|
*/
|
||||||
|
@AllArgsConstructor
|
||||||
@Getter
|
@Getter
|
||||||
public class Money {
|
public class Money {
|
||||||
private @Getter double amount;
|
private double amount;
|
||||||
private @Getter String currency;
|
private String currency;
|
||||||
|
|
||||||
/**
|
|
||||||
* Constructs a Money object with the specified amount and currency.
|
|
||||||
*
|
|
||||||
* @param amnt the amount of money (as a double).
|
|
||||||
* @param curr the currency code (e.g., "USD", "EUR").
|
|
||||||
*/
|
|
||||||
public Money(double amnt, String curr) {
|
|
||||||
this.amount = amnt;
|
|
||||||
this.currency = curr;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Rounds the given value to two decimal places.
|
* Rounds the given value to two decimal places.
|
||||||
|
|||||||
@@ -61,9 +61,7 @@ class MoneyTest {
|
|||||||
|
|
||||||
assertThrows(
|
assertThrows(
|
||||||
CannotAddTwoCurrienciesException.class,
|
CannotAddTwoCurrienciesException.class,
|
||||||
() -> {
|
() -> money1.addMoney(money2));
|
||||||
money1.addMoney(money2);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -85,9 +83,7 @@ class MoneyTest {
|
|||||||
|
|
||||||
assertThrows(
|
assertThrows(
|
||||||
CannotSubtractException.class,
|
CannotSubtractException.class,
|
||||||
() -> {
|
() -> money1.subtractMoney(money2));
|
||||||
money1.subtractMoney(money2);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -98,9 +94,7 @@ class MoneyTest {
|
|||||||
|
|
||||||
assertThrows(
|
assertThrows(
|
||||||
CannotSubtractException.class,
|
CannotSubtractException.class,
|
||||||
() -> {
|
() -> money1.subtractMoney(money2));
|
||||||
money1.subtractMoney(money2);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -120,9 +114,7 @@ class MoneyTest {
|
|||||||
|
|
||||||
assertThrows(
|
assertThrows(
|
||||||
IllegalArgumentException.class,
|
IllegalArgumentException.class,
|
||||||
() -> {
|
() -> money.multiply(-2));
|
||||||
money.multiply(-2);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -143,17 +135,13 @@ class MoneyTest {
|
|||||||
|
|
||||||
assertThrows(
|
assertThrows(
|
||||||
IllegalArgumentException.class,
|
IllegalArgumentException.class,
|
||||||
() -> {
|
() -> money.exchangeCurrency("EUR", -0.85));
|
||||||
money.exchangeCurrency("EUR", -0.85);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testAppExecution() {
|
void testAppExecution() {
|
||||||
assertDoesNotThrow(
|
assertDoesNotThrow(
|
||||||
() -> {
|
() -> App.main(new String[] {}),
|
||||||
App.main(new String[] {});
|
|
||||||
},
|
|
||||||
"App execution should not throw any exceptions");
|
"App execution should not throw any exceptions");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user