Why consider using Guava-like Libraries for API Contract Conditions Checks

This article represents a perspective on why one should consider using Pre/Post condition checks libraries rather than writing it down time and again in their code.
While doing code reviews, many a times, I have found people using preconditions checks such as “Not Null” in a casual manner rather than based on API contracts requiring pre and post conditions checks. Such checks, at times,  do make code difficult to read, learn or understand. One may want to rather use home-grown or external (proven ones) libraries for doing such checks. Not only does it enhance code readability and learn-ability but also, it does make you aware of contracts you put in the code thereby including only necessary checks and, hence, cleaner code.
Sample Code representing usage of Libraries vis-a-vis Traditional Code Checks
Consider code snippets such as following:
// In traditional manner
if (id == null) {
throw new NullPointerException(“Id can’t be null”);
// Using Preconditions API;
Preconditions.checkNotNull(id, “Id can’t be null”); // Google Guava Preconditions API
Assert.notNull(id, “Id can’t be null”); // Spring framework Assert API
Validate.notNull(id, “Id can’t be null”); // Apache Commons Validate API
Contract.Requires<NullReferenceException>(id != null, “Id can’t be null”); // Code Contracts .NET framework
Java/.NET Libraries for Pre/Post conditions Checks
Above considers some of the popular libraries which are mentioned below:
Top 4 Code Checks for which Pre/Post Conditions Libraries could be used
Following are top 4 (most common ones) traditional checks found across source code. The code usability gets a booster if one makes use of pre/post conditions API:
  1. Check for validation of methods’ arguments.  Throws exception such as IllegalArgumantException or the equivalent upon failure.
  2. Check whether a specific value is not null.  Throws exception such as NullPointerException or the equivalent upon failure.
  3. Check state of the object.  Throws exception such as IllegalStateException or the equivalent upon failure
  4. Check whether the index is a valid element or position index into a list, string, or array with the specified size. An element index may range from 0 inclusive to size exclusive. Throws exception such as IndexOutOfBoundsException or the equivalent upon failure
Ajitesh Kumar

Ajitesh Kumar

Ajitesh is passionate about various different technologies including programming languages such as Java/JEE, Javascript, PHP, .NET, C/C++, mobile programming languages etc and, computing fundamentals such as application security, cloud computing, API, mobile apps, google glass, big data etc.Recently, he has been digging deep into the field of data science and machine learning.

Follow him on Twitter and Google+.
Ajitesh Kumar

Leave A Reply