java static factory methods in Spring Model class

118 Views Asked by At

Is it good to use java static factory method in Spring Model Class for validate field with some kind of equation

2

There are 2 best solutions below

0
Boris On

I would recommend to avoid this by the following reasons:

  1. You lose separation of concern between model and model validation logic. Especially if validation touches only a few fields. Adding/modifying fields and modifying validation logic at the same time should not cause the code change conflict.
  2. You make it much harder for testing (static variables are evil for testing).
  3. You violate "inversion of control" principle. You will have bad time when you need to replace validation implementation in a flexible way.

What you can probably do is adding custom validation annotation to the model. This validation will be executed by spring bean that implements some spec. This way you don't have above issues but still you can keep validation rule (without implementation details) on the model class.

0
P_M On

No it is not a good to place java static factory method in Spring Model Class to validate fields.

This is a functionality, which have nothing to do with Model class. The purpose of model classes is to map SQL table data (or NoSQL data) to java POJO called Entity. Do not place any functionality there.

Validation process is a functionality, thus it is the best to place it into Service layer within Spring bean like @Service or @Component.

The less efficient method for validation is to use annotations on POJO attributes. Though those POJOs are should not be Entities, but Data Transfer Objects and they have to map incoming request data. I consider this not as good as to place validation in Spring beans because validation with annotations have limited functionality, and makes functional code placed in few places. Some of validation code will be at the DTO annotations and some validation within bean (Service). This is harder to read and maintain, then have everything in spring Service bean.