Argument validation or Contract by contract in java (GWT). When to start?

I play GWT. I'm looking for validation of basic arguments. I do not require invariants or guaranteed results. I am interested in the best practices in this area.

For example, in C # I use one of the following options:

  • if (arg1 != null) throw new ArgumentNulException....; // Official for public API;

  • Args.NotNull(arg1); // Home grown.

  • Contracts.Requires(arg1 != null); // Internal contract validation.

What's the best place for me?

Good thing I found now.

+1


a source to share


3 answers


I usually do this myself, following the Effective Java guidelines from 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 would highly recommend getting a copy of Effective Java if you don't already have one.

+2


a source


According to the wikipedia page of the Design by Contract page , the 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 Spring framework or Modern Jass, Custos using AspectJ, JavaDbC using AspectJ, JavaTESK using Java extensions.

Reading on one of these is probably a good idea.

I don't have personal experience with any of these, but the Pragmatic Programmer says good things about the original iContract so that it might be a good place to start.



You can always try doing it yourself using the built-in Javas assertions:

assert Expression1;


or
assert Expression1 : Expression2 ;

Where Expression 1 results in a Boolean expression and Expression2 is the value of your testing (optional). Try it.

0


a source


If you are just looking for argument validation, the best exception validation is the best solution.

Exception provides you with a better handling solution than simple assertions.

In this scenario, the Design-by-Contract solution was completely overdone.

0


a source







All Articles