Checking validity of a property on set()

S

Sam Martin

hi all,

I'm looking for your opinions on whether to validate and subsequenly throw
exceptions based on the data set() to an object's property or whether you
should do it on say a Save() method.

For example, I have a series of Business Components that have fairly
straight forward properties, and methods to Save().

Should I...

a) Check the validity of each property when it's set and throw an exception
if invalid
or
b) Wait until the Save() method is called for the object, then validate and
throw exceptions where application

My concern is having to put a try block round every bit of code that tries
to set the propery of one of my business objects...

you thoughts....

TIA
Sam Martin
 
J

Jon Skeet [C# MVP]

Sam Martin said:
I'm looking for your opinions on whether to validate and subsequenly throw
exceptions based on the data set() to an object's property or whether you
should do it on say a Save() method.

It depends on the situation, really. Sometimes you may want to go
through many intermediate steps which may have the object in an invalid
state, but leave it in a valid state eventually. In that kind of
situation, validation on save is a good idea.

In other situations, you really want to make sure that an object is
*always* in a valid state. Without knowing more about your situation,
it's hard to say for sure which line you should take, I'm afraid.
My concern is having to put a try block round every bit of code that tries
to set the propery of one of my business objects...

Don't have a try block round each of them - have a try block nice and
high up. You shouldn't need to use try/catch particularly often.
 
N

Nicholas Paldino [.NET/C# MVP]

To add to what Jon said, I also think that this is a situation where
exceptions might be a bad idea. If these are objects that are business (I
use that term loosely) entities, then you might want to have an IsValid
method which will return what is valid and what is not. I don't think that
raising exceptions while setting values in this case is really a good idea,
since you really are returning information that relates to business logic,
not exceptional situations.

However, if this was an operation more like setting the apartment state
of a thread, where there is a direct and immediate effect, then throwing an
exception for something out of range or invalid is justified, IMO.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top