Skip to content

Commit

Permalink
Merge branch 'master' into feature/template-view
Browse files Browse the repository at this point in the history
  • Loading branch information
iluwatar authored Jan 6, 2025
2 parents 8b80235 + ebcc070 commit 4afffa0
Show file tree
Hide file tree
Showing 22 changed files with 1,315 additions and 64 deletions.
18 changes: 18 additions & 0 deletions .all-contributorsrc
Original file line number Diff line number Diff line change
Expand Up @@ -3312,6 +3312,24 @@
"contributions": [
"translation"
]
},
{
"login": "HabibaMekay",
"name": "HabibaMekay",
"avatar_url": "https://avatars.githubusercontent.com/u/133516736?v=4",
"profile": "https://github.com/HabibaMekay",
"contributions": [
"code"
]
},
{
"login": "Ahmed-Taha-981",
"name": "Ahmed-Taha-981",
"avatar_url": "https://avatars.githubusercontent.com/u/122402269?v=4",
"profile": "https://github.com/Ahmed-Taha-981",
"contributions": [
"code"
]
}
],
"contributorsPerLine": 6,
Expand Down
61 changes: 0 additions & 61 deletions .github/stale.yml

This file was deleted.

19 changes: 19 additions & 0 deletions .github/workflows/stale.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
name: 'Comment on stale issues and PRs'
on:
schedule:
- cron: '30 1 * * *'

jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v9
with:
stale-issue-message: 'This issue is stale because it has been open 60 days with no activity.'
stale-pr-message: 'This PR is stale because it has been open 60 days with no activity.'
close-issue-message: 'This issue was closed because it has been stalled for too long with no activity.'
close-pr-message: 'This PR was closed because it has been stalled for too long with no activity.'
days-before-issue-stale: 60
days-before-pr-stale: 60
days-before-issue-close: -1
days-before-pr-close: -1
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=coverage)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns)
[![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
[![All Contributors](https://img.shields.io/badge/all_contributors-362-orange.svg?style=flat-square)](#contributors-)
[![All Contributors](https://img.shields.io/badge/all_contributors-365-orange.svg?style=flat-square)](#contributors-)
<!-- ALL-CONTRIBUTORS-BADGE:END -->

<br/>
Expand Down Expand Up @@ -544,6 +544,8 @@ This project is licensed under the terms of the MIT license.
<td align="center" valign="top" width="16.66%"><a href="https://github.com/SalmaAzeem"><img src="https://avatars.githubusercontent.com/u/121863224?v=4?s=100" width="100px;" alt="Salma"/><br /><sub><b>Salma</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=SalmaAzeem" title="Code">💻</a></td>
<td align="center" valign="top" width="16.66%"><a href="https://codemaverick-143.github.io/My-Portfolio/"><img src="https://avatars.githubusercontent.com/u/182847716?v=4?s=100" width="100px;" alt="Arpit Sarang"/><br /><sub><b>Arpit Sarang</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=CodeMaverick-143" title="Code">💻</a></td>
<td align="center" valign="top" width="16.66%"><a href="https://github.com/mayatarek"><img src="https://avatars.githubusercontent.com/u/111644421?v=4?s=100" width="100px;" alt="Maya"/><br /><sub><b>Maya</b></sub></a><br /><a href="#translation-mayatarek" title="Translation">🌍</a></td>
<td align="center" valign="top" width="16.66%"><a href="https://github.com/HabibaMekay"><img src="https://avatars.githubusercontent.com/u/133516736?v=4?s=100" width="100px;" alt="HabibaMekay"/><br /><sub><b>HabibaMekay</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=HabibaMekay" title="Code">💻</a></td>
<td align="center" valign="top" width="16.66%"><a href="https://github.com/Ahmed-Taha-981"><img src="https://avatars.githubusercontent.com/u/122402269?v=4?s=100" width="100px;" alt="Ahmed-Taha-981"/><br /><sub><b>Ahmed-Taha-981</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=Ahmed-Taha-981" title="Code">💻</a></td>
</tr>
</tbody>
</table>
Expand Down
2 changes: 1 addition & 1 deletion hexagonal-architecture/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
<dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<version>4.18.0</version>
<version>4.18.1</version>
<scope>test</scope>
</dependency>
<dependency>
Expand Down
168 changes: 168 additions & 0 deletions money/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
---
title: "Money Pattern in Java: Encapsulating Monetary Values with Currency Consistency"
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."
category: Behavioral
language: en
tag:
- Encapsulation
- Precision handling
- Currency safety
- Value Object
- Financial operations
- Currency
- Financial
- Immutable
- Value Object
---

## Also known as

* Monetary Value Object

## 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.

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

### 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.
In this example:
- 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.
### 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."
## Programmatic Example of Money Pattern in Java

### Money Class

```java

/**
* 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
public class Money {
private @Getter double amount;
private @Getter String currency;

public Money(double amnt, String curr) {
this.amount = amnt;
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 {
if (!moneyToBeSubtracted.getCurrency().equals(this.currency)) {
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;
}
}

## When to Use the Money Pattern

The Money pattern should be used in scenarios where:

1. **Currency-safe arithmetic operations**
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**
Precise rounding to two decimal places is critical to maintain accuracy and consistency in financial 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
1. **Precision and Accuracy**
The Money pattern ensures precise handling of monetary values, reducing the risk of rounding errors.

2. **Encapsulation of Business Logic**
By encapsulating monetary operations, the pattern enhances maintainability and reduces redundancy in financial systems.

3. **Currency Safety**
It ensures operations are performed only between amounts of the same currency, avoiding logical errors.

4. **Improved Readability**
By abstracting monetary logic into a dedicated class, the code becomes easier to read and maintain.

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

1. **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

- [Patterns of Enterprise Application Architecture](https://martinfowler.com/eaaCatalog/money.html) by Martin Fowler
- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
49 changes: 49 additions & 0 deletions money/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
The MIT License
Copyright © 2014-2022 Ilkka Seppälä
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.26.0-SNAPSHOT</version>
</parent>

<artifactId>money</artifactId>


<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

</project>
Loading

0 comments on commit 4afffa0

Please sign in to comment.