Life Codecs @

Ruminations. Reflections. Refractions. Code.

Mar 11, 2009 - general gripe


Disclaimer: Firstly, this is partly tongue-in-cheek (but only partly), and secondly I don’t think all consultancies are like this, there are definitely better companies out there, I’ve certainly worked in one. On to the content…

Michael posted a link to a news on Superpartners tech revamp on Facebook, which is expected to cost 70 million dollars (!). The news speaks of a company called CSC who’s secured a chunk of the SI work. Anyway, this post has nothing to do with CSC (so please keep your lawyers on a leash) – but it brought us to the topic of consultancies (ya know, mind associations, boredom, that kinda thing). Since Mike seg-faulted reading my long comment (how rude), I may just delete it – but I rather liked my comment, so thought I’d reproduce it here before dust turns to dust.. or comment to.. bit dust.. whatever.

The background conversation here is that moving jobs from one bad consultancy to another may just entail the same thing, my comment:


Scary ain’t it.

In terms of code it’s like someone defined a few marker interfaces: ICrap and ILateHours. The base class AbstractConsultancy implemented them, and added more of its own inner painful classes (e.g. AnalysisParalysis and AllPainNoGainStakeholderMeeting).

Then the various consultancy startup entrepreneurs created their own Consultancy classes extending AbstractConsultancy (for much of the work was done there), but also implementing IPersonalisedCrapAndLateHours to add their own distinct flavour. Oh then obviously they instantiated the Consultancy.

I’d link to a UML class diagram, but this sore throat exacerbates my inertia. Please use your imagination skills, guys and gals.

Yours truly in sarcasm,



Ah, my space, my comment.

— Kamal

Feb 24, 2009 - general

Theme Redesign!

I got sick of the fixed-width default theme, so I took the WordPress classic theme (which was variable width, what an improvement!), and replaced it with my colors! Whew! Thank God for CSS. I then proceeded to apply the same colors (not yet uploaded) to the main site! Enjoy, funnily enough, the dark colors are a lot easier on the eyes when writing code.

— Kamal

Feb 24, 2009 - software dev

Delegates in Java – Introducing delegates4j


