I decided to start a new sub-series on Validation, since it is a huge and controversial subject, I suspect it will take a post or two, or three.
So, I was chatting with Peter Farrell some time ago:
me: Peter, I have a quick question for you
Peter: Sure, what?
me: Where should input validation go? In the Controller or In the service layer?
Peter: THAT is NOT a quick question.
Those are not Peter's exact words. I do not have the transcript, but that is roughly how the conversation went.
So after learning more, talking to experts, asking questions and trying things out, I have come to the conclusion that Peter was right.
Handling ValidationThere are A LOT of ways to handle user input validation. To name a few:
- In the Controller
- In the service layer
- In the business object itself
- In a separate validator object
Now, I am not saying that any one way is the "right" way. I'm still not even sure which way is right for me. I am going to show you how I do it. I would love to hear feedback on this method. I am going to simplify some things just to keep my posts shorter.
Right now, the way I am handling validation is in the business object. I am not sure if that makes my bean "smart" or not. But it is self-validating, and I think that is kinda smart of it ;).
We have been working on creating Lists in our To-do list application. We have been able to populate a bean and get it persisted to the database, but we have not validated any of the input. In fact, right now, it will allow us to create a list with no name (or with duplicate names) and no priority, and it would let us pass in a non-numeric character into the priority if we intercept the form and alter the field. So this is all bad and can cause us errors and headaches down the line.
So what validation rules do we need?
- The list name cannot be empty
- The list name must be unique
- Priority must not be empty
- Priority must be numeric
- Priority must be 1, 2, or 3
In my next post, we will actually build this functionality, along with some supporting functionality into the bean and a bean decorator.