Skip to content

Commit cc4b990

Browse files
committed
iluwatar#590 Add explanation for Converter pattern
1 parent 8747f1f commit cc4b990

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

converter/README.md

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,71 @@ mapping, reducing a boilerplate code to minimum.
1717

1818
![alt text](./etc/converter.png "Converter Pattern")
1919

20+
## Explanation
21+
22+
Real world example
23+
24+
> In real world applications it is often the case that database layer consists of entities that need to be mapped into DTOs for use on the business logic layer. Similar mapping is done for potentially huge amount of classes and we need a generic way to achieve this.
25+
26+
In plain words
27+
28+
> Converter pattern makes it easy to map instances of one class into instances of another class.
29+
30+
**Programmatic Example**
31+
32+
We need a generic solution for the mapping problem. To achieve this, let's introduce a generic converter.
33+
34+
```java
35+
public class Converter<T, U> {
36+
37+
private final Function<T, U> fromDto;
38+
private final Function<U, T> fromEntity;
39+
40+
public Converter(final Function<T, U> fromDto, final Function<U, T> fromEntity) {
41+
this.fromDto = fromDto;
42+
this.fromEntity = fromEntity;
43+
}
44+
45+
public final U convertFromDto(final T dto) {
46+
return fromDto.apply(dto);
47+
}
48+
49+
public final T convertFromEntity(final U entity) {
50+
return fromEntity.apply(entity);
51+
}
52+
53+
public final List<U> createFromDtos(final Collection<T> dtos) {
54+
return dtos.stream().map(this::convertFromDto).collect(Collectors.toList());
55+
}
56+
57+
public final List<T> createFromEntities(final Collection<U> entities) {
58+
return entities.stream().map(this::convertFromEntity).collect(Collectors.toList());
59+
}
60+
}
61+
```
62+
63+
The specialized converters inherit from this base class as follows.
64+
65+
```java
66+
public class UserConverter extends Converter<UserDto, User> {
67+
68+
public UserConverter() {
69+
super(userDto -> new User(userDto.getFirstName(), userDto.getLastName(), userDto.isActive(),
70+
userDto.getEmail()),
71+
user -> new UserDto(user.getFirstName(), user.getLastName(), user.isActive(),
72+
user.getUserId()));
73+
}
74+
}
75+
```
76+
77+
Now mapping between User and UserDto becomes trivial.
78+
79+
```java
80+
Converter<UserDto, User> userConverter = new UserConverter();
81+
UserDto dtoUser = new UserDto("John", "Doe", true, "whatever[at]wherever.com");
82+
User user = userConverter.convertFromDto(dtoUser);
83+
```
84+
2085
## Applicability
2186
Use the Converter Pattern in the following situations:
2287

0 commit comments

Comments
 (0)