mardi 19 octobre 2021

Create a mapping function depending on type hierarchy

I have an application that follows Domain Driven Design rules. One of the rules of DDD is that the domain layer should not depend on the infrastructure layer. I have a tool that checks if there are any dependencies (imports) from domain to infrastructure. In my infrastructure layer, I have a class hierarchy like this:

infrastructure

In my domain layer, like this:

domain

Now, I need to map my domain classes to the infrastructure entities in order to save them in my database.

I have an out port in my domain which is an interface:

// infra/ports/out/RuleRepository.java
public interface RuleRepository {
  Rule save(Rule rule);
}

This interface in implemented in the infrastructure layer:

// domain/RuleRepositoryJpaAdapter.java
public class RuleRepositoryJpaAdapter implements RuleRepository {

  // extends CrudRepository<RuleEntity, Long>
  RuleCrudRepository jpaRepository;
  RuleMapper mapper;

  @Override
  public Rule save(Rule rule) {
    return jpaRepository.save(mapper.mapToEntity(rule))
      .mapToDomain();
  }
}

I'm looking for a way to implement mapToEntity without having to check the type of the rule. The best way would be to add a mapToEntity method to Rule, IpRule, BlackListRule but this would break the unit tests that check if there is any imports between the domain and infrastructure layer. If there any other way?

What I have right now:

public class RuleMapper {

  public RuleEntity mapToEntity(Rule rule) {
    if (rule instanceof IpRule) {
      return new IpRuleEntity().mapFromDomain(rule);
    } else if (rule instanceof BlackListRule) {
      return new BlackListRuleEntity().mapFromDomain(rule);
    } else {
      throw new IllegalArgumentException("Unexpected argument of type " + (rule == null ? "null" : rule.getClass().getName()));
    }
  }

}

Aucun commentaire:

Enregistrer un commentaire