Browser docs



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.


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> {
 3  private final Function<T, U> fromDto;
 4  private final Function<U, T> fromEntity;
 6  public Converter(final Function<T, U> fromDto, final Function<U, T> fromEntity) {
 7    this.fromDto = fromDto;
 8    this.fromEntity = fromEntity;
 9  }
11  public final U convertFromDto(final T dto) {
12    return fromDto.apply(dto);
13  }
15  public final T convertFromEntity(final U entity) {
16    return fromEntity.apply(entity);
17  }
19  public final List<U> createFromDtos(final Collection<T> dtos) {
20    return;
21  }
23  public final List<T> createFromEntities(final Collection<U> entities) {
24    return;
25  }

The specialized converters inherit from this base class as follows.

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

Now mapping between User and UserDto becomes trivial.

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

Class diagram

alt text


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.