Redundant if condition in Java record mapping with RETURN_DEFAULT strategy
Expected behavior
The generated code should avoid unnecessary empty if blocks. It should generate something like these:
@Override public ApiCategoryRecord mapRecord(Category category) { Long id = null; String title = null; if ( category != null ) { id = category.getId(); title = category.getTitle(); } ApiCategoryRecord apiCategoryRecord = new ApiCategoryRecord( id, title ); return apiCategoryRecord; }
OR
@Override public ApiCategoryRecord mapRecord(Category category) { if ( category != null ) { return new ApiCategoryRecord( category.getId(), category.getTitle() ); } else { return new ApiCategoryRecord( null, null ); } }
Actual behavior
MapStruct generates an empty and unnecessary if block after constructing the record:
@Override public ApiCategoryRecord mapRecord(Category category) { Long id = null; String title = null; if ( category != null ) { id = category.getId(); title = category.getTitle(); } ApiCategoryRecord apiCategoryRecord = new ApiCategoryRecord( id, title ); if ( category != null ) { } return apiCategoryRecord; }
Literally this is not a bug but a minor inefficiency in the generated code.
It does not affect functionality, removing the redundant if condition would improve code clarity and doesn’t suggest anything went wrong during generation.
Steps to reproduce the problem
Use the following setup
public class Category { private Long id; private String title; public Long getId() { return id; } public String getTitle() { return title; } } public record ApiCategoryRecord(Long id, String title) {} @Mapper(nullValueMappingStrategy = NullValueMappingStrategy.RETURN_DEFAULT) public interface ICategoryMapper { ApiCategoryRecord mapRecord(Category category); }
MapStruct Version
1.6.2