From cc4b990ae8487049123aa48d05a364ab157f81bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ilkka=20Sepp=C3=A4l=C3=A4?= Date: Sat, 16 Nov 2019 21:06:05 +0200 Subject: [PATCH] #590 Add explanation for Converter pattern --- converter/README.md | 65 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/converter/README.md b/converter/README.md index 79b539422892..5cde646eedbc 100644 --- a/converter/README.md +++ b/converter/README.md @@ -17,6 +17,71 @@ mapping, reducing a boilerplate code to minimum. ![alt text](./etc/converter.png "Converter Pattern") +## Explanation + +Real world example + +> 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. + +In plain words + +> Converter pattern makes it easy to map instances of one class into instances of another class. + +**Programmatic Example** + +We need a generic solution for the mapping problem. To achieve this, let's introduce a generic converter. + +```java +public class Converter { + + private final Function fromDto; + private final Function fromEntity; + + public Converter(final Function fromDto, final Function fromEntity) { + this.fromDto = fromDto; + this.fromEntity = fromEntity; + } + + public final U convertFromDto(final T dto) { + return fromDto.apply(dto); + } + + public final T convertFromEntity(final U entity) { + return fromEntity.apply(entity); + } + + public final List createFromDtos(final Collection dtos) { + return dtos.stream().map(this::convertFromDto).collect(Collectors.toList()); + } + + public final List createFromEntities(final Collection entities) { + return entities.stream().map(this::convertFromEntity).collect(Collectors.toList()); + } +} +``` + +The specialized converters inherit from this base class as follows. + +```java +public class UserConverter extends Converter { + + public UserConverter() { + super(userDto -> new User(userDto.getFirstName(), userDto.getLastName(), userDto.isActive(), + userDto.getEmail()), + user -> new UserDto(user.getFirstName(), user.getLastName(), user.isActive(), + user.getUserId())); + } +} +``` + +Now mapping between User and UserDto becomes trivial. + +```java +Converter userConverter = new UserConverter(); +UserDto dtoUser = new UserDto("John", "Doe", true, "whatever[at]wherever.com"); +User user = userConverter.convertFromDto(dtoUser); +``` + ## Applicability Use the Converter Pattern in the following situations: