Quick and Dirty DBC

November 5th, 2007

I really like the idea of Design-by-Contract (DBC), but when I tried to use it in my own code, I found a few problems. It wasn’t that DBC was particularly flawed, it was just that I usually program in Java and it isn’t part of the language as it is in Eiffel. This meant that I had to use some extra external tools to enforce the “contracts” I had written into my Javadoc. This turned out to be a bigger pain than I had anticipated. Things may be better now, but I discovered that either the tools I wanted to use were not actively being maintained or were just hard to use. They also added an extra “instrumentation” processing step to the normal edit/compile/run cycle that became something more to manage. I think, today, if I used AspectJ, I could probably make things run more transparently with less management on my part, but it wasn’t around with I came up with the following solution.

What I thought was the most useful and powerful feature of DBC was the “class invariant”. This was a check that the contents of a class instance were “correct”. Basically, it is a kind of “self test” on the state of the data structures in a running program. Given the lack of general knowledge and discussion of DBC, at least that I’ve observed, this little “gem” of an idea seems to have gone relatively unnoticed. As programmers, we generally don’t have a clue about the state of our running code until we notice something that isn’t quite right (a bug). Then we fire up the debugger and manually take the code out for a spin. With the class invariant we instrument our code such that we can ask the question “Is everything ok?” and have the code itself look for problems.

My solution is to dump the overhead of external tools and instead simply implement the DBC “class invariant” as a method within the class itself. This has the advantage of having no external dependencies and of making its invocation be completely under my control. To aid my efforts, I created a simple interface called SanityChecker that contains a single method sane() that returns true if the class instance is “sane” (i.e., validates the class invariant contract) or false if it is “insane” (i.e., a bug has been detected).

public interface SanityChecker {

boolean sane();

}

The trick to its usefulness is to implement it such that it throws an assertion exception if it detects that something is wrong. Here’s an example:

void sane() {

boolean retValue = super.sane();

// The length of the jobs queue should be less than ten

retValue = retValue && (jobs.length() < 10);

assert(retValue);

return retValue;

} // sane

Basically, this makes sure the super-class thinks it is “sane”, and then asserts its own sanity.

The idiom retValue = retValue && <boolean test> followed by an assertion of the value of retValue is a typical pattern. If followed, then once a problem is detected, an assertion will be thrown, or the rest of the tests will be skipped and the value of false returned. By having sane() return a value rather than simply relying upon the assert keyword sanity testing can occur even if assertions are not enabled.

The sane() method should be called when the instance is expected to be “stable” so the consistency checks should complete with no problems (if all is well). Typically, I find I use it like this:

main() {

// Do my big processing loop

while(true) {

assert topDataStructure.sane();

// Do the rest of the work here

} //while

} // main

The assert statement causes the state of the class instance referenced by topDataStructure to be validated before my code makes any changes to it. I implement the sane() method such that the class also asserts the sanity of any other classes it references (that implement the SanityChecker interface). They in turn, do the same. This causes the validation process to ripple throughout the program’s class instances (be careful to avoid cycles) and ensures that everything is as expected before the next iteration of the main processing loop gets its chance to muck things up. As a bonus, if a problem is detected, it is usually pretty easy to figure out which iteration of the loop is the culprit, this makes debugging much easier.

The net effect, for me at least, is that my code either runs, basically “bug free”, or it throws an exception and stops. And, if it does stop, the exception pinpoints the problem for me with high precision. Also, if I disable assertion checking (i.e., no “-ea” flag) then none of this checking is performed and the system runs without any baggage. The solution is simple, flexible, doesn’t require external tools and is extremely powerful; I’m happy.

Taking this idea further, one could imagine a simple extension to Java in which the class Object would include an additional method called sane(), like it does with toString(). As described above, it would return true by default and any classes that wanted to, could override it. It would be “simple” to trigger a debugger to run a “sanity check” and have the contents of the heap be validated automatically. This would be a lot simpler and more accurate than manually digging through with the debugger to “eyeball” class instances and make sure they look “ok”.

Go “First-person shooter” with the Eclipse debugger

October 17th, 2007

