Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit dd1dcdd

Browse files
authoredApr 15, 2025
Merge branch 'iluwatar:master' into actor-model
2 parents 11abf48 + b8aa775 commit dd1dcdd

File tree

14 files changed

+186
-215
lines changed

14 files changed

+186
-215
lines changed
 

‎microservices-distributed-tracing/README.md

Lines changed: 37 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,32 @@
11
---
2-
title: "Microservices Distributed Tracing Pattern: Enhancing Visibility in Service Communication"
3-
shortTitle: Distributed Tracing in Microservices
2+
title: "Microservices Distributed Tracing Pattern In Java: Enhancing Visibility in Service Communication"
3+
shortTitle: Microservices Distributed Tracing
44
description: "Learn how the Distributed Tracing pattern enhances visibility into service communication across microservices. Discover its benefits, implementation examples, and best practices."
5-
category: Structural
5+
category: Architectural
66
language: en
77
tag:
8-
- Scalability
8+
- Cloud distributed
9+
- Microservices
10+
- Resilience
11+
- Observability
12+
- Scalability
13+
- System health
914
---
1015

1116
## Intent of Microservices Distributed Tracing Design Pattern
1217

13-
Distributed tracing aims to monitor and track requests as they flow through different services in a microservices architecture, providing insights into performance, dependencies, and failures.
18+
Provide a mechanism to trace and correlate requests as they traverse multiple microservices in a distributed system, enabling end-to-end visibility and easier troubleshooting.
1419

1520
## Also known as
1621

1722
* Distributed Request Tracing
18-
* End-to-End Tracing
23+
* End-to-End Microservice Tracing
1924

2025
## Detailed Explanation of Microservices Distributed Tracing Pattern with Real-World Examples
2126

2227
Real-world example
2328

24-
> In an e-commerce platform, distributed tracing is used to track a customer's request from the moment they add an item to the cart until the order is processed and shipped. This helps in identifying bottlenecks, errors, and latency issues across different services.
29+
> Imagine an online food delivery platform where one microservice handles user orders, another manages restaurant menus, and yet another coordinates courier assignments. When a user places an order, the request travels through all three services in sequence. By implementing distributed tracing, each service attaches a trace identifier to its logs. This allows the operations team to follow the journey of a single order across the entire pipeline, identify any delays along the way, and quickly pinpoint which service is causing the bottleneck or experiencing an error.
2530
2631
In plain words
2732

@@ -31,10 +36,13 @@ Wikipedia says
3136

3237
> Tracing in software engineering refers to the process of capturing and recording information about the execution of a software program. This information is typically used by programmers for debugging purposes, and additionally, depending on the type and detail of information contained in a trace log, by experienced system administrators or technical-support personnel and by software monitoring tools to diagnose common problems with software.
3338
34-
## Programmatic Example of Microservices Distributed Tracing in Java
39+
Sequence diagram
40+
41+
![Microservices Distributed Tracing Sequence Diagram](./etc/microservices-distributed-tracing-sequence-diagram.png)
3542

43+
## Programmatic Example of Microservices Distributed Tracing in Java
3644

37-
This implementation shows how an e-commerce platform's `OrderService` interacts with both `PaymentService` and `ProductService`. When a customer places an order, the `OrderService` calls the `PaymentService` to process the payment and the `ProductService` to check the product inventory. Distributed tracing logs are generated for each of these interactions and can be viewed in the Zipkin interface to monitor the flow and performance of requests across these services.
45+
This implementation shows how an e-commerce platform's `OrderService` interacts with both `PaymentService` and `ProductService`. When a customer places an order, the `OrderService` calls the `PaymentService` to process the payment and the `ProductService` to check the product inventory. By adding distributed trace instrumentation (usually via libraries like Spring Cloud Sleuth or OpenTelemetry), each service attaches trace context to outgoing requests and logs. These logs can then be viewed in the Zipkin interface (or other tracing tools, such as Jaeger) to observe the entire flow of the request and quickly identify any performance bottlenecks or failures across multiple services.
3846

3947
Here's the `Order microservice` implementation.
4048

