Reputation: 19544
What would be the correct (and best) way to code in limits as to what values a property can get?
For example, suppose I have the following simple class:
Public Class MyClass
Public Property MyDate As Date
Now, suppose MyDate
gets set at run-time, but can't take any values less than a year ago.
Is it correct to throw an exception in the MyDate's setter and then program this in my main module in a Try...Catch
fashion and then alert the user if the value is bad or is there a better way to do this?
I'm sure this is a stupidly simple question, but I just want to make sure I'm doing this according to best programming practices.
Upvotes: 2
Views: 122
Reputation: 3133
While throwing an exception is a valid option, I recommend against it. The reason is that when a programmer sets a property he/she expects very little to happen other than the value being set. In this case I'd recommend using a set function instead of a property or having the value passed as part of the constructor (where programmers expect validation logic of this sort to happen).
Upvotes: 2
Reputation: 10390
Check this article out. It gives an overview of Validators in the System.ComponentModel.DataAnnotations namespace. They are attributes for your model that support validation.
http://stephenwalther.com/archive/2008/09/10/asp-net-mvc-tip-43-use-data-annotation-validators.aspx
ASP.NET MVC supports surfacing those validations on forms using JS, but in other applications types you can read the attributes from the model itself and enforce the validations.
Upvotes: 0
Reputation: 125630
Yes, throwing and exception is a good idea. ArgumentOutOfRangeException seems to be the best in that situation. Following the MSDN:
The exception that is thrown when the value of an argument is outside the allowable range of values as defined by the invoked method.
Upvotes: 5