Jump to content

Validating a collection in business layer: best practices

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1
serges123

serges123

    Newbie

  • Members
  • Pip
  • 1 posts
Good day,

First of all, sorry for my English, it is not my mother tongue.

Here is a simplified version of my problem.

I got a web form that construct a RegisterForm object. That RegisterForm object contains a collection of Options.

After that the form as been submitted, I construct a RegisterForm object that contains a collection of Options based on the form fields. Then, I pass that RegisterForm object to my business layer, to insert it into the database

Here is my question: The collection of Options objects in the RegisterForm has to be validated. For example, the user cannot select the Option A and B together, but can select Option A and C. What is the best practice for validating it? Is it by creating a AreOptionsValid() in the RegisterForm object? Is it by wrapping the collection of Options in a TheOptions class and call IsValid on it? Of course, the real system is more complex and I don't wanna validate the collection of Options in the web form, I have to validate it in the business layer.

And if the collection is not valid, what should I return to the web form... A custom exception? A OptionsError object?

So what are your thoughts about that? I am looking for the best practices here.

Thank you very much!

#2
John

John

    Writes binary right handed and hex left handed

  • Moderators
  • 6,321 posts
I do not believe the Business Layer should be responsible for validation. In my framework, I have a class that us used strictly for common validation purposes (valid email address, web address, ect...). I would suggest you create a separate class for your validation thus creating a more decoupled code (you never know when it will be used again).

As for what to do when your collection is not valid, I would simply print out an error. I use exceptions when there could be errors PHP cannot recover from. This provides an elegant way to exit the application. A invalid object can easily be handled by you, without exiting the application.