Tuesday, June 22, 2004

The C++ Source

The C++ Source is a new, online C++ journal. More is better (usually).

A page about call/cc

An excellent page on call/cc. If I spent all my time reading about Java I'd quit programming and go back to writing classical music.

Monday, June 21, 2004

Audit history with Hibernate

Christian Bauer at Hibernate posts a very interesting technique for object auditing with Hiberate in combination with database triggers. How useful is this?

Thursday, June 17, 2004

Interruptible queries with Java

ONJava.com has a nice article with clean examples of several techniques, Interruptible Database Queries. The clean code includes:

public synchronized ResultSet executeQuery(Statement statement, String query) throws SQLException, InterruptedException { // Set query parameters synchronized (params) { params.statement = statement; params.query = query; params.pending = true; params.notify(); } synchronized (results) { try { // Wait for the query to complete while (!results.serviced) results.wait(); if (results.exception != null) throw results.exception; } catch (InterruptedException e) { cancel(); throw e; } finally { results.serviced = false; } return results.rs; } }

Read the whole article for the worker thread, cancel() and how to put it all together.

Tuesday, June 15, 2004

APIs

Norman Walsh has an intelligent, interesting post on APIs (in spite of the lame title).

Tuesday, June 08, 2004

Cellular automata and music from IBM

Rule 30 after 100 steps

Big Blue is so much cooler now than when I was a kid. For starters, there's the whole Linux shop a few miles from me here in Austin. And there's stuff like this, Cellular automata and music, a fascinating article featuring the Automatous Monk.

And see the beautiful presentation, Things Computer Science Tells Us About Philosophy. Too bad the darn thing is some sort of PowerPoint presentation!

Friday, June 04, 2004

First-class threads in C++

A library package to provice threads in C++ as first-class objects. From the introduction:

The main goal of RT++ however is to provide a programming interface which is considerably higher-level than that of comparable packages. RT++ considers threads as an abstract datatype with a functional interface i.e. threads communicate only via arguments (which are provided when the thread is defined) and results (which are delivered when the thread has terminated). Threads can be used like objects of any other type i.e. they can be stored in data structures, passed as thread arguments, and returned as thread results. Functional programming languages are called higher-order if they treat functions as first-order objects; we call RT++ higher-order because it treats threads in this way.

And:

RT++ provides a thread/memory management system where programmers need not care about these low-level issues. Thread resources are implicitly allocated as late as possible and implicitly freed as early as possible regardless whether or how often the thread result is retrieved. Threads are subject to garbage collection and automatically reclaimed when not referenced any more. RT++ also provides type constructors for arrays, lists, and general pointer structures whose objects can be passed by reference among threads and that are subject to automatic garbage collection. A high-level notion of non-determinism is supported via thread bags which retrieve their result in the order in which they become available and thus allow to write more abstract (and sometimes more efficient) parallel programs.

This is one reason I prefer C++ to Java for some of my programming — choice. Try replacing java.lang.Thread.

See your garbage, smell your garbage

Moazam Raja points out an interesting tool for watching garbage collection in a running program in his post, Visualizing Garbage Collection. What a pretty picture:

Tuesday, June 01, 2004

Excellent C++ refresher

Once, Weakly is an excellent C++ refresher blog by Stephen Dewhurst. The only minus is that the posts are PDF files! Still, it is worth the nuisance.

More on delegation

Of course the word I was searching for yesterday was delegation. But there are three flavors of implementation inheritance given:

public interface Bob { void dodeedo(); }
Your basic class inheritance
public class Fred extends BobImpl { }
Typical delegation
public class Fred implements Bob { private Bob bob = new BobImpl(); public void dobeedo() { bob.dobeedo(); } }
Returning the interface
public class Fred { private Bob bob = new BobImpl(); public Bob bob() { return bob; } }

Only in C++ is the first very flexible by using a template parameter to vary the implementing base class. Most code I see does the second, but this falls down when you provide several interfaces, especially when they are poorly designed to fit together such as List and Map. The third is the most flexible and resembles interface discovery. One could code it that way:

public class Fred { private Bob bob = new BobImpl(); public Object discover(Class itf) { if (itf.isAssignableFrom(Bob.class)) return bob; else return null; // alternatively throw something like ClassCastException } }

But that is way overkill most of the time.

Monday, May 31, 2004

Faking implementation inheritance in Java

I am a lazy programmer, and generate far too many typos. What to do when I want my objects to provide more than one interface and share the implementation amongst themselves? I could write a slew of forwarding methods, but that's sloppy and ugly and blows up the classes. I need mixins but Java doesn't have mixins. (However see here and here.) In C++ I could use implementation inheritance in the standard fashion. But what about Java?

The best I have is forwarding methods:

public interface Interface1 { void dobeedo(); } public class Bob implements Interface1 { private Interface1 mixin1; public Bob(Interface1 mixin1) { this.mixin1 = mixin1; } public void dobeedo() { mixin1.dobeedo(); } }

Sure it works, but do you really want to do this for several large interfaces? Poor Bob gets rather cluttered rather quickly.

(NB — What pattern is this? I can't quite put my finger on it. I don't mean the dependency injection, but the forwarding.)

Sunday, May 30, 2004

Closures to the rescue

Simon Willison makes excellent use of closures in JavaScript to insert code for page load without interfering with other scripts trying to do the same thing:

function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { oldonload(); func(); } } } addLoadEvent(nameOfSomeFunctionToRunOnPageLoad); addLoadEvent(function() { /* more code to run on page load */ });

This is very excellent.

Thursday, May 20, 2004

A beautiful language-theoretic post

Maneability has a beautiful post on recombinant computing (yet another buzzwordy phrase) with a good grounding in the classics. The paper reference gets good style points. Enjoy as pleasure reading.

Monday, May 17, 2004

Clever use of Package

This is a class I wish I'd known about earlier: java.lang.Package. Euxx points out that is has the information you need to describe software's version: title, vendor and version for both software specification and the particular implementation. Yummy.

Wednesday, May 12, 2004

Propagating web exceptions to the test environment

Rather than use in-container testing such as Cactus, our project elected to run the tests separately and communicate with the web using httpunit and jwebunit. For the most part this has worked well but one lingering issue was that exceptions thrown in the container are hidden from the tests, and only show up as the exception handling page (our "red screen").

But, that is different now. We had passed the web session back and forth (a clever trick from Andrew McCormick using a helper servlet) using standard object serialization, but flattened it to a string on the trip back because of serial id mismatches. Then last night I realized that I could use XML serialization from the JDK (XMLEncoder) to serialize the session without worrying about mismatch issues. Once this worked, it was a small step to see to serialize web exceptions and rethrow them in unit tests. A rather neat solution, I think.

Saturday, May 01, 2004

Very excellent NKS lecture

Cluey (if that's his real name, Danil) pointed me to to Wolfram's excellent lecture, A New Kind of Science and the Future of Mathematics. Did you buy his book? I did. Wow, is it heavy. It's one of the few books I have to read in pieces — all in one go and I wind up skimming too much. And the pretty pictures... oh so many pretty pictures. Here's just one, but is it a doosie:

To be 20 again, and a new kind of programmer.

Tuesday, April 27, 2004

Personal best practises

Joe Walnes has a very interesting diagram of his personal best practises:

I wish I had the time to draw things like this. ;-)

UPDATE: I mistyped Joe's name for some reason. Sorry about that!

Wednesday, April 21, 2004

Brick Science

American Digest points out an amusing essay on the crapulence of some neer-do-well coders. Sadly, I encounter these people all the time.

I was fortunate to never have completed a course in Computer Science while at Rice. On the other hand, I was also very unfortunate as Rice has a truly fine department and I would have loved the chance to study programming languages or computer security from true experts. But I was fortunate as I learned how to write programs the old-fashioned way: by studying the code of masters and reading the right books. I had many friends who were excellent programmers, and they put me on the right course with things like the dragon book for compilers, Knuth for algorighms, or the ARM for C++. (No kidding — I learned C++ from the ARM and couldn't figure out why the compilers I tried out didn't seem to implement quite the same language as what I read. It was very eye-opening about what was right v. what was right now.) I learned Linux from the sources and studied good operating system programming from Lions. They both taught me how disgusting and unneccessary most software bloat is, and how a simple implementation is a thing of beauty.

Of late I've learned Java and its companions and become steeped in its culture, and discovered that JUnit is the best of the lot. I'll be happy to return to greener pastures, but for now I'll be satisfied simple with greenbacks for my troubles. I also learned that bird in hand isn't to be sneezed at; I can mix metaphors as well as languages.

Cool AspectJ trick

A nice trick for magically transforming new Fred() into something else from Brian McCallilster. In C++ I would provide a custom new operator, but AspectJ offers another interesting option. Too bad there are no destructors in Java.

Tuesday, April 20, 2004

The request, the session and the form

Struts sucks. Just kidding. Actually, struts really sucks. But it's better than nothing, and it's available everywhere, so like Microsoft Windows, it's the default bolt-on for J2EE webapps in spite of its short comings. And unlike Windows, it is open and free.

Complaints aside, I've been trying out three ways of passing data from an action to the corresponding controller:

Use the request
This is very sensible, but was not the initial approach in my current project. In the action stash the data as an attribute on the request, and fetch it back out in the controller. To ensure type safety, use wrapper methods and manifest constants (e.g., setFooId(Long) to set the FOO_ID attribute).
Use the session
This is similar to using the request, and was the initial approach in my current project, but leaves garbage littered about and occassionally tricks code into using an old value from a previous request. Avoid. I'm working on moving session-based code to request-based code as I encounter it.
Use the form
This is the most interesting choice. On the surface, the controller has no form to use, only the action has one. But the form is stored as an attribute in the request, and you can fetch it back out if only you know the key for it. Struts uses the name field of the form bean from struts-config.xml as the attribute name. This is nice if you know the name, but fragile if you ever change it. Better would be to take your action mapping, and use that to get at the form bean name. If this works, this would be the best choice of all.

Ah, but just how does one get at the action mapping from inside a controller? That is the question I am presently working on. One way is to use the request processor to give you the action mapping, but I don't know how to get the request processor. More research awaits.

Friday, April 16, 2004

tearDown()

What's the right way to use tearDown() in JUnit tests? I spent an afternoon fixing all the places in our codebase where programmer's had forgotten to call super.setUp() and super.tearDown(), respectively, in their own setUp() and tearDown(). To prevent this in the future, I changed BaseTestCase, our in-house extension of JUnit's TestCase, to catch this in the future when running tests: setUp() and tearDown() in BaseTestCase set flags when run, and I overrode runBare() to check for these flags. Voila!

But Paul Holser, a fellow ThoughtWorker on the project, pointed out that tearDown() should also be recoded. Usually everyone writes:

    protected void tearDown() throws Exception {
        // do your tear down here
        super.tearDown();
    }

But Paul suggests instead:

    protected void tearDown() throws Exception {
        try {
            // do your tear down here
        } finally {
            super.tearDown();
        }
    }

I think Paul is correct, but that means I need to go back and fix up some 50 spots and delay working on functionality. Is it worth the extra work?

Monday, April 12, 2004

AspectJ and IoC

Brian McCallister asks an intersting question:

Speaking of AOP -- a problem we have not found a good solution for is using an IoC container with AspectJ. You have no control over how aspects are instantiated at runtime, so you cannot exactly obtain them from a container.

The best we have come up with so far is to provide a static service lookup component that can provide the container to the aspect via a lookup. Yuck, completely breaks the point of the container. Static lookup to obtain a container and then use it to lookup components... far from ideal.

In cases where we've used proxy based AOP the container isn't a problem, but I find myself, and others at the company I work for, leaning more and more towards AspectJ from proxy based options.

Anyone have any ideas?

I wonder if any of my fellow ThoughtWorkers involved in these technologies have a solution?

Related to these, is a great new book I just got, Generative Programming by Czarnecki and Eisenecker. I especially appreciate the illustration of how flexible and forward-looking is C++ which this tome presents. And using Smalltalk to discuss metaobject protocols is very slick also. Too bad there isn't much Lisp. :-)

Monday, April 05, 2004

The Linux desktop

Merrick Schincariol has some excellent thoughts on the Linux desktop. And he should checkout KDE3. :-)