0

In my Springboot project I need to perform a validation of the type validFromDate<validToDate. I was wondering whether would it be a good or bad practice to place a validation in the model itself (pros and cons?) or should it be in the controller which feeds the value in model. I have taken reference from this question In MVC should a model handle validation?.

In it the accepted answers favors for the case of date validation in model, but there are answers which contradict as well. So I would like to have clearer view on the topic.

Which clearly provides some insights, but I was looking for this particular scenario. (As a concrete example for the above question).

Thanks very much for any insights!

2

The controller should always handle validation. Because its the only one capable of actually presenting the problem to the user (be that a message, some sort of highlight, etc..).

That being said, always enforce invariants in the core model. I'm not talking about business rules, those should be enforced by business logic. I'm talking about structural rules. These are the invariants like an empty container has no elements.

In your case I cannot see how this rule could be structural. A close by example that is structural would be a DateRange with the invariant DateRange.From <= DateRange.Till because otherwise the from and till swap.

  • Also, an issue that I would like to mention would come while updating the model, say if the toDate from database comes to be 5thApril20XX and we want to update fromDate to 6thApril20XX, It will cause validation Error in setter of FromDate. – Salim Shamim Aug 22 at 8:26
  • For starters your domain model is always transitioned by domain events. In the case of a Date Range, you would not update the individual properties separately. You would update them simultaneously or completely replace the object. eg: daterange.set(from, to); or something.range = new DateRange(from, to); If your persistence framework is dictating how you implement your domain then you have problems. Aside from restricting you, what happens when that framework is no longer supported? Its not like you can easily replace it, which means either a costly rework, or complete replacement. No fun. – Kain0_0 Aug 22 at 23:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.