@@ -150,25 +158,32 @@ public class ProductController {
150158
}
151159
```
152160

153-
## When to Use the Microservices Distributed Tracing Pattern in Java
161+
In this example, each microservice would typically be configured with tracing libraries (like Sleuth or OpenTelemetry). The trace context is propagated via HTTP headers, enabling the logs and metrics for each service call to be grouped together and visualized in Zipkin or another compatible tool. This ensures complete end-to-end visibility into each request’s journey.
154162

155-
* When you have a microservices architecture and need to monitor the flow of requests across multiple services.
156-
* When troubleshooting performance issues or errors in a distributed system.
157-
* When you need to gain insights into system bottlenecks and optimize overall performance.
163+
## When to Use the Microservices Distributed Tracing Pattern in Java
158164

165+
* When multiple services form a single user request path and debugging failures requires visibility across service boundaries.
166+
* When monitoring or diagnosing performance bottlenecks is critical in a multi-service environment.
167+
* When correlation of logs and metrics from independent services is needed to understand overall system health.
159168

160169
## Microservices Distributed Tracing Pattern Java Tutorials
161170

162171
* [Spring Boot - Tracing (Spring)](https://docs.spring.io/spring-boot/reference/actuator/tracing.html)
163172
* [Reactive Observability (Spring Academy)](https://spring.academy/guides/microservices-observability-reactive-spring-boot-3)
164173
* [Spring Cloud – Tracing Services with Zipkin (Baeldung)](https://dzone.com/articles/getting-started-with-spring-cloud-gateway)
165174

175+
## Real-World Applications of Microservices Distributed Tracing Pattern in Java
176+
177+
* OpenTelemetry for tracing instrumentation in Java services.
178+
* Spring Cloud Sleuth for automatic tracing in Spring Boot microservices.
179+
* Jaeger and Zipkin for collecting and visualizing distributed traces in Java-based systems.
180+
166181
## Benefits and Trade-offs of Microservices Distributed Tracing Pattern
167182

168183
Benefits:
169184

170-
* Provides end-to-end visibility into requests.
171-
* Helps in identifying performance bottlenecks.
185+
* Centralized insight into request paths across services, reducing time to diagnose issues.
186+
* Improved observability enables proactive identification of system bottlenecks.
172187
* Aids in debugging and troubleshooting complex systems.
173188

174189
Trade-offs:
@@ -177,20 +192,17 @@ Trade-offs:
177192
* Requires additional infrastructure (e.g., Zipkin, Jaeger) for collecting and visualizing traces.
178193
* Can become complex to manage in large-scale systems.
179194

180-
## Real-World Applications of Microservices Distributed Tracing Pattern in Java
181-
182-
* Monitoring and troubleshooting e-commerce platforms.
183-
* Performance monitoring in financial transaction systems.
184-
* Observability in large-scale SaaS applications.
185-
186195
## Related Java Design Patterns
187196

188-
* [Log Aggregation Microservice](https://java-design-patterns.com/patterns/microservices-log-aggregation/) - Distributed tracing works well in conjunction with log aggregation to provide comprehensive observability and troubleshooting capabilities.
189-
* [Circuit Breaker](https://java-design-patterns.com/patterns/circuit-breaker/) - Distributed tracing can be used alongside the Circuit Breaker pattern to monitor and handle failures gracefully, preventing cascading failures in microservices.
190-
* [API Gateway Microservice](https://java-design-patterns.com/patterns/microservices-api-gateway/) - The API Gateway pattern can be integrated with distributed tracing to provide a single entry point for tracing requests across multiple microservices.
197+
* [API Gateway Microservice](https://java-design-patterns.com/patterns/microservices-api-gateway/): Acts as an entry point to microservices and can propagate trace information to downstream services.
198+
* [Circuit Breaker](https://java-design-patterns.com/patterns/circuit-breaker/): Distributed tracing can be used alongside the Circuit Breaker pattern to monitor and handle failures gracefully, preventing cascading failures in microservices.
199+
* [Log Aggregation Microservice](https://java-design-patterns.com/patterns/microservices-log-aggregation/): Distributed tracing works well in conjunction with log aggregation to provide comprehensive observability and troubleshooting capabilities.
200+
* [Saga](https://java-design-patterns.com/patterns/saga/): Orchestrates distributed transactions, which benefit from trace identifiers to correlate steps across services.
191201

192202
## References and Credits
193203

194204
* [Building Microservices](https://amzn.to/3UACtrU)
195-
* [OpenTelemetry Documentation](https://opentelemetry.io/docs/)
196205
* [Distributed tracing (microservices.io)](https://microservices.io/patterns/observability/distributed-tracing.html)
206+
* [Microservices Patterns: With examples in Java](https://amzn.to/3UyWD5O)
207+
* [OpenTelemetry Documentation](https://opentelemetry.io/docs/)
208+
* [Release It! Design and Deploy Production-Ready Software](https://amzn.to/3Uul4kF)

‎microservices-distributed-tracing/product-microservice/src/test/java/com/iluwatar/product/microservice/ProductControllerTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ class ProductControllerTest {
3636
private ProductController productController;
3737

3838
@BeforeEach
39-
public void setUp() {
39+
void setUp() {
4040
productController = new ProductController();
4141
}
4242

‎microservices-idempotent-consumer/README.md

Lines changed: 58 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,53 +1,56 @@
11
---
2-
title: "Idempotent Consumer Pattern in Java: Ensuring Reliable Message Processing"
3-
shortTitle: Idempotent Consumer
2+
title: "Microservices Idempotent Consumer Pattern in Java: Ensuring Reliable Message Processing"
3+
shortTitle: Microservices Idempotent Consumer
44
description: "Learn about the Idempotent Consumer pattern in Java. Discover how it ensures reliable and consistent message processing, even in cases of duplicate messages."
5-
category: Structural
5+
category: Messaging
66
language: en
77
tag:
8+
- Asynchronous
9+
- Decoupling
810
- Event-driven
11+
- Messaging
12+
- Microservices
13+
- Resilience
14+
- Retry
915
---
1016

1117
## Also known as
1218

13-
* Idempotency Pattern
19+
* Idempotent Subscriber
20+
* Repeatable Message Consumer
21+
* Safe Consumer
1422

1523
## Intent of Idempotent Consumer Pattern
1624

17-
The Idempotent Consumer pattern is used to handle duplicate messages in distributed systems, ensuring that multiple processing of the same message does not cause undesired side effects. This pattern guarantees that the same message can be processed repeatedly with the same outcome, which is critical in ensuring reliable communication and data consistency in systems where message duplicates are possible.
25+
Ensure that consuming the same message multiple times does not cause unintended side effects in a microservices-based architecture.
1826

1927
## Detailed Explanation of Idempotent Consumer Pattern with Real-World Examples
2028

21-
### Real-world Example
29+
Real-world example
2230

2331
> In a payment processing system, ensuring that payment messages are idempotent prevents duplicate transactions. For example, if a user’s payment message is accidentally processed twice, the system should recognize the second message as a duplicate and prevent it from executing a second time. By storing unique identifiers for each processed message, such as a transaction ID, the system can skip any duplicate messages. This ensures that a user is not charged twice for the same transaction, maintaining system integrity and customer satisfaction.
2432
25-
### In Plain Words
33+
In plain words
2634

2735
> The Idempotent Consumer pattern prevents duplicate messages from causing unintended side effects by ensuring that processing the same message multiple times results in the same outcome. This makes message processing safe in distributed systems where duplicates may occur.
2836
29-
### Wikipedia says
3037

31-
> In computing, idempotence is the property of certain operations in mathematics and computer science whereby they can be applied multiple times without changing the result beyond the initial application.
38+
Wikipedia says
3239

33-
## When to Use the Idempotent Consumer Pattern
40+
> In computing, idempotence is the property of certain operations in mathematics and computer science whereby they can be applied multiple times without changing the result beyond the initial application.
3441
35-
The Idempotent Consumer pattern is particularly useful in scenarios:
42+
Flowchart
3643

37-
* When messages can be duplicated due to network retries or communication issues.
38-
* In distributed systems where message ordering is not guaranteed, making deduplication necessary to avoid repeated processing.
39-
* In financial or critical systems, where duplicate processing would have significant side effects.
44+
![Microservices Idempotent Consumer flowchart](./etc/microservices-idempotent-consumer-flowchart.png)
4045

41-
## Real-World Applications of Idempotent Consumer Pattern
46+
## Programmatic example of Idempotent Consumer Pattern
4247

43-
* Payment processing systems that avoid duplicate transactions.
44-
* E-commerce systems to prevent multiple entries of the same order.
45-
* Inventory management systems to prevent multiple entries when updating stock levels.
48+
In this Java example, we have an idempotent service that creates and updates orders. The `create` method is idempotent, meaning multiple calls with the same order ID return the same result without duplicates. For state changes (like starting or completing an order), the service checks whether the transition is valid and throws an exception if it’s not allowed. The `RequestStateMachine` ensures that order statuses move forward in a valid sequence (e.g., PENDING → STARTED → COMPLETED).
4649

47-
## Programmatic example of Idempotent Consumer Pattern
48-
In this Java example, we have an idempotent service that offers functionality to create and update (start, complete, etc.) orders. The service ensures that the **create order** operation is idempotent, meaning that performing it multiple times with the same order ID will lead to the same result without creating duplicates. For state transitions (such as starting or completing an order), the service enforces valid state changes and throws exceptions if an invalid transition is attempted. The state machine governs the valid order status transitions, ensuring that statuses progress in a defined and consistent sequence.
4950
### RequestService - Managing Idempotent Order Operations
50-
The `RequestService` class is responsible for handling the creation and state transitions of orders. The `create` method is designed to be idempotent, ensuring that it either returns an existing order or creates a new one without any side effects if invoked multiple times with the same order ID.
51+
52+
The `RequestService` class provides methods to create and transition an order. The `create` method returns an existing order if it already exists, making it idempotent.
53+
5154
```java
5255
public class RequestService {
5356
// Idempotent: ensures that the same request is returned if it already exists
@@ -76,8 +79,11 @@ public class RequestService {
7679
}
7780
}
7881
```
82+
7983
### RequestStateMachine - Managing Order Transitions
80-
The `RequestStateMachine` ensures that state transitions occur in a valid order. It handles the progression of an order's status, ensuring the correct sequence (e.g., from `PENDING` to `STARTED` to `COMPLETED`).
84+
85+
The `RequestStateMachine` enforces valid state changes. If a requested transition is not allowed based on the current status, an exception is thrown.
86+
8187
```java
8288
public class RequestStateMachine {
8389

@@ -102,9 +108,10 @@ public class RequestStateMachine {
102108
}
103109
}
104110
```
111+
105112
### Main Application - Running the Idempotent Consumer Example
106113

107-
In the main application, we demonstrate how the `RequestService` can be used to perform idempotent operations. Whether the order creation or state transition is invoked once or multiple times, the result is consistent and does not produce unexpected side effects.
114+
Here, we demonstrate how `RequestService` can be called multiple times without creating duplicate orders. We also show how invalid transitions (like trying to start an order twice) result in exceptions, while valid transitions proceed normally.
108115

109116
```java
110117
Request req = requestService.create(UUID.randomUUID());
@@ -127,32 +134,49 @@ req = requestService.complete(req.getUuid());
127134
// Log the final status of the Request to confirm it's been completed
128135
LOGGER.info("Request: {}", req);
129136
```
137+
130138
Program output:
139+
131140
```
132141
19:01:54.382 INFO [main] com.iluwatar.idempotentconsumer.App : Nb of requests : 1
133142
19:01:54.395 ERROR [main] com.iluwatar.idempotentconsumer.App : Cannot start request twice!
134143
19:01:54.399 INFO [main] com.iluwatar.idempotentconsumer.App : Request: Request(uuid=2d5521ef-6b6b-4003-9ade-81e381fe9a63, status=COMPLETED)
135144
```
145+
146+
## When to Use the Idempotent Consumer Pattern
147+
148+
* When messages can arrive more than once due to network glitches or retries
149+
* When microservices must guarantee consistent state changes regardless of duplicates
150+
* When fault-tolerant event-driven communication is critical to system reliability
151+
* When horizontal scaling requires stateless consumer operations
152+
153+
## Real-World Applications of Idempotent Consumer Pattern
154+
155+
* Payment processing systems that receive duplicate charge events
156+
* E-commerce order services that handle duplicate purchase requests
157+
* Notification services that retry failed message deliveries
158+
* Distributed transaction systems where duplicated events are common
159+
136160
## Benefits and Trade-offs of the Idempotent Consumer Pattern
137161

138-
### Benefits
162+
Benefits
139163

140-
* **Reliability**: Ensures that messages can be processed without unwanted side effects from duplicates.
141-
* **Consistency**: Maintains data integrity by ensuring that duplicate messages do not cause redundant updates or actions.
142-
* **Fault Tolerance**: Handles message retries gracefully, preventing them from causing errors.
164+
* Prevents duplicate side effects
165+
* Increases reliability under repeated or delayed messages
166+
* Simplifies error handling and retry logic
143167

144-
### Trade-offs
168+
Trade-offs
145169

146-
* **State Management**: Requires storing processed message IDs, which can add memory overhead.
147-
* **Complexity**: Implementing deduplication mechanisms can increase the complexity of the system.
148-
* **Scalability**: In high-throughput systems, maintaining a large set of processed messages can impact performance and resource usage.
170+
* Requires careful design to track processed messages
171+
* Can add overhead for maintaining idempotency tokens or state
172+
* May require additional storage or database transactions
149173

150174
## Related Patterns in Java
151175

152-
* [Retry Pattern](https://java-design-patterns.com/patterns/retry/): Works well with the Idempotent Consumer pattern to handle failed messages.
153-
* [Circuit Breaker Pattern](https://java-design-patterns.com/patterns/circuitbreaker/): Often used alongside idempotent consumers to prevent repeated failures from causing overload.
176+
* Outbox Pattern: Uses a dedicated table or storage to reliably publish events and handle deduplication at the source.
154177

155178
## References and Credits
156179

180+
* [Building Microservices](https://amzn.to/3UACtrU)
157181
* [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/4dznP2Y)
158-
* [Designing Data-Intensive Applications](https://amzn.to/3UADv7Q)
182+
* [Microservices Patterns: With examples in Java](https://amzn.to/3UyWD5O)
Loading

‎microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/RequestService.java

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -44,18 +44,15 @@ public RequestService(
4444
}
4545

4646
/**
47-
* Creates a new Request or returns an existing one by it's UUID. This operation is idempotent:
47+
* Creates a new Request or returns an existing one by its UUID. This operation is idempotent:
4848
* performing it once or several times successively leads to an equivalent result.
4949
*
5050
* @param uuid The unique identifier for the Request.
5151
* @return Return existing Request or save and return a new Request.
5252
*/
5353
public Request create(UUID uuid) {
5454
Optional<Request> optReq = requestRepository.findById(uuid);
55-
if (!optReq.isEmpty()) {
56-
return optReq.get();
57-
}
58-
return requestRepository.save(new Request(uuid));
55+
return optReq.orElseGet(() -> requestRepository.save(new Request(uuid)));
5956
}
6057

6158
/**

‎microservices-idempotent-consumer/src/test/java/com/iluwatar/idempotentconsumer/AppTest.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,12 +39,12 @@
3939
class AppTest {
4040

4141
@Test
42-
void main() {
42+
void testMain() {
4343
assertDoesNotThrow(() -> App.main(new String[] {}));
4444
}
4545

4646
@Test
47-
void run() throws Exception {
47+
void testRun() throws Exception {
4848
RequestService requestService = Mockito.mock(RequestService.class);
4949
RequestRepository requestRepository = Mockito.mock(RequestRepository.class);
5050
UUID uuid = UUID.randomUUID();

‎microservices-idempotent-consumer/src/test/java/com/iluwatar/idempotentconsumer/RequestServiceTests.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,11 +43,10 @@
4343
class RequestServiceTests {
4444
private RequestService requestService;
4545
@Mock private RequestRepository requestRepository;
46-
private RequestStateMachine requestStateMachine;
4746

4847
@BeforeEach
4948
void setUp() {
50-
requestStateMachine = new RequestStateMachine();
49+
RequestStateMachine requestStateMachine = new RequestStateMachine();
5150
requestService = new RequestService(requestRepository, requestStateMachine);
5251
}
5352

‎microservices-idempotent-consumer/src/test/java/com/iluwatar/idempotentconsumer/RequestStateMachineTests.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ class RequestStateMachineTests {
3535
private RequestStateMachine requestStateMachine;
3636

3737
@BeforeEach
38-
public void setUp() {
38+
void setUp() {
3939
requestStateMachine = new RequestStateMachine();
4040
}
4141

‎money/README.md

Lines changed: 74 additions & 103 deletions
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)

‎money/etc/money-flowchart.png

56.3 KB
Loading

‎money/etc/money-mind-map.png

149 KB
Loading

‎money/src/main/java/com/iluwatar/Money.java

Lines changed: 4 additions & 13 deletions
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.

‎money/src/test/java/com/iluwater/money/MoneyTest.java

Lines changed: 6 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -59,11 +59,7 @@ void testAddMoney_DifferentCurrency() {
5959
Money money1 = new Money(100.00, "USD");
6060
Money money2 = new Money(50.25, "EUR");
6161

62-
assertThrows(
63-
CannotAddTwoCurrienciesException.class,
64-
() -> {
65-
money1.addMoney(money2);
66-
});
62+
assertThrows(CannotAddTwoCurrienciesException.class, () -> money1.addMoney(money2));
6763
}
6864

6965
@Test
@@ -83,11 +79,7 @@ void testSubtractMoney_DifferentCurrency() {
8379
Money money1 = new Money(100.00, "USD");
8480
Money money2 = new Money(50.25, "EUR");
8581

86-
assertThrows(
87-
CannotSubtractException.class,
88-
() -> {
89-
money1.subtractMoney(money2);
90-
});
82+
assertThrows(CannotSubtractException.class, () -> money1.subtractMoney(money2));
9183
}
9284

9385
@Test
@@ -96,11 +88,7 @@ void testSubtractMoney_AmountTooLarge() {
9688
Money money1 = new Money(50.00, "USD");
9789
Money money2 = new Money(60.00, "USD");
9890

99-
assertThrows(
100-
CannotSubtractException.class,
101-
() -> {
102-
money1.subtractMoney(money2);
103-
});
91+
assertThrows(CannotSubtractException.class, () -> money1.subtractMoney(money2));
10492
}
10593

10694
@Test
@@ -118,11 +106,7 @@ void testMultiply_NegativeFactor() {
118106
// Test multiplying by a negative factor
119107
Money money = new Money(100.00, "USD");
120108

121-
assertThrows(
122-
IllegalArgumentException.class,
123-
() -> {
124-
money.multiply(-2);
125-
});
109+
assertThrows(IllegalArgumentException.class, () -> money.multiply(-2));
126110
}
127111

128112
@Test
@@ -141,19 +125,12 @@ void testExchangeCurrency_NegativeExchangeRate() {
141125
// Test converting currency with a negative exchange rate
142126
Money money = new Money(100.00, "USD");
143127

144-
assertThrows(
145-
IllegalArgumentException.class,
146-
() -> {
147-
money.exchangeCurrency("EUR", -0.85);
148-
});
128+
assertThrows(IllegalArgumentException.class, () -> money.exchangeCurrency("EUR", -0.85));
149129
}
150130

151131
@Test
152132
void testAppExecution() {
153133
assertDoesNotThrow(
154-
() -> {
155-
App.main(new String[] {});
156-
},
157-
"App execution should not throw any exceptions");
134+
() -> App.main(new String[] {}), "App execution should not throw any exceptions");
158135
}
159136
}

0 commit comments

Comments
 (0)
Please sign in to comment.