2
I was thinking about how validation is applied in different scenarios and mainly using layered architecture and I came across some issues that I would like to discuss.
Are there any validations that should be used at the application level and not at the business level? If they exist, then they should not be forced on the entities but on the application layer above.
When we find errors in validation how we should propagate these errors to the upper layers?
1) Create a specific type of Exception (Evalidationexception)? And from that the top layers could create code to intercept and display error messages?
try
customerService.registerCostumer(name, phoneNumber, email);
except
on E:EValidationException do
Self.ShowValidationMessages(E.getErrorMessages());
end;
2) Create a type of Application Context that would be injected into Application Services and serve as a bridge to validation errors?
validator := TValidator.Create;
//in service layer
if validator.isValid(customer) then
FApplicationContext.addMessages(validator.getErrorMessages());
//in presentation layer (a form for example)
if applicatioContext.hasErrorMessages() then
Self.ShowValidationMessages(applicationContext.getErrorMessages());
I’ll point out that I’m developing in Delphi and my project uses a layered architecture like the DDD layers (I’m not using 100% DDD yet, I just use a few ideas). In this case I am calling my validation code in the application services.
In this particular case I showed only the case where I use the application-level validations, but I also have business-level validations. What I meant is that there are validations that only exist at the application level. In one application I restrict the age of the customer to at least 18 years and in others I do not need this restriction. If I force on the domain, I will have to modify the class to use in another application.
– Robson Coutinho
And the other point I was really looking forward to finding the best way to return the validation errors to the upper layers. Because I didn’t want to have to put a return on the service method with validation error messages, it would be meaningless. I will apply the first option even with exceptions then.
– Robson Coutinho
@Robsoncoutinho I understood correctly... maybe I have curled up and not made clear hehehe... In the case of the 18-year restriction, the correct is to validate in the business model as well. As this building in Delphi, it is unlikely that the user will dribble their validation into the application layer, but in the case of a web application, this is a case that should be taken seriously. I don’t know exactly how you built your application, but maybe using the Decorator Pattern is the most appropriate, but it will probably force you to some low-level modifications in the application.
– Vinícius Gobbo A. de Oliveira