views:

277

answers:

3

I am playing GWT. I am looking for basic argument checking. I do not require invariants or result ensures. What I am interested about it best practises on the topic.

For example, in c# I use one of this options:

  1. if (arg1 != null) throw new ArgumentNulException....; // Official for public API;
  2. Args.NotNull(arg1); // Home grown.
  3. Contracts.Requires(arg1 != null); // Internal contract validation.

What is the best place for me to start?

Ok, what I found for now.

  1. Validate method arguments
  2. Programming With Assertions
A: 

According to the wikipedia page of Design by Contract, popular tools for this methodology with Java are:

iContract2, Contract4J, jContractor, Jcontract, C4J, CodePro Analytix, STclass, Jass preprocessor, OVal with AspectJ, Java Modeling Language (JML), SpringContracts for the Spring framework, or Modern Jass, Custos using AspectJ,JavaDbC using AspectJ, JavaTESK using extension of Java.

Reading up on one of those is probably a good idea.

I have no personal experience of any of them but Pragmatic Programmer says good things about the original iContract so that might be a good place to start.

You could always try doing it on your own by using Javas built-in assertions:

assert Expression1;
or
assert Expression1 : Expression2 ;

Where Expression1 results in a boolean and Expression2 is the value your testing (optional). Try it out.

Stefan Thyberg
I have quick look to jContractor and really feel that it too heavy. This is why I have stopped diving with searching and asking expirience others have.
Mike Chaliy
+1  A: 

I typically just do it myself, per the recommendations of Effective Java by Josh Bloch, so:

if (arg == null) throw new NullPointerException("arg cannot be null");

or

if (arg < 0) throw new IllegalArgumentException("arg must be positive");

I'd highly recommend getting a copy of Effective Java if you don't already have it.

Jack Leow
Thank you very much, just ordered Effective Java, what do you think about "assert arg < 0" for internal code?
Mike Chaliy
I don't think I'd be a good person to give you an opinion on that, since I never really got into a habit on using the Java 1.4 assert feature, and never really figured out the best practices there.With that said, I'm sure Effective Java talks about that at some point. :)
Jack Leow
A: 

If you are just looking for arguments checking, then a simple check with exception should be the best solution.

Exception provides you a better solution for catching an processing than simple assertions.

In that scenario Design-by-Contract solutions are definitively overkill.

Chris