Where should I keep logic for derived fields (derived from attributes of the same model class) - in model layer or in service layer?
Example:
In the code below, age is derived from dateOfBirth (do not ask why you need to persist age when it can be derived from dateOfBirth in the model class - this is a hypothetical example). Where should I keep calculateAge() method - in PersonModel or PersonService?
import java.util.Date;
models/Person.java
@Entity
public class Person {
private Date dateOfBirth;
private String age;
}
service/PersonService.java
public interface PersonService {
}
CodePudding user response:
Not sure what you mean by "where to keep it", but this usually depends if you want to treat your entity model as domain or persistence model. Lots of people don't need to distinguish between these two models(because the differences are minimal) and just put everything into the entity class. As soon as the domain logic becomes more important, people usually introduce some sort of domain model on top of the entity model, within which the entity state is encapsulated, and translation between the models happens in the service layer implementation.
This is an open ended question, so you won't get a definitive answer. This is just what I observed from other projects and how I understand this is usually done or supposed to be. Do what works best for you and always ask yourself if the abstraction brings value to your project before applying a design pattern like this.