mirror of
https://github.com/tiennm99/java-design-patterns.git
synced 2026-10-13 12:14:51 +00:00
docs: update tolerant reader
This commit is contained in:
1 parent
628ec1548c
commit
6ed6b1c0f0
6 files changed
+142
-149
No files matched your search
@@ -57,3 +57,5 @@ build/
|
|||||||
#################### Java Design Patterns #######
|
#################### Java Design Patterns #######
|
||||||
etc/Java Design Patterns.urm.puml
|
etc/Java Design Patterns.urm.puml
|
||||||
serialized-entity/output.txt
|
serialized-entity/output.txt
|
||||||
|
fish1.out
|
||||||
|
fish2.out
|
||||||
+133
-145
@@ -1,28 +1,31 @@
|
|||||||
---
|
---
|
||||||
title: Tolerant Reader
|
title: Tolerant Reader
|
||||||
category: Integration
|
category: Resilience
|
||||||
language: en
|
language: en
|
||||||
tag:
|
tag:
|
||||||
- Decoupling
|
- API design
|
||||||
|
- Decoupling
|
||||||
|
- Fault tolerance
|
||||||
|
- Integration
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Also known as
|
||||||
|
|
||||||
|
* Lenient Consumer
|
||||||
|
|
||||||
## Intent
|
## Intent
|
||||||
|
|
||||||
Tolerant Reader is an integration pattern that helps creating robust communication systems. The idea
|
Allows a system to be more resilient to changes in the data structures it consumes by ignoring elements that it does not recognize.
|
||||||
is to be as tolerant as possible when reading data from another service. This way, when the
|
|
||||||
communication schema changes, the readers must not break.
|
|
||||||
|
|
||||||
## Explanation
|
## Explanation
|
||||||
|
|
||||||
Real world example
|
Real world example
|
||||||
|
|
||||||
> We are persisting rainbowfish objects to file and later on they need to be restored. What makes it
|
> Imagine a postal system that delivers letters and packages to recipients. In this system, postal workers deliver mail regardless of additional information or stickers that might be present on the envelopes or packages. If a package has extra labels or instructions that the postal system does not recognize, the postal worker ignores these and focuses only on the essential information like the address. This approach ensures that the delivery process remains functional even when senders use different formats or include unnecessary details, similar to how the Tolerant Reader pattern works in software by ignoring unrecognized data elements to maintain functionality and compatibility.
|
||||||
> problematic is that rainbowfish data structure is versioned and evolves over time. New version of
|
|
||||||
> rainbowfish needs to be able to restore old versions as well.
|
|
||||||
|
|
||||||
In plain words
|
In plain words
|
||||||
|
|
||||||
> Tolerant Reader pattern is used to create robust communication mechanisms between services.
|
> Tolerant Reader pattern is used to create robust communication mechanisms between services.
|
||||||
|
|
||||||
[Robustness Principle](https://java-design-patterns.com/principles/#robustness-principle) says
|
[Robustness Principle](https://java-design-patterns.com/principles/#robustness-principle) says
|
||||||
|
|
||||||
@@ -30,186 +33,171 @@ In plain words
|
|||||||
|
|
||||||
**Programmatic Example**
|
**Programmatic Example**
|
||||||
|
|
||||||
|
We are persisting `RainbowFish` objects to file. Later on they need to be restored. What makes it problematic is that `RainbowFish` data structure is versioned and evolves over time. New version of `RainbowFish` needs to be able to restore old versions as well.
|
||||||
|
|
||||||
Here's the versioned `RainbowFish`. Notice how the second version introduces additional properties.
|
Here's the versioned `RainbowFish`. Notice how the second version introduces additional properties.
|
||||||
|
|
||||||
```java
|
```java
|
||||||
|
@Getter
|
||||||
|
@RequiredArgsConstructor
|
||||||
public class RainbowFish implements Serializable {
|
public class RainbowFish implements Serializable {
|
||||||
|
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
private final String name;
|
private final String name;
|
||||||
private final int age;
|
private final int age;
|
||||||
private final int lengthMeters;
|
private final int lengthMeters;
|
||||||
private final int weightTons;
|
private final int weightTons;
|
||||||
|
|
||||||
/**
|
|
||||||
* Constructor.
|
|
||||||
*/
|
|
||||||
public RainbowFish(String name, int age, int lengthMeters, int weightTons) {
|
|
||||||
this.name = name;
|
|
||||||
this.age = age;
|
|
||||||
this.lengthMeters = lengthMeters;
|
|
||||||
this.weightTons = weightTons;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getName() {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getAge() {
|
|
||||||
return age;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getLengthMeters() {
|
|
||||||
return lengthMeters;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getWeightTons() {
|
|
||||||
return weightTons;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Getter
|
||||||
public class RainbowFishV2 extends RainbowFish {
|
public class RainbowFishV2 extends RainbowFish {
|
||||||
|
|
||||||
private static final long serialVersionUID = 1L;
|
@Serial
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
private boolean sleeping;
|
private boolean sleeping;
|
||||||
private boolean hungry;
|
private boolean hungry;
|
||||||
private boolean angry;
|
private boolean angry;
|
||||||
|
|
||||||
public RainbowFishV2(String name, int age, int lengthMeters, int weightTons) {
|
public RainbowFishV2(String name, int age, int lengthMeters, int weightTons) {
|
||||||
super(name, age, lengthMeters, weightTons);
|
super(name, age, lengthMeters, weightTons);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
public RainbowFishV2(String name, int age, int lengthMeters, int weightTons, boolean sleeping,
|
||||||
* Constructor.
|
boolean hungry, boolean angry) {
|
||||||
*/
|
this(name, age, lengthMeters, weightTons);
|
||||||
public RainbowFishV2(String name, int age, int lengthMeters, int weightTons, boolean sleeping,
|
this.sleeping = sleeping;
|
||||||
boolean hungry, boolean angry) {
|
this.hungry = hungry;
|
||||||
this(name, age, lengthMeters, weightTons);
|
this.angry = angry;
|
||||||
this.sleeping = sleeping;
|
}
|
||||||
this.hungry = hungry;
|
|
||||||
this.angry = angry;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean getSleeping() {
|
|
||||||
return sleeping;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean getHungry() {
|
|
||||||
return hungry;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean getAngry() {
|
|
||||||
return angry;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Next we introduce the `RainbowFishSerializer`. This is the class that implements the Tolerant Reader
|
Next we introduce the `RainbowFishSerializer`. This is the class that implements the Tolerant Reader pattern.
|
||||||
pattern.
|
|
||||||
|
|
||||||
```java
|
```java
|
||||||
|
|
||||||
|
@NoArgsConstructor
|
||||||
public final class RainbowFishSerializer {
|
public final class RainbowFishSerializer {
|
||||||
|
|
||||||
private RainbowFishSerializer() {
|
public static void writeV1(RainbowFish rainbowFish, String filename) throws IOException {
|
||||||
}
|
var map = Map.of(
|
||||||
|
"name", rainbowFish.getName(),
|
||||||
|
"age", String.format("%d", rainbowFish.getAge()),
|
||||||
|
"lengthMeters", String.format("%d", rainbowFish.getLengthMeters()),
|
||||||
|
"weightTons", String.format("%d", rainbowFish.getWeightTons())
|
||||||
|
);
|
||||||
|
|
||||||
public static void writeV1(RainbowFish rainbowFish, String filename) throws IOException {
|
try (var fileOut = new FileOutputStream(filename);
|
||||||
var map = Map.of(
|
var objOut = new ObjectOutputStream(fileOut)) {
|
||||||
"name", rainbowFish.getName(),
|
objOut.writeObject(map);
|
||||||
"age", String.format("%d", rainbowFish.getAge()),
|
}
|
||||||
"lengthMeters", String.format("%d", rainbowFish.getLengthMeters()),
|
|
||||||
"weightTons", String.format("%d", rainbowFish.getWeightTons())
|
|
||||||
);
|
|
||||||
|
|
||||||
try (var fileOut = new FileOutputStream(filename);
|
|
||||||
var objOut = new ObjectOutputStream(fileOut)) {
|
|
||||||
objOut.writeObject(map);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void writeV2(RainbowFishV2 rainbowFish, String filename) throws IOException {
|
|
||||||
var map = Map.of(
|
|
||||||
"name", rainbowFish.getName(),
|
|
||||||
"age", String.format("%d", rainbowFish.getAge()),
|
|
||||||
"lengthMeters", String.format("%d", rainbowFish.getLengthMeters()),
|
|
||||||
"weightTons", String.format("%d", rainbowFish.getWeightTons()),
|
|
||||||
"angry", Boolean.toString(rainbowFish.getAngry()),
|
|
||||||
"hungry", Boolean.toString(rainbowFish.getHungry()),
|
|
||||||
"sleeping", Boolean.toString(rainbowFish.getSleeping())
|
|
||||||
);
|
|
||||||
|
|
||||||
try (var fileOut = new FileOutputStream(filename);
|
|
||||||
var objOut = new ObjectOutputStream(fileOut)) {
|
|
||||||
objOut.writeObject(map);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public static RainbowFish readV1(String filename) throws IOException, ClassNotFoundException {
|
|
||||||
Map<String, String> map;
|
|
||||||
|
|
||||||
try (var fileIn = new FileInputStream(filename);
|
|
||||||
var objIn = new ObjectInputStream(fileIn)) {
|
|
||||||
map = (Map<String, String>) objIn.readObject();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return new RainbowFish(
|
public static void writeV2(RainbowFishV2 rainbowFish, String filename) throws IOException {
|
||||||
map.get("name"),
|
var map = Map.of(
|
||||||
Integer.parseInt(map.get("age")),
|
"name", rainbowFish.getName(),
|
||||||
Integer.parseInt(map.get("lengthMeters")),
|
"age", String.format("%d", rainbowFish.getAge()),
|
||||||
Integer.parseInt(map.get("weightTons"))
|
"lengthMeters", String.format("%d", rainbowFish.getLengthMeters()),
|
||||||
);
|
"weightTons", String.format("%d", rainbowFish.getWeightTons()),
|
||||||
}
|
"angry", Boolean.toString(rainbowFish.getAngry()),
|
||||||
|
"hungry", Boolean.toString(rainbowFish.getHungry()),
|
||||||
|
"sleeping", Boolean.toString(rainbowFish.getSleeping())
|
||||||
|
);
|
||||||
|
|
||||||
|
try (var fileOut = new FileOutputStream(filename);
|
||||||
|
var objOut = new ObjectOutputStream(fileOut)) {
|
||||||
|
objOut.writeObject(map);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static RainbowFish readV1(String filename) throws IOException, ClassNotFoundException {
|
||||||
|
Map<String, String> map;
|
||||||
|
|
||||||
|
try (var fileIn = new FileInputStream(filename);
|
||||||
|
var objIn = new ObjectInputStream(fileIn)) {
|
||||||
|
map = (Map<String, String>) objIn.readObject();
|
||||||
|
}
|
||||||
|
|
||||||
|
return new RainbowFish(
|
||||||
|
map.get("name"),
|
||||||
|
Integer.parseInt(map.get("age")),
|
||||||
|
Integer.parseInt(map.get("lengthMeters")),
|
||||||
|
Integer.parseInt(map.get("weightTons"))
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
And finally here's the full example in action.
|
And finally, here's the full example in action.
|
||||||
|
|
||||||
```java
|
```java
|
||||||
var fishV1 = new RainbowFish("Zed", 10, 11, 12);
|
// Write V1
|
||||||
LOGGER.info("fishV1 name={} age={} length={} weight={}", fishV1.getName(),
|
var fishV1 = new RainbowFish("Zed", 10, 11, 12);
|
||||||
fishV1.getAge(), fishV1.getLengthMeters(), fishV1.getWeightTons());
|
LOGGER.info("fishV1 name={} age={} length={} weight={}", fishV1.getName(), fishV1.getAge(), fishV1.getLengthMeters(), fishV1.getWeightTons());
|
||||||
RainbowFishSerializer.writeV1(fishV1, "fish1.out");
|
RainbowFishSerializer.writeV1(fishV1, "fish1.out");
|
||||||
|
|
||||||
var deserializedRainbowFishV1 = RainbowFishSerializer.readV1("fish1.out");
|
// Read V1
|
||||||
LOGGER.info("deserializedFishV1 name={} age={} length={} weight={}",
|
var deserializedRainbowFishV1 = RainbowFishSerializer.readV1("fish1.out");
|
||||||
deserializedRainbowFishV1.getName(), deserializedRainbowFishV1.getAge(),
|
LOGGER.info("deserializedFishV1 name={} age={} length={} weight={}", deserializedRainbowFishV1.getName(), deserializedRainbowFishV1.getAge(), deserializedRainbowFishV1.getLengthMeters(), deserializedRainbowFishV1.getWeightTons());
|
||||||
deserializedRainbowFishV1.getLengthMeters(), deserializedRainbowFishV1.getWeightTons());
|
|
||||||
|
|
||||||
var fishV2 = new RainbowFishV2("Scar", 5, 12, 15, true, true, true);
|
// Write V2
|
||||||
LOGGER.info(
|
var fishV2 = new RainbowFishV2("Scar", 5, 12, 15, true, true, true);
|
||||||
"fishV2 name={} age={} length={} weight={} sleeping={} hungry={} angry={}",
|
LOGGER.info("fishV2 name={} age={} length={} weight={} sleeping={} hungry={} angry={}", fishV2.getName(), fishV2.getAge(), fishV2.getLengthMeters(), fishV2.getWeightTons(), fishV2.isHungry(), fishV2.isAngry(), fishV2.isSleeping());
|
||||||
fishV2.getName(), fishV2.getAge(), fishV2.getLengthMeters(), fishV2.getWeightTons(),
|
RainbowFishSerializer.writeV2(fishV2, "fish2.out");
|
||||||
fishV2.getHungry(), fishV2.getAngry(), fishV2.getSleeping());
|
|
||||||
RainbowFishSerializer.writeV2(fishV2, "fish2.out");
|
|
||||||
|
|
||||||
var deserializedFishV2 = RainbowFishSerializer.readV1("fish2.out");
|
// Read V2 with V1 method
|
||||||
LOGGER.info("deserializedFishV2 name={} age={} length={} weight={}",
|
var deserializedFishV2 = RainbowFishSerializer.readV1("fish2.out");
|
||||||
deserializedFishV2.getName(), deserializedFishV2.getAge(),
|
LOGGER.info("deserializedFishV2 name={} age={} length={} weight={}", deserializedFishV2.getName(), deserializedFishV2.getAge(), deserializedFishV2.getLengthMeters(), deserializedFishV2.getWeightTons());
|
||||||
deserializedFishV2.getLengthMeters(), deserializedFishV2.getWeightTons());
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Program output:
|
Program output:
|
||||||
|
|
||||||
```
|
```
|
||||||
fishV1 name=Zed age=10 length=11 weight=12
|
15:38:00.602 [main] INFO com.iluwatar.tolerantreader.App -- fishV1 name=Zed age=10 length=11 weight=12
|
||||||
deserializedFishV1 name=Zed age=10 length=11 weight=12
|
15:38:00.618 [main] INFO com.iluwatar.tolerantreader.App -- deserializedFishV1 name=Zed age=10 length=11 weight=12
|
||||||
fishV2 name=Scar age=5 length=12 weight=15 sleeping=true hungry=true angry=true
|
15:38:00.618 [main] INFO com.iluwatar.tolerantreader.App -- fishV2 name=Scar age=5 length=12 weight=15 sleeping=true hungry=true angry=true
|
||||||
deserializedFishV2 name=Scar age=5 length=12 weight=15
|
15:38:00.619 [main] INFO com.iluwatar.tolerantreader.App -- deserializedFishV2 name=Scar age=5 length=12 weight=15
|
||||||
```
|
```
|
||||||
|
|
||||||
## Class diagram
|
## Class diagram
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
## Applicability
|
## Applicability
|
||||||
|
|
||||||
Use the Tolerant Reader pattern when
|
* Use when a system needs to consume data from external sources that may change over time.
|
||||||
|
* Applicable when backward compatibility is required in API design.
|
||||||
|
* Suitable for integration scenarios where different systems exchange data and evolve independently.
|
||||||
|
|
||||||
* The communication schema can evolve and change and yet the receiving side should not break
|
## Known Uses
|
||||||
|
|
||||||
|
* JSON or XML parsers that skip unknown elements.
|
||||||
|
* API clients in microservices architectures that interact with multiple versions of a service.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
Benefits:
|
||||||
|
|
||||||
|
* Increases the robustness and flexibility of the system.
|
||||||
|
* Allows independent evolution of producers and consumers in a distributed system.
|
||||||
|
* Simplifies versioning by enabling backward compatibility.
|
||||||
|
|
||||||
|
Trade-offs:
|
||||||
|
|
||||||
|
* May result in silent failures if important data is ignored.
|
||||||
|
* Can complicate debugging and tracing of issues due to missing or unrecognized data.
|
||||||
|
|
||||||
|
## Related Patterns
|
||||||
|
|
||||||
|
* [Adapter](https://java-design-patterns.com/patterns/adapter/): Both patterns deal with data transformation and integration, but the Adapter Pattern focuses on converting interfaces, while Tolerant Reader focuses on ignoring unrecognized data.
|
||||||
|
* [Facade](https://java-design-patterns.com/patterns/facade/): Simplifies interactions with complex systems, similar to how Tolerant Reader simplifies data consumption by ignoring irrelevant data.
|
||||||
|
* [Strategy](https://java-design-patterns.com/patterns/strategy/): Can be used in conjunction with Tolerant Reader to dynamically switch between different data handling strategies.
|
||||||
|
|
||||||
## Credits
|
## Credits
|
||||||
|
|
||||||
* [Martin Fowler - Tolerant Reader](http://martinfowler.com/bliki/TolerantReader.html)
|
* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
|
||||||
* [Service Design Patterns: Fundamental Design Solutions for SOAP/WSDL and RESTful Web Services](https://www.amazon.com/gp/product/032154420X/ref=as_li_tl?ie=UTF8&tag=javadesignpat-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=032154420X&linkId=94f9516e747ac2b449a959d5b096c73c)
|
* [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)
|
||||||
|
* [Service Design Patterns: Fundamental Design Solutions for SOAP/WSDL and RESTful Web Services](https://amzn.to/4dNIfOx)
|
||||||
|
* [Tolerant Reader - Martin Fowler](http://martinfowler.com/bliki/TolerantReader.html)
|
||||||
@@ -28,7 +28,7 @@ import java.io.IOException;
|
|||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tolerant Reader is an integration pattern that helps creating robust communication systems. The
|
* Tolerant Reader is an integration pattern that helps to create robust communication systems. The
|
||||||
* idea is to be as tolerant as possible when reading data from another service. This way, when the
|
* idea is to be as tolerant as possible when reading data from another service. This way, when the
|
||||||
* communication schema changes, the readers must not break.
|
* communication schema changes, the readers must not break.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -24,6 +24,7 @@
|
|||||||
*/
|
*/
|
||||||
package com.iluwatar.tolerantreader;
|
package com.iluwatar.tolerantreader;
|
||||||
|
|
||||||
|
import java.io.Serial;
|
||||||
import java.io.Serializable;
|
import java.io.Serializable;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
@@ -35,6 +36,7 @@ import lombok.RequiredArgsConstructor;
|
|||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class RainbowFish implements Serializable {
|
public class RainbowFish implements Serializable {
|
||||||
|
|
||||||
|
@Serial
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
private final String name;
|
private final String name;
|
||||||
|
|||||||
+2
-3
@@ -30,6 +30,7 @@ import java.io.IOException;
|
|||||||
import java.io.ObjectInputStream;
|
import java.io.ObjectInputStream;
|
||||||
import java.io.ObjectOutputStream;
|
import java.io.ObjectOutputStream;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* RainbowFishSerializer provides methods for reading and writing {@link RainbowFish} objects to
|
* RainbowFishSerializer provides methods for reading and writing {@link RainbowFish} objects to
|
||||||
@@ -37,14 +38,12 @@ import java.util.Map;
|
|||||||
* RainbowFish} objects. This way the reader does not break even though new properties are added to
|
* RainbowFish} objects. This way the reader does not break even though new properties are added to
|
||||||
* the schema.
|
* the schema.
|
||||||
*/
|
*/
|
||||||
|
@NoArgsConstructor
|
||||||
public final class RainbowFishSerializer {
|
public final class RainbowFishSerializer {
|
||||||
|
|
||||||
public static final String LENGTH_METERS = "lengthMeters";
|
public static final String LENGTH_METERS = "lengthMeters";
|
||||||
public static final String WEIGHT_TONS = "weightTons";
|
public static final String WEIGHT_TONS = "weightTons";
|
||||||
|
|
||||||
private RainbowFishSerializer() {
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Write V1 RainbowFish to file.
|
* Write V1 RainbowFish to file.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -24,6 +24,7 @@
|
|||||||
*/
|
*/
|
||||||
package com.iluwatar.tolerantreader;
|
package com.iluwatar.tolerantreader;
|
||||||
|
|
||||||
|
import java.io.Serial;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -32,6 +33,7 @@ import lombok.Getter;
|
|||||||
@Getter
|
@Getter
|
||||||
public class RainbowFishV2 extends RainbowFish {
|
public class RainbowFishV2 extends RainbowFish {
|
||||||
|
|
||||||
|
@Serial
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
private boolean sleeping;
|
private boolean sleeping;
|
||||||
|
|||||||
Reference in new issue
Block a user