In this article we aim to clarify why sometimes it’s important to map two different classes and how it’s possible to do it by building the simplest possible mapping manager step-by-step. Design choices / constraints often produce a considerable amount of mechanical work which we will try to minimize by automatically mapping Java objects.
By “mapping objects” we mean copy one object state to another object. Sometimes the mapping is transparent, considering that both objects have the same attributes, but often it happens between two objects with different attributes. Those who are familiar with Web API development probably already faced a situation where your resource representation is similar but not identical to the domain model or even when you don’t want to expose your domain objects to any other layer within your system. In these cases we generally create a component to abstract this mapping task, which also allow us to reuse it in other parts of the system.
An advantage of having a mapping component (e.g. to map your domain to DTO and vice versa) is not as apparent when you are only supporting a single mapping, but as the number of mappings increases, having that code isolated from the domain helps to keep the domain simpler and leaner. You won’t be cluttering your domain with a lot of extra weight.
To clarify the mapping idea, let’s start creating two domain classes (Customer and Address) and one DTO class (CustomerDTO).