Question

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
Was it helpful?

Solution

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.

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top