BadPractice4 - SpotBugsExtensionForSpringFrameWork/CS5098 GitHub Wiki

Summary: Use DTO rather than directly sending Entity.

Description & Theory

Exposing your internal structure is never a good idea because it creates inflexibility in service design and consequently promotes bad coding practices. Also, unnecessary transmitted values make the speed slow down.

"You might argue that having a DTO object, when a new column is added to the database, means you have to do double work, adding the property in both the entity and the DTO. That is technically correct. It requires a bit of extra effort to maintain two classes instead of one. However, you need to compare the effort required. When one or more new columns are added, copy/pasting a few properties doesn't take all that long. When the data model changes structurally, having to change the frontend, possibly in ways that only cause bugs at runtime (and not at compile time), takes considerably more effort, and it requires the developer(s) to go hunting for bugs." (link)

@Entity
@NoArgsConstructor
@Getter
public class TopTalentEntity {
    @Id
    @GeneratedValue
    private Integer id;

    @Column
    private String name;

    public TopTalentEntity(String name) {
        this.name = name;
    }

}

Solutions

a more flexible solution would be creating a new class to represent the TopTalentEntity data on the API endpoint

@AllArgsConstructor
@NoArgsConstructor
@Getter
public class TopTalentData {
    private String name;
}

Implementation Strategy

  1. Find the points where @Entity is used
  2. Check if the entity has its Data Transfer Object (DTO)
    • Generally, suffixed with DTO.
    • Could check the control flow if an entity is directly passed
  3. If not, recommend using DTO

Reference List

https://www.toptal.com/spring/top-10-most-common-spring-framework-mistakes https://softwareengineering.stackexchange.com/questions/373284/what-is-the-use-of-dto-instead-of-entity https://stackoverflow.com/questions/1724774/java-data-transfer-object-naming-convention