Vishwanath Krishnamurthi's blog

A blog on Java EE, clean code, open source and TDD

Posts Tagged ‘assertive programming preconditions assert java

Failing Fast / Assertive Programming

leave a comment »

I am not using this term “assertive programming” strictly on the basis of  using “assert” keyword, but a little loosely, to  fail-fast and expose bugs early. It is a great technique for programmers to shorten their debugging-time, but hardly do I ever see any ‘asserts’ in codebase.

Languages like Eiffel contain constructs for preconditions and postconditions and goes a step further in helping to program assertively, but at least we’ve got an “assert” keyword in Java.

Here is a nice usage of assert, I found in a merge-sort implementation.  The merge step merges two sorted halves into one.

For this to work correctly, the two halves must be sorted.

merge(int []a, int aux[], int low, int mid, int high)
assert isSorted(a,low,mid);
assert isSorted(a,mid+1,high);
// rest of the merging code

What better way to document our expectations and to expose the bugs early on ?

There are a couple of choices when it comes to “ways of asserting”

The assert keyword is handy, throws error on failing and could be switched off at production. The other way is to go towards an API (Spring-Assert, GoogleGuavaPreconditions) or a custom-class,that throws an Exception

but regardless of the ways, assertion as such is a great tool, not to be disregarded.

Assertions aren’t the only ways ensure ‘Fail Fast’. For example, when using transaction attributes, you could ensure that a transaction must be present using ‘mandatory’ rather than using a ‘required’ and stay away from a vague transaction attribute like ‘supports’

While working with read-only values, you could use something from the programming language to ensures it. Marking references as, ‘final’, better yet, using Immutable objects, would go towards it.

So, hey ! Go assert !

Good Reads:

Here’s a very good article on “failing fast“.

To assert or not to assert


Written by Vishwanath Krishnamurthi

December 9, 2012 at 11:57 am