I have a class Employee. I want to be able to Validate() it before I save it to make sure all the fields have been populated with valid values.
The user of the class may call Validate() before they call Save() or they may call Save() directly and Save() will then call Validate() and probably throw an Exception if validation fails.
Now, my (main) question is this;
If my Validate() function returns a simple bool then how do I tell the user of the class what is wrong, i.e. “Email not filled in”, “ID not unique” etc. For the purposes of this I just want the error strings to pass to the human user, but the principle is the same if I wanted a list of error codes (except that makes the use of a bitmap more logical).
- I could use an Out paramater in my Validate function but I understand this is frowned upon.
- Rather than returning a bool, I could return a string array from my function and just test if it was empty (meaning no errors) – but that seems messy and not right.
- I could create a Struct just to return from this method, including a bool and a string array with error messages, but just seems clunky.
- I could return a bitmap of error codes instead of a bool and look it up, but that seems rather excessive.
- I could create a public property “ValidationErrors” on the object which would hold the errors. However, that would rely on me calling Validate() before reading it or explicitly calling Validate from the Property() which is a bit wasteful.
My specific program is in C# but this looks like a fairly generic “best practice” question and one I am sure I should know the answer to. Any advice gratefully received.
I would probably go for the bitmap-option. Simply
…and in the calling code, simply:
Seems nice and compact to me.