Often I have to deal with a save method which has to check a few things before saving to the database.
Things I check for, for example, are empty properties, and values which depends on other properties.
I am always struggling on how to implement such a things. The questions I ask myself are:
- Should I use a boolean as a return value for the Save method? And in the client code, check of it is false, show the end-user a messagebox with: “Saving failed”. But the problem is, I can’t show the user why saving is failed. So I don’t like this one very much.
- In my Save methods, should I throw an Exception? So when a check fails, a Exception is thrown?
- Do nothing. When a check fails, just don’t do anything. But I think this is not really a option.
I was wondering, how do you implement this? Is there kind of a pattern?
imho it’s not up to the save method to validate the object. It should be valid when Save is called. It’s therefore OK to throw an exception if the object is not specified correctly.
As for validation, there are built in framework in .NET which is called DataAnnotations. Use it for easier validations in all layers.