Brian's Waste of Time

Wed, 24 Nov 2004

The Same Code

Same thing in three languages (one language twice, doing two styles). All technically as very realistic pseudo-code =)

Handle h;
try {
    h = dbi.open();
    h.begin()
    final Collection results = h.query(CHANGED_DESCRIPTIONS);
    for (Iterator i = results.iterator(); i.hasNext();) {
        final Map row = (Map) i.next();
        System.out.println(row.get("name"));
    }
} catch (Exception e) {
    if (h != null && h.isOpen()) {
        if (h.isInTransaction()) {
            h.rollback();
        }
    }
    throw new DBIException("...", e);
} catch (Error e) {
    if (h != null && h.isOpen()) {
        if (h.isInTransaction()) {
            h.rollback();
        }
    }
    throw new DBIError("...", e);
} finally {
    if (h != null) {
        h.close();
    }
}

or

dbi.open(new HandleCallback() {
    public void withHandle(final Handle handle) throws Exception {
        handle.inTransaction(new TransactionCallback() {
            public void inTransaction(final Handle handle) throws Exception {
                handle.query(CHANGED_DESCRIPTIONS, new RowCallback() {
                    public void eachRow(final Handle handle, final Map row) throws Exception {
                        System.out.println(row.get("name"));
                    }
                });
            }
        });
    }
});

or (this one is even more pseudocode'ish)

(invoke dbi 'with-handle (lambda (handle) 
    (invoke handle 'in-transaction (lambda(handle)
        (invoke handle 'each-row (CHANGED_DESCRIPTIONS lambda(row) 
            (print (map-get row 'name))))))))

or

dbi.open do |handle|
    handle.inTransaction do 
        handle.query(CHANGED_DESCRIPTIONS) { |row| puts row['name'] }
    end
end

?

5 writebacks [/src/java] permanent link