Should validation code exist in set methods or in a validate method
I was wondering whether I need to validate data passed to a set method, or whether I should keep all the validation checks in a single method. In other words is it dangerous to set class variables without checking them, providing you do check them before you use them?
Re: Should validation code exist in set methods or in a validate method
Quote:
validate data passed to a set method
That'd be my choice. Then you could throw an invalid data exception at the source of bad data.
Re: Should validation code exist in set methods or in a validate method
I guess it make sense, I've been told any public method should check it's data so I assume it makes sense. I'll have to play with it a bit. Thanks for the reply!
Re: Should validation code exist in set methods or in a validate method
The purist approach to this is to start every method with a precondition to check everything is OK to continue, and finish each method with a postcondition to check everything is OK to return. Some languages (e.g. Eiffel) have this approach built-in. In Java you can do this manually or use AOP (Aspect Oriented Programming), and the checks can range from just ensuring a parameter isn't null, to doing a full inspection of the class state before continuing.
Re: Should validation code exist in set methods or in a validate method
Typically you can check the value in the setter method and if it is invalid throw an IllegalArgumentException or IllegalStateException, depending upon the condition. These thrown exceptions should be well documented for the function so those calling know why these are thrown when they are thrown.
If the code is written for a project which is not expected to be used or visible by other groups, then you could alternatively use assertions during debugging tests.