Do @Annotations create a dependency relationship?
No one doubts the effectiveness of annotations in Java. Since they were included in the language, their use has been widespread in various frameworks and libraries. Their usage is almost inevitable in large applications. Or will you tell me you can live without Lombok and JPA?
But I'm not questioning their importance here. The main point is the dependency relationship they create. If, indeed, they do create one.
When developing applications following best practices and certain architectures, like clean code and hexagonal architecture, we strive to ensure that business classes do not depend on the technology. After all, following the SRP principle, classes should only have one reason to change!
Frameworks are wonderful in a programmer’s life, but they are always trying to put their tentacles into our code, making us dependent on them forever! It is the job of the software designer to do everything to prevent this from happening. Here's the question: If you decide to change the framework, will your business modules remain intact? Or will you need to hit CTRL+F (if you know what I mean)?
But enough talk; let’s get to an example! Check out the code below of a class representing a model.
领英推荐
package com.example.accessingdatajpa;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Customer {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
protected Customer() {}
public Customer(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return String.format(
"Customer[id=%d, firstName='%s', lastName='%s']",
id, firstName, lastName);
}
public Long getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}
This model is at the core of the business module. However, we can see several annotations related to JPA for persistence. But weren’t all these database-related things supposed to be hidden below a Repository or DAO implementation?
The purpose of this article is not to reach a conclusion but rather to open an honest discussion.
Please share your opinion in the comments.
#Java #CleanCode #SRP
Senior Software Engineer @ Start Consig | Java and Spring Boot Specialist
6 个月Insightful discussion on the impact of annotations! It's crucial to balance convenience with clean architecture.