Thursday, 7 August 2014

Easy Design-By-Contract for Java and Javascript

Why use Design by Contract?
I like a very cut down form of Design By Contract. I use it to validate the arguments passed to a function. So if an expectation suddenly fails, my code will immediately drop me into the debugger if I am developing, or throw an Error with an actual meaningful message in Production.

I have been frustrated for a while by the number of lines of code (complexity) needed to implement Design By Contract in either Java or JavaScript, or the need to use recompiling frameworks so the output code is modified.

This frustration has finally come of age, and with some help from James Gee, we have almost finished working on ExceptionExtensions for both Java and JavaScript.

There are 2 advantages to using this:
  1. It is designed to read like natural language, so code is much easier to read and write. Parameter validation in java REST interfaces, or function expectations in a JavaScript event handler, both become easy to write, and more importantly 6 months later, I can read it as easily as English, or my colleague can read it tomorrow without needing to ask me WTF?
  2. Debugging an contract expectation failure become simplicity itself. Isolating and identifying the causes of bugs is so much easier if your code simply stops at the point of failure and makes a fully scoped stack available, without the need for complex conditional breakpoints.
I know it sounds simple, but using ExceptionExtensions and Design by Contract has massively improved the readability of my code and revolutionized my ability to isolate and identify the causes of a bugs.

import static com.techmale.exception_extension.ExceptionExtensions;

public void myMethodName(String arg1, int arg2){
    IllegalArgumentException.when(arg1 == null,"arg1 is NULL");

To debug: Simply set a break point in the ExceptionExtensions src code and run your code in debug mode. You will drop into step debugging without needing to set up any complicated conditional debug points.

function myFunc(arg1,arg2,arg3){
    arg1 = arg1 || "defaultValue";
    Exception.when(!!arg2,"Arg2 is mandatory");
    Exception.when(arg2 typeof != "Number","Arg2 must be a Number");
    Exception.when(arg3 != 100,"Arg3 must be a 100, is actually %s", arg3);
    // .. the rest goes here

To debug: Just make sure your console is open, as debugging is automatic out-of-the-box. If you want to turn it off for a production system, just read the instructions on GitHub, or the post below on conditional evaluation.

The Conclusion?
The price: A really simple change to your coding practices.
The prize: A massive win for readability and super easy bug hunting.

Lastly... to download ExceptionExtensions:

ExceptionExtensions for Java
ExceptionExtensions for JavaScript

No comments:

Post a Comment