Unit Tests and Runnable Classes in Python, Java, and Perl

Python makes it pretty simple to make both unit tests for every function, and to make class files runnable.  I came to realize that unit tests are the object oriented programers way to make a object oriented program behave like a script: every test is run, one after the other.  To make a Python program runnable, there needs to be something that realizes if the class was called directly, then a "main" function should be called that does two things: parses the command line, and calls whatever routines seem like they should be called.

In Java it is the same story that is rarely mentioned.  If one has a class method called "main", then it will be used if the class is called directly.  One needs a way to parse the command line.  A bit of work with google and a few hours led me to JCommander.  That does exactly the right thing.  The hardest part is getting all the darn libraries one needs to run the program itself from the command line. Fortunately I got barely good enough with gradle and groovy to let gradle put all that crap into one shell program, so the command looks simple:

Grid.java.sh -p 2 3
The grid point is (2, 3).

...and behind the curtain:

% cat Grid.java.sh
 /System/Library/Frameworks/JavaVM.framework/Versions/1.6.0/Home/bin/java
 -Dfile.encoding=MacRoman  -cp
/Users/doug/Dropbox/QProcessing/build/classes/main:/Users/doug/Dropbox/QProcessing/build/resources/main:/Users/doug/.gradle/caches/artifacts-14/filestore/com.beust/jcommander/1.27/jar/58c9cbf0f1fa296f93c712f2cf46de50471920f9/jcommander-1.27.jar
 org.visualphysics.layout.Grid  $@

I am such a Perl programmer, this is the only way for me to believe the Java program really works.

One of the reasons Perl has a long history is that unit tests were always part of its culture.  They are not called unit tests: use Test::More is enough.  Then instead of asserts, there is the method ok().  The test are _smaller_ in Perl than in Python because there are fewer games with objects.

In Perl, one builds the structure for a class by hand.  Call the method "new" if you like, or not, it makes no difference except to mess up communication.  Once you have "rolled your own" class, you realize that all this talk about objects is really a way to take the file.h which has data structures and method prototypes, put that all in one file instead of two, then say all the stuff in this one file, both data and methods, should pay together super nice, and may play with others if allowed (sub or super classed).

It is possible to make Perl modules runnable too.  Then one needs a method called main, which parses the command line and decides which methods to run.

If you are interested in seeing the details, visit here: Comparing code: Python, Java, and Perl


The current code sprint involves making 9 classes and 2 interfaces to figure out 37 numbers my UI needs to put things in the right places.