Browser docs

Converter

Intent

The purpose of the Converter pattern is to provide a generic, common way of bidirectional conversion between corresponding types, allowing a clean implementation in which the types do not need to be aware of each other. Moreover, the Converter pattern introduces bidirectional collection mapping, reducing a boilerplate code to minimum.

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.

 1public class Converter<T, U> {
 2
 3  private final Function<T, U> fromDto;
 4  private final Function<U, T> fromEntity;
 5
 6  public Converter(final Function<T, U> fromDto, final Function<U, T> fromEntity) {
 7    this.fromDto = fromDto;
 8    this.fromEntity = fromEntity;
 9  }
10
11  public final U convertFromDto(final T dto) {
12    return fromDto.apply(dto);
13  }
14
15  public final T convertFromEntity(final U entity) {
16    return fromEntity.apply(entity);
17  }
18
19  public final List<U> createFromDtos(final Collection<T> dtos) {
20    return dtos.stream().map(this::convertFromDto).collect(Collectors.toList());
21  }
22
23  public final List<T> createFromEntities(final Collection<U> entities) {
24    return entities.stream().map(this::convertFromEntity).collect(Collectors.toList());
25  }
26}

The specialized converters inherit from this base class as follows.

 1public class UserConverter extends Converter<UserDto, User> {
 2
 3  public UserConverter() {
 4    super(UserConverter::convertToEntity, UserConverter::convertToDto);
 5  }
 6
 7  private static UserDto convertToDto(User user) {
 8    return new UserDto(user.getFirstName(), user.getLastName(), user.isActive(), user.getUserId());
 9  }
10
11  private static User convertToEntity(UserDto dto) {
12    return new User(dto.getFirstName(), dto.getLastName(), dto.isActive(), dto.getEmail());
13  }
14
15}

Now mapping between User and UserDto becomes trivial.

1var userConverter = new UserConverter();
2var dtoUser = new UserDto("John", "Doe", true, "whatever[at]wherever.com");
3var user = userConverter.convertFromDto(dtoUser);

Class diagram

alt text

Applicability

Use the Converter Pattern in the following situations:

  • When you have types that logically correspond with each other and you need to convert entities between them.
  • When you want to provide different ways of types conversions depending on the context.
  • Whenever you introduce a DTO (Data transfer object), you will probably need to convert it into the domain equivalence.

Credits