Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Validation - where should it occur

Status
Not open for further replies.

calahans

Programmer
Jun 14, 1999
348
IE
I have an application object which takes data from the front end. It validates most fields. This is all fine. Now say that this object uses another utility object to, say, write a datastream to a socket. The utility class takes in certain data from the front end which has been validated initially by the app object.

My question: Should the utility object validate everything it needs before using it, or should it presume that the programmer gives it correct objects i.e. machineName string not empty, valid port number, valid data to write etc?

Its basically, should all object validate EVERYTHING they need to use b4 using or is it the application programmers problem to make sure the objects are correct?

Cal Cal
 
There are several ways to handle this. One is to validate all the parameters and throw a contextual error or exception if they are incorrect.

Another is to consider what would happen if the parameters are incorrect (e.g. you try to substring a null parameter and get a null pointer exception, etc) and declare these exceptions as being thrown if the parameters are incorrect. You then have warned the client programmer--it is up to them to give you good data. The absolute worst thing you could do is ever assume that you will be given correct data. You should always program defensively even if that simply means that you declare exceptions that may be thrown. Realize, however, that many programmers will not code to deal with unchecked exceptions and these may lead to hard to find bugs. For example, if I declare that a method throws a NullPointerException, the client programmer doesn't have to code this in a try-catch block nor rethrow it. The compiler will ignore it.

It really depends on what your audience is. If you are writing extensible classes or libraries, they should simply throw a meaningful exception--leave it to the client programmer (which could very well STILL be you) to handle the exception elsewhere.

Believe me, the more code you see, the easier this becomes. I excitedly waded through alot of 'production' quality code looking for these kinds of hints when I was starting out trying to figure out 'the way' to do it only to discover that there is no 'one way'--everyone has their own bias.

Charles
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top