For a while now I’ve wanted a delegate-like (C# delegates – think of them as basically type-safe function pointers) feature to use in Java (and don’t mention closures or dynamic languages please, I know it will make my whole post obsolete :P), and I tried several attempts to simulate them, but didn’t quite get it right. I learnt about funky uses of the proxy pattern from my ex-team lead (very neat person, hey Steve!) in various projects. Then Java 5 came along…

No wait, before that, one day as I was messing around with cglib (I call it an AOP enabling tech through proxies – go proxy!), I noticed that they provided a dynamic delegate creator, in the cglib sources, see: net.sf.cglib.reflect.MethodDelegate – quoting from Apache Avalon‘s Delegate class, a delegate is defined as an interface with a single method. Note that Avalon has been marked as a closed project – but I don’t think it had anything to do with the delegate definition, phew.

delegates4j is Born:

Anyway, while that was neat (and backward compatible with pre-Java 5 stuff, hmph), it required a method name as a string, not a very big deal, but not quite what I wanted either, I wanted something a little more declarative, and something perhaps simpler, and a little more typesafe; and not requiring an external class enhancer (yes, maybe I just wanted to reinvent the wheel and not use cglib to do it). Annotations to the rescue! So! Keeping in mind that a delegate is an interface with a single method, let’s look at what I have (might want to paste this into an editor if it’s too annoying to read):

package net.namingcrisis.delegates4j.core;

import static net.namingcrisis.delegates4j.core.DelegateFactory.cdg;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class DelegateFactoryBasicTest {
    // Basic case, also a sampling of how the API is used.

    public void setUp() throws Exception {

    // Delegate type interface, only a single method.
    // Think of it as a function pointer in disguise
    // (C# of course supports delegates natively)
    private static interface IStringProcessor {
        String process(String s);

    // A strategy class with different string processing routines
    // Does NOT extend StringProcessor, nor do the method names have to match,
    // this is the point.
    private static class GString { /*
                                     * It's a joke here, but GTK actually has a
                                     * gstring type

        private static final String UPPER_CASE = "upper case";
        private static final String PRAYER = "prayers";
        private static final String EMPTY = "nada";

        @Implements(clazz = IStringProcessor.class, mode = UPPER_CASE)
        public String toUpperCase(String s) {
            return s.toUpperCase();

        @Implements(clazz = IStringProcessor.class, mode = PRAYER)
        public String toPrayer(String s) {
            return "Hallelujah! " + s;

        @Implements(clazz = IStringProcessor.class, mode = EMPTY)
        public String toEmptyString(String s) {
            return ""; // :P

    // A test client of StringProcessor, assume it to be a simple visitor
    // Returns a new array of processed strings
    public String[] printStrings(final String[] strings, IStringProcessor proc) {
        final String[] res = new String[strings.length];
        for (int i = ; i < strings.length; i++)
            res[i] = proc.process(strings[i]);
        return res;

    public void testCreateDelegate() {
        final String[] strings = new String[] { "you", "and", "i" };
        final GString gs = new GString();

        // Dynamically create delegate instance, cdg is a static import
        // meaning "create delegate", deliberately keeping the name
        // short and unintrusive.
        // cdg(interfacetype, mode, implementationInstance)
        final IStringProcessor upperCaseProcessor = cdg(IStringProcessor.class,
                GString.UPPER_CASE, gs);
        String[] res = printStrings(strings, upperCaseProcessor);
        Assert.assertTrue(res.length == strings.length);
        for (int i = ; i < strings.length; i++)
            Assert.assertEquals(res[i], gs.toUpperCase(strings[i]));

        final IStringProcessor prayerProcessor = cdg(IStringProcessor.class,
                GString.PRAYER, gs);
        res = printStrings(strings, prayerProcessor);
        Assert.assertTrue(res.length == strings.length);
        for (int i = ; i < strings.length; i++)
            Assert.assertEquals(res[i], gs.toPrayer(strings[i]));

        final IStringProcessor emptyProcessor = cdg(IStringProcessor.class,
                GString.EMPTY, gs);
        res = printStrings(strings, emptyProcessor);
        Assert.assertTrue(res.length == strings.length);
        for (int i = ; i < strings.length; i++)
            Assert.assertEquals(res[i], gs.toEmptyString(strings[i]));

A couple of things (noted in comments):

  • The implementation class did NOT implement the delegate’s interface (or the delegate rather, “delegate interface” is redundant going by the above definition!), it merely provided compatible methods, whose names did not have to match.
  • The use of mode, is of course a string, and perhaps not very typesafe either, but it is exclusively there to support the scenario where multiple similar methods implement different behaviour, allowing you to have several strategies in a class, very handy for quick things. Probably not a good idea for larger reusable strategies. If you didn’t have it, just set it as an empty string (at the moment it’ll NPE-out otherwise :P)
  • This test doesn’t illustrate it, but to keep things single and fast (method resolution is done at runtime after all), it matches declared methods only, nothing inherited is usable – an interface that extends another but has no method will error out as a delegate type, a class with a superclass annotated method overridden but not annotated, also errors out. (The class bit is redundant, annotations are not inherited anyway, so).
  • Finally – also not illustrated by this test, delegates4j supports Java 5 covariance, where the return type of the implementor can be narrower than that of the delegate type.

Hopefully, it is simple enough to use – my initial attempts had multiple steps, but they tried to do more too. An improvement to this is possibly somehow caching resolved methods for reuse keyed by the annotation detail for example, in practice I don’t know if this is worth it yet.

The project is available as Maven downloadable jar (licensed under Apache License v2.0) in my repository, including sources, and tests to better illustrate usage/limitations (and of course, test that it works!). Set the dependency as follows: groupId = net.namingcrisis, artifactId = delegates4j, version = 0.5.

For the curious, under the hood, the only real magic is the use of the JDK Dynamic Proxy to implement the delegate and pass on the request to the supplied instance, and reflection for method resolution – the source is there anyway :-). If you do use it, hate it, try it out, etc. drop me a line anyway :-).

— Kamal

Feb 23, 2009 - software dev

Bloggy: Wicket Demo Blog App!

I pointed out in a previous post that I was learning Wicket. I decided to write something a bit more realistic in it, and since blog applications are all the rage these days (oh wait, are we past Web 2.0 yet? :P) – I figure it was as good an app to write as any, fairly simply domain model if you don’t go crazy, you can find it – Bloggy – in the code section. Due to the huge number of dependencies (uses Spring, Hibernate, and the Hibernate JPA implementation, and of course the Wicket jars as well), I have simply provided the sources – it is a Maven-based project however, so it should be fairly easy to get up and running. I have tested it on Jetty, and you will require Java 6 for 2 reasons:

  1. I marked the source and target to be 1.6 in the POM, hah!
  2. I have used @Override annotations on interface implementations, which is a Java 6 only thing (as I found out from a friend just a few days ago)

As far as Wicket itself goes – I am impressed, thoroughly enjoyed using it. Some points worth noting:

  • The thing I tripped on most often was ensuring that my object and markup hierarchies were in synch – a little annoying (though I’d rather have it disciplined this way than overly forgiving models) – but the error messages turned on in development mode/configuration were awesome1
  • As pointed out in Wicket in Action, you do tend to think a fair bit more about reusing components, so you initially start slow because Wicket encourages you to write your own components (panels being the most reusable components)
  • I found it was necessary to have the sources (recommended just for the heck of it) open in order to see how certain things could be extended, not necessarily a good thing, but the sources are well-written and useful to write your own stuff, or just understand how things are handled underneath, especially dealing with models. Speaking of sources, it is very OO that I learnt a few new ways to use patterns myself. (Sigh, been dealing with crappy UIs far too long)
  • I think with Wicket 1.4+ where Java 5 is the minimum requirement, using models will be much clearer, I admit to having been spoilt by Java 5+ generics thoroughly, and I created a couple of base parameterised models
  • Serialization – wasn’t as big a deal as I thought it would be – in fact in a 3-tier app where we generally use DTOs, this won’t even be an issue, granted however, it’s still something to look out for, you don’t wish to be serialising huge stuff into the session, and it is easier to do that than in something like struts because of the very stateful nature of Wicket
  • Wicket’s spring integration layer is quite nice, it allows you to inject stuff, but since it does not have explicit bean definitions of your components, I don’t think (and I may be wrong) it allows you to do funkier things like AOP, in UI code, I generally don’t find this to be a problem, the injection is far more crucial for me. I think the point as justified by the authors is that Wicket is by default an unmanaged framework
  • Ooh the Ajaxy stuff – I am no front-end Javascript guy – this made it a breeze to use, you obviously must understand basic Ajax concepts, but you don’t actually need to write Javascript, fascinating, I used editable labels, and link-submittable forms mostly (which were POST-ed, no nasty GETs for side-effect producing actions). I did not venture far enough as to write my own Javascript components however :-).
  • The default URL generation scheme’s not pretty – but Wicket provides additional schemes (packaged as URL codec classes) which are much prettier, and you can write your own – I found the provided ones to be quite sufficient though. I love the way they’ve designed the hook into the URL generation. Well, I hope someone finds this useful, if google ever gets you here!

1 If you’ve worked with the Struts tag lib (Struts 1 anyway), you will see what I mean – Wicket’s UI handling is certainly no hack of a solution tacked on with inconsistent conventions and uber-crappy error messages (anyone like “bean ” not found in scope” or something to that effect – gee thanks, or that there’s no select-EL version or one of those damned controls). I dread going back to the work force having to use that piece of unholiness again. Note that my harsh criticism is directed at solely the taglib, the rest of Struts is something to be respected for having achieved what it did way back!

Feb 23, 2009 - general personal philosophy

Blog Name Change

So I googled “lifeflow”, my God I am embarrassed – that turned up a heap of hits – could I be part of the hive mind that is the world. No, that can’t be, I attribute it to a quirk of fate :P. So here’s the new name, the tagline has “Code” added to it. In a sense the original intent of this web log has not changed, and I think figuring life out takes some encoding and decoding, and I do enjoy writing code, and and ‘codex’ is a book or manuscript – very log-y – so ‘Life Codecs’ sounds rather apropos. And googling this, as expected a lot of results turned up on audio/video codecs, but that’s okay – at least I am not some quick fix to gain enlightenment. I mean, I wish I was – like for real – but I’m not :P.

Let’s hope I don’t have to change it again.