"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Bill Butler <qw****@asdf.com> wrote: Let me Splain.
A classic case of needing validation is Dates and times.
Is the month between 1 and 12 (or is it 0 and 11)
Is the day between...
You get the idea.
Now look at the DateTime struct.
None of its properties throw an exception.
All of the validation (exception throwing) is in the constructor.
This goal is not always achievable, but in general, you should think about it.
That's just because none of its properties have setters - DateTime is
immutable. Immutability is great where appropriate, but it's far from
always appropriate.
There are plenty of other places in the framework which *do* validate
in properties and throw exceptions.
<grin>
Hi Jon,
I was well aware of the immutably factor when I posted. I went back and forth with myself about
using that particular example, but decided in favor of it due to all of the issues involved if you
allowed DateTime objects to have their properties set individually.
You are absolutely correct.I was just attempting to point out that sometimes it makes more sense to
Put your validation code in the constructor, or in a method.
If DateTime was an class and not a struct, you could still make a good argument for making it behave
in a similar fashion to the way it does now.
If you set the Day to 31....is that valid??? We don't know until we know what month.
What about 29 FEB ? IS it a leap year
Another thing you see frequently in the framework is properties that *Could* be integer values with
range validation. Instead they are refactored to take an object/struct that validated the range in
it's constructor.
I really don't disagree with you at all.
I am simply saying that you should at least *consider* refactoring if you run into a similar
situation.
I was just arguing in favor of exceptions in properties in another thread a couple of days ago ;^)
I guess I just like looking at both sides of the issue.
Bill