[Tutor] An example of something extremely difficult to expres s in Java

dman dman@dman.ddts.net
Thu, 11 Apr 2002 14:25:44 -0500


On Thu, Apr 11, 2002 at 09:46:39AM -0400, Blake Winton wrote:
| * Karthik Gurumurthy <karthikg@aztec.soft.net> [020411 04:03]:
| > i tried writing a command interface to encapsulate a method..i mean
| > the way Runnable is...to accomodate a function object. i tried
| > returning an ArrayList.  I did figure out that it is a little
| > complicated.
| 
| I never thought it was that bad...
| interface Command
| {
|     public Response execute( Request request );
| }
| 
| interface Request {}
| interface Response {}
| 
| Then you can make implementors of Request and Response, and stick
| whatever data they want in them, and pass them to your implementors of
| Command.

So you need to make 3 extra classes just for this.  What about passing
"primitive" stuff to the method, or passing multiple arguments?  Now
you need to make even more classes.

| Just remember to cast them in your execute method...

Again, ugh.

Oh, yeah, don't forget the possiblities of throwing exceptions from
that execute method, and then catching them in the client code.
However, some methods don't throw exceptions.  Even more classes to
handle all the different cases.


It is doable, but not trivial.  I did it once for a test harness.  I
first wrote it in python (which ran in jython), then rewrote it in
java.  Unfortunately I don't have access to that code right now so
I'll give you an overview in prose :

    In the classes being tested, there were several methods with the
    same interface -- they were boolean "get/set" pairs.  The process
    of testing them was straightforward, so I made a method in my test
    super-class to take a function as the argument and test it.  Then
    I was able to iterate over all the methods in the class being
    tested and call the test function.  In python the code was really
    compact and slick.  When converting it to java I had to make 2 new
    classes just to encapsulate the idea of the method.  Their were 2
    classes because the arguments and retvals were reversed in the get
    vs. the set methods.  Then I had to create a subclass of each of
    those classes for each method to be tested.  I couldn't easily
    iterate over them because creating a sequence in java take more
    boilerplate code than in python.  What was trivial and took only a
    few lines in python took several files in java and was hard to
    follow.  C is about just as bad as java for dynamic stuff like
    that.

-D

-- 

If we claim to be without sin, we deceive ourselves and the truth is not
in us.
        I John 1:8