Writing Invariants For POJOs That Validate Business Rules

Viewed 81

I want to start incorporating the practice of writing invariants for my classes. For my POJOs, is it a good practice to validate its state by validating it against business rules. Say I have this class for instance:

@Data
public class Pick {
    List<Substitution> substitutions = new ArrayList<>();
}

Now, my invariant says that every substitution object in the list needs to have a substitution reason. Is it a good practice to do such business checks inside POJOs that are meant to be simple data carriers?

Note that I already use @NonNull which is also an invariant, although a very basic one. Is it a good practice to write invariants that test for complex business relationships b/w your fields?

1 Answers

JSR 380 is a specification of the Java API for bean validation, part of Jakarta EE and JavaSE, which ensures that the properties of a bean meet specific criteria, using annotations such as @NotNull, @Min, and @Max.

We can see this approach used in Java ecosystem heavily, as far as it doesn't touch your business logic and also data object and keeps them clean it is goof

more here

Related