Photo credit: Windell H. Oskay, www.evilmadscientist.com bridell.com
on creative engineering and new media art

How to use min() and max() - and a DIY unit test

November 8th, 2007

So, there I was, coding a little thing in Processing. I was just testing out this thing where the user could drag control points around in a window, and I just needed to make sure she didn’t drag them out of bounds. What I want to achieve is this: I have a value that comes from somewhere - an x coordinate from user interaction, say - and I want to limit that value so it’s not smaller than the left edge and not bigger than the right one. I’ve done this lots of times before but I always have to think about which way is which. Well, here it is, once and for all.

The tricky part is that in this case you want to use min to check for the maximum value, and max to check for the minimum value. Very backwards.

int limit(int minValue, int value, int maxValue){
return max(minValue, min(value, maxValue));
}

The inner min(value, maxValue) takes the value of whichever is smaller - the value or the max value - so that’s checking that the value is not too big. The outer max checks the lower limit.

If you want to have a look at the actual code I wrote (complete with comments and error checking) there’s an attached file with the original Processing (in this case, pure Java) code.

Since I was doing this in Processing (and for some reason not from Eclipse but from the rather crappy Processing IDE) there’s not really any unit testing framework around - so I did that as well. The idea behind unit testing is that if you know how your method is supposed to work, it’s a good idea to verify that it does indeed do what you think it does. This seems like a pretty obvious idea, but people were coding along happily for years (and many still are) before thinking of actually testing the parts before testing the whole. The simplest do-it-yourself unit testing takes about three lines of code to set up in whatever language you’re using. The test method goes something like this:

void assertEqual(int expected, int actual, String message){
if (actual != expected){
System.err.println("Assertion failed (" + message + "): expected " + expected + ", got " + actual);
}
}

This works even better in non-typed languages where you don’t have to make one version for ints and one for floats and so on. If you’re doing more serious development you should of course take the time to dig up a serious unit testing framework for you language (such as JUnit for Java).

The original processing code is here: Processing code - Limit utility

Update: DOH! I just found out that somebody already thought of this. There’s a Processing method contrain(value, min, max) that does the same thing!