Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About software design: Where I must check parameters?

Imagine I have an application that request to the user a name, a category list. When user click on save button, application will save name and category to a database.

I have a layer that get name and category from UI. This layer check if there is a name (a string with length > 0). If this is correct, it will pass name a category to another layer. Note: category is a radiobutton list where one item is always selected.

On this second layer, application will select a suitable class to save name, depending on category.

On last layer, a class will save this name on a database. On this class I will check if name is empty or not.

My question is: where is the right place to check method's input parameters? on every layer? Maybe, I'm going to use these layers on others developments.

Is my example correct? Maybe, I can left validation on database layer and raise an exception to UI layer.

like image 643
VansFannel Avatar asked Feb 27 '11 15:02

VansFannel


2 Answers

In general, in terms of the larger question about validating input that is ultimately persisted, it is best to:

  • Convert the input parameters to a fully encapsulated business object as soon as possible after you receive it.

  • Validate early and fail fast then to wait until you get to a lower layer -- waste of resources, waste of time, possibly more complex (more things to roll back).

  • Validate the business logic once and make that part of your object instantiation process. (but note that validation of view logic and persistence logic may need to be done at the other layers and is separate from business logic)

  • Model how your object is persisted using an ORM (e.g., Hibernate) so that you could work purely at the object level in memory and leave persistence as an implementation detail. Focus the business logic at the object layer.

And in terms of method validation itself, I agree with Oded -- at every layer, and it should be done immediate upon method entry. Again, this is part of the fail fast methodology. But, as I noted above, this doesn't mean you validate business logic at every method (or every layer). I'm just referring to the basic practice of validating inputs (either by assertions or explicit checks and exceptions thrown).

like image 124
kvista Avatar answered Sep 23 '22 00:09

kvista


where is the right place to check method's input parameters? on every layer?

Yes, on every layer. This is called defense in depth.

There are different reasons to do so on each layer:

  • UI/Client code: keep things responsive and avoid roundtrips when data is invalid
  • Business layer: Ensure business rules are kept
  • Data layer: Ensure that valid data is passed through
like image 30
Oded Avatar answered Sep 24 '22 00:09

Oded