DenaliHardtail
DenaliHardtail

Reputation: 28296

Where should data validation occur?

I have a method 'ABC' that does some stuff. The ABC method is called from another method, method XYZ. Where should the data validation of the input values occur?

Should I validate in XYZ before even calling ABC? If it's bad data method ABC won't even be called.

Or, should I validate in ABC?

Or, validate in both locations?

Upvotes: 1

Views: 170

Answers (4)

Vladimir Ivanov
Vladimir Ivanov

Reputation: 43088

Fast failure is good. You should report about bad data as early as you can determine this. So, if you know that data is bad in XYZ, then throw an exception in XYZ. ABC method doesn't have sense, if data is already bad.

Upvotes: 0

JOTN
JOTN

Reputation: 6317

I look a number of considerations:

How important is it the data is correct.

Where is it likely to be wrong.

Where is the most efficient and effective place to check it.

Where is the best to fix it.

Most likely your bad data is going to come from the user interface, and that's also where you can prompt for it to be fixed.

Referential and unique constraints are most effectively handled in the database. The code that changes the database should catch these and pass a useful exception back to the user interface.

Checking multiple times is worth the overhead if correctness is really important and bugs in the code may generate bad data to the back end. I do multiple checks on things like financial data or something that could cause the entire system to malfunction.

Upvotes: 0

Napas
Napas

Reputation: 2801

If it's bad data method ABC won't even be called.

I think you have answer in your question :)

Upvotes: 0

blowdart
blowdart

Reputation: 56490

It depends.

If ABC is only ever called by XYZ then you can validate by XYZ.

If ABC has visibility outside of XYZ (for example it's a public method, or an internal one) then you should validate in ABC.

If it's a critical function (ABC = AtomicBombControl) then validate everywhere you can.

Upvotes: 3

Related Questions