Redundant null checks for nested properties
Expected behavior
Consider this simple DTO and Entity classes:
@Data public class PersonDTO { private String name; private String parentName; }
@Data public class Person { private String name; private Person parent; }
And a simple mapper:
@Mapper public interface PersonMapper { @Mapping(target = "parentName", source = "parent.name") PersonDTO entityToDTO(Person person); }
Generated code should be:
public class PersonMapperImpl implements PersonMapper { @Override public PersonDTO entityToDTO(Person person) { if ( person == null ) { return null; } PersonDTO personDTO = new PersonDTO(); personDTO.setParentName( personParentName( person ) ); personDTO.setName( person.getName() ); return personDTO; } private String personParentName(Person person) { Person parent = person.getParent(); if ( parent == null ) { return null; } return parent.getName(); }
Actual behavior
Generated code is this:
public class PersonMapperImpl implements PersonMapper { @Override public PersonDTO entityToDTO(Person person) { if ( person == null ) { return null; } PersonDTO personDTO = new PersonDTO(); personDTO.setParentName( personParentName( person ) ); personDTO.setName( person.getName() ); return personDTO; } private String personParentName(Person person) { if ( person == null ) { // Redundant null check, unreachable return statement return null; } Person parent = person.getParent(); if ( parent == null ) { return null; } String name = parent.getName(); if ( name == null ) { // Redundant null check, just return the parent name return null; } return name; }
As marked, two additional redundant null checks were generated. The first one makes it impossible to reach full code coverage (unless using Reflection) and the second is just unnecessary code.
Steps to reproduce the problem
No special configuration needed to reproduce this.
MapStruct Version
MapStruct 1.5.4.Final