One of the things I learned early on in my career was just how powerful a force consumer demand was as a driver for technological innovation. Conventional “wisdom” tends to see the development of new technology as the driver for new consumer products, things like CD players, advanced computer graphics for PC’s, high-capacity storage devices, etc., but the reality is the exact opposite. Basically, if it wasn’t for a bunch of kids playing video games, we’d all still be using punch cards. I could go on about this, but my real purpose is to motivate people to examine the extremely innovative technology being developed for consumers and take inspiration from it.

Here’s an example. I spend a lot of time in front of Eclipse and really love it as a development environment. However, there is one thing that bugs me, I hate interacting with the debugger. Now, don’t get me wrong, I really like the debugger, it truly is my “friend”, I just hate pushing the “F” keys or using the mouse to click on tiny icons to make it step through a program. It just isn’t as fluid as I would like it to be.

One day while prowling Frys, I discovered the “NostromoTM SpeedPad n50″ and then about a year later (not at Frys) I discovered its “big brother” the “NostromoTM SpeedPad n52″, which I see is being updated as the “NostromoTM SpeedPad n52te”. These are “keyboard accelerators” designed for”first shooter” role playing games.

n52

Basically, these devices are small USB keyboards that combine a number of standard keyboard keys (10 for the n50, 15 for the n52 and n52te) and controls (e.g., a roller wheel) together for quick access by a single (left) hand. Using configuration software, one can assign macros of customized key sequences (with timing delays if desired) to each key or control. The keyboards also have a “shift/shift lock” function that set it into three different modes identified by different colored (Red, Blue, and Green) LEDs on the device. This gives 60 (4×15) different macro assignments for just the keypad alone! Suddenly, Eclipse’s support for accelerator key sequences takes on a whole new importance.

Standing in the aisle at Frys, holding the n50 box in my hand, I realized that I could rev-up my partnership with the Eclipse debugger and go “first-person shooter” against the bugs in my code. I wouldn’t have to hunt around for a little spot on my screen with my mouse to just step the program. I could hammer away at my new “death-to-bugs” keyboard and fly through the code bringing order and correctness to all.

Getting it home, my first challenge was to figure out a good key assignment. I wanted to assign everything I possibly could, but soon realized that the keyboard would be a “paper weight” if I couldn’t remember what was assigned to what. So, I decided on simplicity and consistency at the expense of maximum utilization (i.e., I didn’t assign all the keys). I basically, settled on two main sets of assignments, unshifted for general Eclipse control (the mode I’m usually in) and shifted (Red) for debugging. I did make assignments for the other shift modes (Blue and Green), but use them less frequently.

In “Eclipse mode” (Unshifted), I assigned a mixture of Eclipse and editor controls, but I’m still experimenting with the best assignment. One thing I did correctly was to assign “Run Last Launched” and “Debug Last Launched” to the far left keys on two separate rows. This makes it fast and easy to start whatever I’m working and be ready for the debugger when it pops up. I also assigned “Add break point” to quickly insert a breakpoint. These three assignment are shared with the debugging mode (Red) so that I don’t have to remember which mode I’m in to use them, they always work.

For debugging (Red), I clustered the functions of “resume”, “step to return”, “step into (filtered)”, and “step over” together in that order so that with my fingers resting on the “home keys” my index finger would be sitting on “step over”. This way I could comfortably control most of the code execution I needed without moving my hand or leaving that row. On the row of keys above I added macros for “set break point”, “step into” and “run to line” (in the order).

I’ve played with assignments to the roller wheel, and some of the other keys clustered around the thumb position (to launch missiles more quickly, I guess), but I find them either awkward to use or they lack responsiveness and precision in their control.

To help my memory, I created a “cheat sheet” with the key assignments that I then pasted to some cardboard cut from a cereal box. I have it on my desk near the key pad for reference. I’ve uploaded the configuration file with my macro assignments and the word document for the cheat sheet.

I’ve looked closely at other game peripherals available in the stores to see how I might exploit them for my purposes. I really like some of the sophisticated Joysticks I see, and the Gamepads look like they just have to be useful to a serious programmer. However, I think to really exploit them we’ll need to rethink debugger interfaces, but that’s a subject for another post.

Cheat Sheet
Macro Assignments

Enjoy.

Dan