MayoMan
MayoMan

Reputation: 4917

What is best practice for validating an object before passing it to an ORM helper class to persist it

Say you have an instance of your DB entity class MyClass. You have 3 fields in this entity which are all tagged as "Cannot be null" If you create an object of this class and pass it along to be persisted you DB layer will throw an exception when it tries to persist the object if it does NOT have the 3 fields populated. What is the best practice in this situation. Should the constructor, setter methods in MyClass validate that all fields are correct and if not complain. Or do you allow an invalid object to be created and have the DB layer do the complaining?

Upvotes: 1

Views: 592

Answers (1)

hvgotcodes
hvgotcodes

Reputation: 120178

1) You should prevent the client from submitting an invalid data

2) Even if you do 1, you still need to validate on the server -- people will try wacky things with curl and wget...

3) I would check in the service layer that the incoming data is valid. If it is not, I would return some sort of error code to the client, and not even do the save. For simple cases I would have a validate method on my domain class. For complicated cases, I would create a service method to do the validation, for example, in the case where I need to check the submitted data against data in the DB. There is no 1 right way to do validation that covers all cases.

The problem with doing the save and catching the exception is it can be difficult to distinguish this error from other errors that can occur. Plus, it's easy to test validation code, and that the service does the right thing on validation failure. Plus, validation logic is business rules, and it's always good to be able to easily test your business rules.

Upvotes: 4

Related Questions