avatarharuki zaemon

My foray into C# - Part III

By

Something I forgot to mention that was very cool about all this was the fact that I developed everything under Linux and the binaries run ASIS, under windows. That, to me, speaks volumes. It’s a credit to the guys on the mono project.

I also feel compelled to answer some of the suggestions that I’m biased. Me? Never! Nor am I opinionated, loud, prone to ranting….hehehehe

I too found the process to be very smooth and very easy. In no way did I try and suggest otherwise. At the end of both blogs I clearly stated how easy it was.

I was really trying to give an accurate account of what it was like to start from knowing nothing, along with all the annoyances and frustrations that comes with it. Some comparisons may not be valid from the perspective of a born and bred C#/Microsoft developer but you have to remember that it’s only natural to make comparisons. That’s how we learn. We try and compare it with something we already know to give it some context, some meaning.

I hear from a mate that C# version 2 will have generics and Iterators and a few things other things.

Regarding string versus String, you can’t (at least using mono) use any of the System classes without “using” the System namespace. This was the thing that seemed ridiculous to me. Unfortunately String (big S) lives in the System namespace. I only found this out after I had converted lots of code so I kept on with the string (little s) convention. This was how I had seen examples written up on the ’net that I was using as a guide.

As for performance, again, in no way did I try and make out that .Net was necessarily slower. All I reported was what I had found running under mono on gentoo linux. As stated in the blog, hardly a reasonable comparison hehehe.

The only thing I really can’t get used to are the libraries. I really do find them awkward. I used to be a C++ developer before I moved to Java and I really don’t see the C# libraries as a step forwards. Oh and unchecked exceptions.

In no way do I despise C#. Okay so the quip about compsci students may have been a little harsh… I got over all the extra keywords, maybe you can forgive me in return hehehe. C# and .Net may not be my cup of tea but they no longer appear too different and too scary to at least try out.

Thank-you linesmen. Thank-you ball boys. It’s back to watching the Australian Open…

My foray into C# - Part II

By

Well it’s just gone 7pm and I’ve pretty much finished the conversion of Simian to C#.

All in all it took around 8 hours to convert 2000 lines of real source (around 6,500 raw source lines) of Java code to C#.

I haven’t quite finished due to the blatently stupid file/directory handling in .Net. But I’m almost there. I’ve hard-`d it to run from the current directory for testing purposes. But 99% of it has been completed. Even the output is identical which is nice to see.

Performance? Well again, I stress I’m running under mono on gentoo so that’s probably not the best test but it seems to take around 50% longer to run and consume around 50% more memory than the Java version. I’ll have to run some tests on windows and see how that performs.

Some, hopefully, interesting bits to add to my last blog…

Case statements don’t allow you to fall through to the next one if you have defined any code for it. Instead you have to explicitly say you want to goto the particular case you need. Hmmm…not sure about that.

C# doesn’t allow you to put array specifiers [] after the variable name. It only allows them to go after the type. This is good. Only because it’s the way I code anyway but I did find some code that somehow managed to slip through unnoticed.

What’s up with structs? Sheesh! How are they in any way different to an Object except in the underlying implementation (ie they’re probably allocated on the stack or something)? More warm and fuzzies for the C fraternity? Get rid of them I say.

Marking something as readonly doesn’t actually seem to mean you must have assigned it a value. This may be a quirk of the mono compiler. I don’t know. But if not, that’s just wrong. The thing I love about final in Java is that it stops me from accidentally forgetting to assign a value to something. Took me 10 minutes to track down a NullReferenceException because I had accidentally deleted a line (an assignment) from a constructor. Using const is sometimes an option but it has a few caveats: const can only be used if you want a static variable; and; more importantly, the value has to be known at compile time! This pretty much means it’s only useful for simple, primitive values assigned in the declaration. I can’t use const for say a collection or an instance of any object that requires new. Nor can I use it for values assigned in constructors. Which is exactly the problem I had.

instanceof becomes is. How nice of them to simplify something I hardly ever use and generally consider poor practice anyway LOL.

I started off thinking that having to specify override for things was a good thing. Now I’m not convinced. Basically, if I haven’t thought that someone might want to override a method I’m pretty much screwed. Well they are. Luckily this is my own code base so I can refactor all I like. Shame about all those libraries and frameworks out there. If in doubt, you could always mark the methods virtual. Now that’s all very well and good but if the majority of the time I want stuff marked as virtual, wouldn’t it make sense to have that be the default? I think I’ll need a macro in my IDE for all these keywords: v[TAB]; ro[TAB]; etc. hehehe. But again, maybe it’s just what I’m used to?

Don’t get me started on the FileInfo, DirectoryInfo, File, Directory, yada yada yada. Even the regular expression libraries seem to have all these extra, essentially static, classes. The .Net libraries look like they were designed (and I use the term loosely) by high-school students. First year CompSci students at best.

Readers become TextReaders, Writers become TextWriters. In and out are reserved words! probably should have named my parameters something more meaningful anyway?

Auto-boxing? Didn’t use it. Well not that I know of. That’s the problem. I have no idea. Scares the hell out of me. Let’s see, we want a language with lots of optimizations to keep C/C++ developers happy so they can feel like they’re writing on to the metal, but for everyone else, lets make it really easy to not know you’re creating bazillions of objects all over the place. Hmmm…

All in all it was really easy and relatively painless. I started from nothing and probably still know nothing but it all seems to work. I can’t help but think that even in the early days of Java, the libraries may have been less functional, but they weren’t all over the place. More to the point, remember that C# came from Java (oh go on tell me it didn’t) so in my opinion there are no excuses. What, since C# started, a myriad languages have popped up that are at least as functional (probably more so) and far easier to use.

So, whilst it’s an interesting thing that we’ll all have to get used to, I’m happy in my Java land for the forseable future.

Time for a G&T to top off a good afternoon.

My foray into C#

By

Well after a relaxing 10 days riding my motorbike around Tasmania I return to Melbourne, chilled (literally), relaxed and raring to go. I think it’s about time to convert Simian to .net as had been suggested by many users. So here is a little blog of my experiences.

To start with, I’ve never written a line of C#. EVER. So I’m totally ignorant about all language constructs (except that having read the CLR book it looks like Java with uppercase method names) including, importantly, the libraries.

I’m also a linux weenie so I’m using mono under Gentoo. The combination is pretty good. Mono comes with mcs the compiler, monodoc, a purpose built browser for the framework libraries and mono for running your assemblies. At least I think that’s the new fandangled name for executables. Anyone?

I had first investigated writing an automated tool. The process seemed mechanical enough to automate yet difficult enough to end up doing some curly stuff. I also looked at some off the shelf converters but in the end decided doing it myself by hand was probably a good way to learn the ins and outs of the C# language and at the same time indulge my years of Java bias :-D.

My approach is simple: Open my project in IntelliJ (my editor of choice) and one by one, copy the .java files to corresponding .cs files, run mcs and hack away until it compiles cleanly. I have to also admit that I’m not going to turn my code into C# style stuff during this conversion. All my method names, variable names, class names, interfaces are remaining untouched. I’m not adding an I to my interfaces nor am I giving all my method names an uppercase first letter. Stuff that LOL.

So here we go…

The first thing is the package declaration. This becomes a namespace. Only, some crack smoking monkey decided that it should be a proper block which means I have to have open and closing curly braces around my entire source file. Not so bad but that means everything gets indented one more level. YUK! So I choose to just leave the indenting ASIS. Not so bad. Still seems unecessarily verbose to me.

Next. String becomes string. What’s with that? Method names get uppercase but String (a class) gets a lowercase? I got over it. Find+Replace is my friend.

Once again, Find+Replace for boolean. It’s a bool in C#. I’m guessing a hang-over from C++. Again, I can live with this.

What’s the problem with declaring a class as final? Ahhh. A quick search of the ’net reveals that it’s sealed. Ok. Another keyword to remember. Not too bad I guess. On we go…

Crap. How do I declare a constant? In java it’s static final. In C# it’s, quite logically I guess, const. Bulk Find+Replace for that. Done

Ok. Now I want an immutable (readonly) instance field. In Java I just mark something as final. In C# it turns out, I have to use readonly. Egads! Another keyword to remember.

It’s interesting. When I first started using Java I thought it odd that a few keywords, such as final, seemed to be used for slightly different meaning but it soon became apparent that really the meaning was the same: It’s final; Unchangeable; Immutable; Not modifiable. C# seems to want me to use a different keyword for every little thing. This is beginning to irritate me but it’s still not difficult to do.

Starting to lose enthusiasm for this. I see all this syntactic sugar entering the Java language, obviously driven by C# and I wonder if my already less than perfect Java will become a quagmire of lexical sludge.

On I go…

Syntax Error. Hmmm… Maybe it’s not called throws in C#? Quick IM to Mike Melia. C# has no checked exceptions. I knew this. But what I didn’t know is that you can’t even declare that a mehod throws an exception. Any exception. Hmmm. Oh well. Believe it or not, it’s my custom Assert class (starting simple) and it’s only IllegalStateException anyway so strictly speaking it doesn’t have to be declared. I’ll just delete it.

Ok what’s the problem now? class IllegalStateException not found. What’s an equivelant in C# I wonder. Trudging through the documentation I give up. This doco is really hard to follow. JavaDoc seems much easier to read. Maybe it’s just a matter of what I’m used to. I’ll just throw ApplicationException instead.

Still giving me grief. I prefix the class name with System.. That does the trick. Hmmm. That’s a bit stupid. Having to import the System namespace? Go figure. I choose to add a using for it. I don’t like putting package/namespace names into my code.

I discover that C# doesn’t allow importing classes. Only namespaces. This is ok by me. I always figure that once you have a dependency on a class in a package, you really have a dependency on all classes in the package in a way. What I don’t like is that now I don’t have any idea, just by looking at the top of the class, what other classes it depends on.

Woohoo. A clean compile. It’s complaining that there is no entry point but I can live with that. I haven’t specified a main anywhere. At least we got a compile.

It’s now a little after 12.30am. A bit of success has brought back my enthusiasm. I’ll keep going.

Time for an interface. Bleh. Can’t have public keyword on interfaces. Yeah Yeah I know. They’re all public anyway. But as in Java, it annoys me that a missing visibility modifier means one thing for a class and another for an interface. At least in Java I can safely put the public there and it doesn’t complain. Find+Replace. Done.

Now time to do one of the classes that implements the interface.

Ok. This is ridiculous. If I have an abstract class that implements an interface but doesn’t implement all the methods, I still have to define the methods in the abstract class as abstract. I’ve defined the class as abstract. Can’t the compiler work this out? Sheesh. Talk about needless typing.

Uh. Now I discover I have to explicitly say virtual on all my methods to allow them to be overriden. I have no problem with saying override when I actually do override something, that’s kinda cool, but I’m guessing the virtual bit is a hang-over from C++ and/or it makes it easier to optimize the output of the compiler because I the developer have to tell the compiler that there is no need to create jump-vector-tables for the method. Whatever the reason, combined with the previous stuff to do with interfaces, it’s really starting to drive me nuts.

Ok. It’s now 2:45am and I’m honking along. Thankfully the compiler catches all the bits I forget to change. Sometimes the messages aren’t particularly helpful but that may just be the mono compiler. Nothing to do with C# per-se.

I’ve done all the simple classes I could find. All the ones with few dependencies. Now it’s time for some of the more meatier ones. I think I’ll keep going until 3.30am and then call it a night.

I have a bunch of decorators (I love decorators) but boy is it a pain in the butt to implement in C#. It’s like alphabet soup after I’ve added all the necessary keywords: virtual, override, sealed, etc. Do Microsoft developers get paid by keystrokes? Anyway I’m getting there. It really is becoming quite mechanical now.

C# uses C++ style class extension. So instead of saying extends you use a colon :. you also call the super-class constructor using the C++ style colon after the constructor name instead of on the first line of the constructor. That’s not too bad. Pretty much the same thing anyway. Oh and just to be different, super becomes base.

I’ve just spent the last 20 minutes learning about the collections classes. I’m beginning to think the .Net libraries were an R&D project that made it into the wild a little too early. 57 (I exaggerate a little hehe) different collection classes and none seem to do what I want.

Aha! There it is. StringCollection. Basically a Set implementation for strings. Ok now to iterate over them…

Grrrr. No Iterators. IEnumerator? Gimme a break. Instead of hasNext() followed by next() they use MoveNext() which returns true if it was successfull and a Current property that is null if there isn’t a current value. Ok. but I can change my for loops into foreach which is kinda cool and surely makes up for it. As I mentioned before, that’s one of the features I’m looking forward to in J2SDK 1.5.

I’ve just converted some code that parses numbers and some that performs file I/O. Do you think that I could work out what exceptions might be thrown? I’m going head-first into the unchecked exceptions debate here and state outright that it is plain broken and wrong that the only way I can find out what exceptions can be thrown is to pray and hope that they were documented. My god! Not only that, but the I/O exceptions don’t seem to extend any sensible base class. So now instead of hoping I’ve caught all the necessary exceptions, I’m forced to catch Exception.

I’m very glad I’m converting from fully tested, well designed (if I do say so myself, which I do hehehe) Java code because I truly believe at this stage that C# and the .Net libraries are woeful.

I admit, I’ve now around 3 1/2 hours of C# experience which clearly makes me an expert, NOT, but I struggle to see how you could take Java, and make it worse and less mature. They managed it though.

Ok, well now I’m screwed. IEnumerator doesn’t allow you to remove from a collection whilst iterating. In fact it expressly says this isn’t allowed. I’ve written a bunch of custom collection classes (for performance reasons) that I was hoping I could just ignore for now but looks like I’m going to have to convert them as well just to get the behaviour I need.

It’s now 3.45am. Time for bed. My brain hurts. Back into it tomorrow me thinks. I’ve done around 45% of the code base in a couple of hours. Not bad. It’s pretty easy. I wonder what the Microsoft conversion tool is like :-)

It’s not too bad so far. A few quirky things here and there. It surely looks like they’ve tried to make all their existing developers happy by keeping lots of language constructs the same as those in Microsoft flavours of C/C++, VB, etc. I can understand that. In fact I think in some ways it’s remarkable that they think that way about their developers. But still it’s a bit of a heinz 57 varieties in places.

Generics

By

Now I’m sure you’re all bored to tears with yet another blog on generics but I felt it was only fitting to convert all my example code.

So, here is what the immutable collection examples turned out like:

public class Component {private final Collection<Component> _subComponents;public Component(Collection<Component> subComponents) {Assert.isTrue(subComponents != null, "subComponents can't be null!");_subComponents = Collections.unmodifiableCollection(Arrays.asList(subComponents.toArray(new Component[subComponents.size()])));}public Collection<Component> getSubComponents() {return _subComponents;}}

Interesting. Because I wanted to use Collections.unmodifiableCollection(Collection<T>) it now needs to know the types. So I had to use the T[] Collection.toArray(T[]) method instead.

Or we could make it ever clearer:

public class Component {private final Collection<Component> _subComponents;public Component(Collection<Component> subComponents) {Assert.isTrue(subComponents != null, "subComponents can't be null!");List<Component> temp = new ArrayList<Component>(subComponents.size());temp.addAll(subComponents);_subComponents = Collections.unmodifiableCollection(temp);}public Collection<Component> getSubComponents() {return _subComponents;}}

And of course my original bitch about custom type-safe collections:

Collection<Customer> customers = ...;for (Iterator<Customer> i = customers.iterator(); i.hasNext(); ) {doSomething(i.next());}

Not bad. Feels like C++ again ;-). Not sure if that’s such a good thing or not.

As Damian Guy points out, we could do even better using the new for construct provided by 1.5:

for (Customer c: customers) {doSomething(c);}

Now that definitely looks much nicer! Unfortunately I don’t have a runtime that will support this - I can’t seem to get J2SDK 1.5 to install on Gentoo :-(

Looking over all my newly re-written (that’s re-factored for you buzzword bingo players) code, I have to say it reads pretty well. Time will tell if it really does add much more than using the old collection classes.

One thing I will note is that it’s nearly impossible to copy and paste the examples for publishing as html. I have to change all the < and > to < and > respectively. Just putting that previous sentence in was a job and a half! hehehe

And lastly, I’m using IntelliJs support for generics using the 2.2 early access compiler from Sun. So no doubt things will change by the time they’re released in J2SDK 1.5 proper.

Immutable Collections

By

Oh what joy. Back on the last week of my project from a brief break for xmas and straight to the inevitable cvs update. Yikes!

This is probably old hat to a lot of you but for all others, Collections.unmodifiableCollection() and its siblings don’t actually make a collection immutable!

By way of example, the following code is broken:

public class Component  {
  private final Collection _subComponents;

  public Component(Collection subComponents) {
    Assert.isTrue(subComponents != null, "subComponents can't be null!");
    _subComponents = Collections.unmodifiableCollection(subComponents);
  }

  public Collection getSubComponents() {
    return _subComponents;
  }
}

Looks pretty good but unfortunately, the following test breaks:

public void testImmutability() {
  Collection originalSubComponents = new HashSet();
  Component component = new Component(originalSubComponents);
  Collection returnedSubComponents = component.getSubComponents();
  assertNotNull(returnedSubComponents);

  // First, we test to see if the returned collection is immutable
  try {
    returnedSubComponents.add(new Object());
    fail("sub components should be unmodifiable");
  } catch (UnsupportedOperationException e) {
    // Pass
  }

  // Next, we test to see if we can subvert the immutability
  // by addding to the original collection
  assertTrue(returnedSubComponents.isEmpty());
  originalSubComponents.add(new Object());
  assertTrue("sub components should be a defensive copy", returnedSubComponents.isEmpty());
}

We haven’t made a defensive copy! So let’s add a little more code to get the test to pass:

public class Component  {
  private final Collection _subComponents;

  public Component(Collection subComponents) {
    Assert.isTrue(subComponents != null, "subComponents can't be null!");
    _subComponents = Collections.unmodifiableCollection(Arrays.asList(subComponents.toArray()));
  }

  public Collection getSubComponents() {
    return _subComponents;
  }
}

Remember, anytime a caller passes you a mutable object (such as Collection, Date, Calendar, etc.), you need to make a defensive copy if you’re going to hold on to it. This will ensure no one accidentally subverts your own immutability.

Why did I use Arrays.asList() to create the copy? Well I’m glad you asked:

  • Because I know the collection will never be modified (that’s what immutable means after all), I don’t need to maintain the semantics of the original collection (which may have been a Set for example);
  • The resulting List will be have been created with exactly the right size to accomodate the contents of the collection, meaning no re-allocating buffers. As a reader points out the standard ArrayList constructor that takes a collection as an argument will allocate an additional 10%;
  • Arrays List implementation performs well when iterating; and;
  • The iteration order is preserved (if that was important).

It is also possible to use new ArrayList(int) followed by ArrayList.addAll(Collection), which is probably easier to read?:

public class Component  {
  private final Collection _subComponents;

  public Component(Collection subComponents) {
    Assert.isTrue(subComponents != null, "subComponents can't be null!");
    List temp = new ArrayList(subComponents.size());
    temp.addAll(subComponents);
    _subComponents = Collections.unmodifiableCollection(temp);
  }

  public Collection getSubComponents() {
    return _subComponents;
  }
}

As one reader has demonstrated, on his version of the JDK it uses an iterator which is the way I had assumed it would be implemented but I was thrown off when I looked at the source code for the version of the JDK I have and discovered that it creates a temporary array. Either way this post wasn’t really about performance so I guess I’m getting a little off track now.

P.S. Anyone see the funny side of this test given my previous post?

Be gone ye foul smelling custom type-safe collections!

By

I used to use STL type-safe collections in C++ all the time and when I moved to using generic collections in Java something just felt wrong. How was I to ensure my collections contained the correct types?

But you know what? Much to my surprise over the years, I’ve never really had a problem. I can’t even remember the last time (if ever) I had a class-cast exception from accidentally adding the wrong type of object to a collection.

Which one of these would you rather?

The generic collections approach:

Collection customers = ...;
for (Iterator i = customers.iterator(); i.hasNext(); ) {
  doSomething((Customer) i.next());
}

Versus the custom type-safe collection:

public class CustomerCollection extends AbstractCollection {
  private final Collection _customers = new HashSet();
  public boolean add(Object object) {
    return addCustomer((Customer) object);
  }

  public boolean addCustomer(Customer customer) {
    return _customers.add(customer);
  }

  public int size() {
    return _customers.size();
  }

  public Iterator iterator() {
    return customerIterator();
  }

  public CustomerIterator customerIterator() {
    return new CustomerIterator(_customers.iterator());
  }

  public final class CustomerIterator implements Iterator {
    private final Iterator _iterator;
    private CustomerIterator(Iterator iterator) {
      _iterator = iterator;
    }

    public void remove() {
      _iterator.remove();
    }

    public boolean hasNext() {
      return _iterator.hasNext();
    }

    public Object next() {
      return nextCustomer();
    }

    public Customer nextCustomer() {
      return (Customer) _iterator.next();
    }
  }
}
CustomerCollection customers = ...;
for (CustomerIterator i = customers.customerIterator(); i.hasNext(); ) {
  doSomething(i.nextCustomer());
}

Not so bad you say? Well try doing this for every type for which you need to hold collections. Then try implement List or Set instead of the basic Collection. Don’t even think about what it takes to implement Map. I admit, you might end up re-factoring some of this into a generic base class. You could even write one without implementing any of the collection interfaces. But then, why bother?

Sure, they might have save me a few keystrokes here and there but because most people (as I have done in my example) create their type-safe collections with names like getCustomer(), etc. it saves me 2 key-strokes over using a simple cast like (Customer). In fact, in the example given, I actually ended up with more key-strokes!

“But it’s not about keystrokes, it’s about type-safety” I hear you exclaim. Well yes, you may be right. But as I mentioned earlier, I don’t recall this ever being a problem on any projects I’ve worked on. Oh, how that I think about it, there may have been one project but I’m pretty sure we simply shot the offending developer for being such an imbecile ;-)

I’m currently enduring the pain of working on a project where the consensus was that we should have type-safe collections. I seem to spend half my day implementing these instead of letting IntelliJ and Eclipse do a fine job of adding the casts in for me.

And so it is that I eagerly await the release of JDK 1.5 and language supported type-safe collections in the hope that it’ll once and for all stop people writing these useless custom implementations. Egads!

Be Assertive

By

I recently discovered a bug in an Ant task I had written a while back. A customer was running the code and it barfed with an IllegalStateException telling them proudly that the code"formatterType cannot be null"code. Nothing special about that I suppose. A NPE would have done much the same thing. The only difference is that the code is obfuscated. That means the stack trace is totally useless. Not only that, but they were running an older version of the software which would have meant I would have had to check out that particlar version from CVS, build it and see if I could work out what was going on.

As it turned out, There were only two places in the code that performed a null pointer check with this particular message and only one of them is called from the Ant task. A bit of detective work later (like 5 mins tops) and I had a failing unit test written and running. The fix was one line. Actually half a line as it required assigning a default value to an instance variable in the declaration :-).

I program defensively. I check parameters for null pointers, I assert that objects are in the correct state at the start of the method etc. I’ve found I catch strange bugs much, much earlier than if I simply wait for the NPE. I also have a preference for immutable objects, which substantially reduces the set of things I need to check for. I’ve had countless debates with, mostly junior, developers who believe that it’s better just to wait for the NPE. But fundamentally, I put assertions into my code so that out in the field my software fails in predictable ways. Ways that will ultimately help me to identify the nature and cause of a problem as easily as possible.

I even have an IntelliJ macro setup so that it’s as painless as possible to add a check to my code. And just to be sure, James Ross and I even wrote a custom checkstyle check to ensure that an object reference is always checked for null before being used.

There are also a number of libraries around such as iContract and jContractor, that go way beyond simple assertions and allow you to add Design by Contract conditions to your code via javadoc comments and byte-code modification, special methods, macros that a pre-processor inlines, etc. Though I’ve never used them, I’d be interested in comments from anyone that has.

The thing is, I’ve never used the assert statement in java. That doesn’t mean I don’t believe in assertions, clearly. I’ve just never used the built-in support. I’ve never liked the fact that you can turn them off. To me, this defeats the reason for having them there in the first place. In fact the JDK assertions (at least in 1.4) have to be explicitly turned on. I’m not so much interested in catching NPE’s etc in development as preventing really bad things happing in production so to me, it seems rather pointless to turn then off.

Instead, I use a custom Assert class that works in any JDK and can’t be turned off.

public final class Assert {
    private Assert() {
        throw new UnsupportedOperationException("Constructor should not be called");
    }

    public static void isTrue(boolean condition, String message) throws IllegalStateException {
        if (!condition) {
            fail(message);
        }
    }

    public static void fail(String message) throws IllegalStateException {
        throw new IllegalStateException(message);
    }
}

(This is one of those times where I feel it’s just fine to have a bunch of static methods. Imagine butchering your code to have an Assert object passed into the constructor of every class I ever created? YUK! ;-) All you AOP weenies get back in your box before things get ugly!)

I also noticed commons-lang has a Validate class that provides the same functionality (and then some). Though, again, I’ve never used it myself.

I can think of one possible reason why I might want to turn off not only an AssertionError being thrown but the condition check itself. If you’re using asserts for checks such as “when the method ends, there should be at most 2 address records for the customer”. This may well be an expensive operation that you don’t want performed everytime in production but I don’t tend to check these sorts of things. Now I’m thinking maybe I should? Or is that what my unit tests are for? But then usng asserts, I could turn them on in production if I needed to catch some bug I was having trouble replicating. Having said that of course, if I had a sufficient test suite, I bet I could find the bug just as easily without resorting to debugging in production. Hmmmm

Best Practices

By

I happened upon this post on the artima web site which reminded me that I had been wanting to rant a little about best practices for a while.

It has always seemed to me that so called “industry best practices” are really only ever identified at the end of a cycle of innovation. Or in other words, when many in the industry have moved on to developing “better” practices. My observation has been that companies striving to adhere to “best practices” are often at least 12-18 months behind the leaders.

Some (read large, conservative, glacial, etc.) companies take so long to adopt advances in technologies and methodologies, etc. that by the time they do, they’re really using legacy* practices. They are highly risk averse. They can’t, won’t or don’t employ talented developers. Instead they hire an army of over-paid whiteboard architects who couldn’t build a software system if they tried. These whitebaord architects, with little or no understanding of what really goes on their own industry, need to protect their backsides by showing little or no innovation by promoting whatever methodolgy sees most of a projects time and budget justifying their employment and ensuring there is always someone else to blame if/when something goes wrong.

Now, don’t misunderstand me. I’m, in no way suggesting you jump on the next AOP, IoC, whatever wagon that rolls into town. But don’t be fooled that simply automating manual processes or creating a web site (inter-, intra- or -extranet) will suddenly make your business more efficient. We should be striving to deliver high-quality, adaptable systems that allow the business to realise competitive advantage as early as possible.

  • For clarification, I’ll define legacy to mean anything that clearly doesn’t work to all but the people who try so hard to believe that it does not least because their jobs probably depend upon it. A kind of managed failure. As a reader suggests, if it works, it’s not legacy.

Testing with factories

By

A long time colleage of mine asked me yesterday about IoC. After explaining about constructors, etc. we then discussed factories. He understood the way you would pass a single instance of say a widget to an object via the constructor, but what about something more complex that doesn’t know which widget it wants or needs multiple widgets. Enter the factory.

Factories are really no different from other java objects that require some kind of lookup mechanism to find such as, JDBC connections, JNDI contexts, etc. One of the most common ways to implement factories to facilitate runtime lookup is the so called abstract static factory “pattern”. (I used the term pattern simply because others have. In general I find most people abuse the use of the word, but that’s a rant for another time).

For those not familiar with abstract static factory, the general idea is you create an abstract base class with a static method, say newInstance() or getInstance() for example, that returns the concrete implementation of the factory and an abstract method, say createWidget() that the concrete class implements. Typically, the concrete class is determined at runtime by using something as simple as a system property or something a little more sophisticated (ala META-INF/services). If you’ve ever used JAXP, you’ve been using one without possibly realising it.

public abstract class WidgetFactory {
  public static final WidgetFactory newInstance() {
    try {
      return Class.forName(System.getProperty(WidgetFactory.class.getName()).newInstance();
    } catch (...) {
      throw new IllegalStateException("Can't instantiate concrete factory: " + e.getMessage());
    }
  }

  public abstract Widget createWidget();
}
public final class WidgetFactoryImpl extends WidgetFactory {
  public Widget createWidget() {
    return new WidgetImpl();
  }
}
public final class Window {
  public Window() {
    add(WidgetFactory.newInstance().createWidget());
    ...
  }
  ...
}

I will usually have to set a system property to tell the abstract factory which concrete implementation to use. Apart from the fact that this destroys my ability to run multiple tests in parallel (system properties are global!), you could also think of it as a kind of violation of encapsulation - my test class has to know how the abstract factory is implemented so that I can tell it to return my mock factory instead.

public void testSomething() {
  System.setProperty(WidgetFactory.class.getName(), MockWidgetFactory.class.getName());
  Window window = new Window();
  ...
}

So anyway, given my love of TDD which seems to lead me to pass implementations of interfaces into constructors (ala IoC), I have a dislike of most things static. Even the abstract static factory.

Instead, I prefer to have the factory defined by an interface. Then pass an instance of the interface to the class that depends on the factory (ie no more newInstance()). In my test this can be a mock implementation, and at runtime this can be configured in a number of ways to pass a real implementation.

public interface WidgetFactory {
  public Widget createWidget();
}
public final class WidgetFactoryImpl implements WidgetFactory {
  public Widget createWidget() {
    return new WidgetImpl();
  }
}
public final class Window {
  public Window(WidgetFactory factory) {
    add(factory.createWidget());
    ...
  }
  ...
}
public void testSomething() {
  Window window = new Window(new MockWidgetFactory());
  ...
}

Sometimes this is difficult to achieve, especially when you have to use a 3rd-party API that only has an abstract static factory (such as JAXP). In this case, you really have a few possibilities:

  • Call newInstance() externally and pass the resulting concrete factory into the constructor. At least this way, you should be able to implement some kind of mock implementation, even if that means extending the abstract factory;
  • In the case of sframeworks that force you to have a default constructor, consider a hybrid where your objects have both a constructor that accepts an instance of a factory for your own use, and a default constructor that falls back on some kind of lookup mechanism (such as abstract static factory) and simply passes the factory instance to the other constructor; or
  • In the case of struts, as James Ross has pointed out, you can hang the factories out of the session or the application context and let struts set them for you; or lastly;
  • Continue using the factory ASIS from within the class. In the case of JAXP I can’t see a big problem with this (one hopes that it is already fully tested!);

Naturally, I have a preference for the first approach if I can get away with it as it makes my life much simpler when it comes time to test and debug. No more flipping system properties, tests that can be run independently and in parallel, etc.

I can think of reasons for using the last method that are mainly to do with resource issues like “but I don’t want an instance of the factory lying around if I don’t need it. If that really is going to cause you resource issues (which I very much doubt), then at least wrap the factory in a class that lazily creates a factory for you.

I'd like to coin a phrase...

By

… for software that bears not the hallmarks of great craftsmanship so much as lovingly “hand crufted code” ;-)

What are your intentions?

By

Allow me to vent for just a minute. I promise it won’t take long…

In an effort to improve the amount of Javadoc in the source base, the current project I’m working on has been set up (not by me I might add) to use checkstyle to enforce Javadoc standards.

Following on from why javabeans are evil I have to say that enforcing Javadoc on getters and setters (that’s accessors and mutators for all you Java Certified Developers out there :-P) is one of the most pointless things I’ve ever seen.

It takes me about 10 seconds to use IntelliJ (or eclipse for that matter) to generate all the getters and setters for the attributes on my DTOs. It then takes me ten minutes to either write the JavaDoc by hand. So I try using the auto generated javadoc only to find that it takes almost as long to change all the generated Obtains the value of paymentDate to Obtains the value of the payment date.

In fact it occurs to me that if my IDE can work out what to generate as javadoc, surely I can work out what the code is doing simply by looking at it?

I’ve always been a fan of commenting code. I guess it comes from my assembler programming days. I must admit I write fewer and fewer comments these days as my programming style has changed to be more “self-documenting”. No matter what though, if you are going to write comments, it’s important that you document the intent and not the implementation. How many times have I seen this:

++i;                          // Increment the current index
collection.add(values[i]);    // Add the value at the current index to the collection

This serves no purpose other than to satisfy the good-old comment/source-code ratio checker :-). Even worse, it adds nothing to my understanding of the code (ie intent) and IMHO adds significantly to the signal/noise ratio.

Most javadoc I see follows along similar lines. When 50% of the code is comments, kindly informing me that the getCustomer() method Gets the customer, etc. I can’t help but wonder what the hell we’ve been spending our time doing.

What’s worse, as with most kinds of heavy documentation, the comments rapidly become out of date as we constantly refactor the code, rename classes, attributes, etc.

Hmmm…I’m no language expert (as is evidenced by my ramblings on this site) but I wonder if it’s possible to analyse the comments and determine if they’re documenting intent or implementation detail?

In any event, as a start, do me a favour and don’t enforce Javadoc on getters and setters. I’ll meet you half way and try to get used to putting opening braces on a new line :-)

Inversion of Control

By

“I was expecting a paradigm shift and all I got was a lousy constructor!”

Perryn Fowler has asked me how would we use the Clock? How do we create one for production? The Inversion of Control (IoC) fraternity frown upon factories so what are we to do?

Luckily, software developed using TDD tends to lend itself to IoC.

This example conforms just fine with so called “Type-3” IoC which is based on passing dependencies via constructors. It’s a very simplistic example nonetheless. For more complex systems, you may want to check out IoC containers such as PicoContainer et. al. which seem to be gaining in popularity. And for good reason.

These containers allow you to easily configure components and the dependencies between them. Although I must admit that I’m not a fan of the hype as some people have been building systems like this for a while now. The up-side of course is that others will hopefully feel more comfortable looking into it as an alternative now that it has a snazzy name and the obligatory TLA :-)

Once you get your head around it, it’s pretty easy to see why people love the concept of IoC containers so much. In some ways it’s not that much different to plugins but it does lend itself to other cool stuff, like decorating and “passivating”. No more JNDI lookups, no more creating endless factories with static methods. But as I said it can be hard to see at first how that works.

So here is the simplest example I could think of and whip up in 20 minutes. It displays a panel into which you can enter a duration to wait (in milliseconds) and a message to display once the time has elapsed.

It hopefully demonstrates how we can now use Alarms knowing they are fully tested and how we don’t need a static factory to create anything.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Main extends JFrame {
    private final JTextField _durationMillisField = new JTextField("3000");
    private final JTextField _messageField = new JTextField("Message!");
    private final JButton _setButton = new JButton("Set");
    private final Clock _clock;
    public Main(Clock clock) throws HeadlessException {
        if (clock == null) {
            throw new IllegalArgumentException("clock can't be null");
        }
        _clock = clock;
        getContentPane().setLayout(new GridLayout());
        getContentPane().add(_durationMillisField);
        getContentPane().add(_messageField);
        getContentPane().add(_setButton);
        _setButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent actionEvent) {
                setClicked();
            }
        });
        setSize(300, 50);
    }

    private void setClicked() {
        int durationMillis = new Integer(_durationMillisField.getText()).intValue();
        Popup popup = new Popup(_messageField.getText());
        Alarm alarm = new Alarm(popup, _clock.getCurrentTimeMillis() + durationMillis, _clock);
        new Thread(alarm).start();
    }

    private class Popup implements Runnable {
        private final String _message;
        public Popup(String message) {
            if (message == null) {
                throw new IllegalArgumentException("message can't be null");
            } _message = message;
        }

        public void run() {
            JOptionPane.showMessageDialog(Main.this, _message);
        }
    }

    public static void main(String[] args) {
        new Main(new SystemClock()).show();
    }
}

Nothing too complex here. It doesn’t go into testing GUIs (a topic for a book perhaps?) but as you can see, it would be possible to break down even this example into smaller chunks for testing. But really, the only thing the JFrame does is convert from screen values to primitives in order to create Alarms.

(As an aside, my original example had a Scheduler that created Alarms and set them running in a Thread but again I thought I’d ke it as simple as I could so I simply put the code into Main.)

In some ways it seems almost trivial really. But if you can imagine a whole system done this way it’s a pretty cool way to build apps. In a bizarre way, it’s kind of like rule based systems such as CLIPS or JESS only instead of declarative rules that magically get evaluated, in this case, the dependencies are declarative and are magically resolved at run time.

Take a look at the other examples on the net and drop me a line if you want me to put together a more complex example using say PicoContainer or NanoContainer.

Don't blame the brace

By

Everyone remember this:

int main(int argc, char *argv[]) {
    return 0;
}

The C programming language is the the ancestor of Java that no one likes to talk about anymore. One of the overriding imperitives when developing the syntax of the language was ease of compilation. Curly braces make it easy for a parser to work out where blocks of code start and end. So naturally, we humans realised we could use them for the same purpose. Only we also worked out, smart little things that we are, that code is much easier to read if nested blocks are indented. This way the blocks stand out even more.

(As an aside, languages like Python use this indenting to delineate blocks of code which is kinda cool in my book but certainly not to everyones taste).

Anyway, next thing you know, the C language takes off. Developers used curly braces on new lines and indenting to make their code more readable. You could easily match up start and end blocks, you could see the nesting. Ooh it was a happy time for all. Sure made a change from all that assembler code right? Great mountains of code are produced. Functions from tens to even hundreds of lines long, containing levels so deep that, once again, it became hard to tell where blocks of code started and end.

Enter the end-of-block-comment! “Of course!” exclaimed the developers, “lets mark the end of each block with a comment to indicate what to look for when searching for the start. If it’s a while loop we’ll add /* while */ at the end. If it was a for, we’d finish with a /* for */ , etc. What a sensible idea” they chuffed.

Years later, we C programmers ventured forth into the brave new world of C++ and sometime thereafter, into Java, bringing with us all our accumulated knowledge and wisdom.

When I wrote Simian one of the first things I noticed was that removing curly braces from the input stream improved the overall effectiveness of the matching. Why? Because by removing the curly braces, I reduce the signal/noise ratio. Yup, curly braces are noise. They started off as a neat way of simplifying parsing and still add little value over and above that.

“But, but but…” I hear you complain loudly. “What about all the examples you’ve just given. Surely that counts for something?”

Sure. If you have methods that are hundreds of lines long. If you have blocks of code nested 3, 4 even 5 or more levels deep. If you have boolean expressions containing dozens of conditions, then you know what? I might just have to agree with you.

But I don’t! I have methods with an average length of no more than probably 15 lines with an upper bound (enforced by checkstyle) of 30. I’m talking executable statements here not simply EOL characters.

Make your code more readable by simplifying the code! Break out those conditionals. Break out those nested for loops. Stop nesting try-catch-finally blocks. Break up those ugly switch statements and turn them all into private methods. Make them all static final if you’re worried about performance (not that it buys you much these days). The fact is that compilers can do wonders with inlining of private methods these days. Compilers are much smarter now than when Mr. Kernighan and Mr. Ritchie were playing around with their lovely new C language compiler.

Importantly, I believe the usual arguments over whether one way is esthetically more or less pleasing than another are a waste of time. It’s not a democracy but it is a benevolant dictatoriship so if you like it that way let’s all agree and get over it. Just please stop using the curly brace as an excuse to write crappy code.

Domain Driven Design

By

I spent many years writing software that was essentially procedural in nature with transaction scripts accessing a database through very simple active records. Since I’ve come to appreciate the benefits of a rich domain model I’ve wished I had the ability to communicate this to others.

So I was excited when I heard about the book Domain Driven Design.

It’s nicely written. A good mix of code, diagrams, anocdotes and I particularly like the transcripts of conversations from actual modelling and design sessions. Lots of examples, rules of thumb and hints and tips here and there. It reminds me of Pragmatic Programmer in the way it reads.

Points I’ve particularly liked:

  • Model-driven design he says “discards the dichotomy of analysis model and design to search out a single model that serves both purposes.” Something I’ve always felt since reading Analysis Patterns. As the author points out, this is very hard to do but well worth the effort.
  • The good old manufacturing metaphor where highly skilled engineers design and less skilled laborers assemble the products has “messed up a lot of projects for one simple reason – software development is all design.” All right! Rock on! I’m printing that out in 70pt font and sticking it up on the wall of my favourite enterprise architects office!
  • “If an unsophisticated team with a simple project decides to try a MODEL-DRIVEN DESIGN with LAYERED ARCHITECTURE, it will face a difficult learning curve.” I’ve recently pondered this as I’ve struggled with bringing teams of developers up to speed with these concepts. I’ve wondered whether I may be making matters worse before they, hopefully, get better.

Things I’ve disliked:

  • As Doug points out in his review, I too was a bit surprised by the “Manager” classes. Seems to defeat the whole purpose of rich domain models but as I haven’t finished yet and, the author promises to address this later in the book (fingers crossed) I’ve chosen to ignore it so far.
  • The book is rather verbose I’m sad to say. I got into the first section and started to stall! It was very hard to get motivated to read the rest of the book.

All in all not a bade book. Someone definitely needed to write about it but as I mentioned, it was a little verbose for my liking. But I did finish it and I’d have to say that it was probably worth it.

Question for all you blogging gurus

By

I just received a message from a reader:

Hey I just wanted to let you know I really enjoy your blog but I’ve been getting lots of duplicate copies of your posts in my RSS reader (Newsgator), I don’t know if this is because you repeatedly modify your posts? And now I’ve gotten another copy of all your posts back to Nov 28 so I have to find them all to mark them as read. So I unsubscribed (But I should still receive your posts from javablogs.com I guess if it is still in operation :).

I had no idea this would happen. Doh! Some technologist I am LOL.

So to my question: is there a way to not have it behave this way? Or should I just stop editing my blog? Hehehe. I continually update it to correct spelling mistakes and typos in code examples, etc. So that seems like a rather crappy solution. Or maybe I should just move to a wiki with an RSS feed? Any idea?

I’d hate to think how many others are frustrated with seeing the same stuff appearing over and over again.

And you all rock! I hope this works but the solution seems very simple:

It’s a stupid feature of newsgator that is on by default. Whenever a blog entry is modified it’s sent to the user as a new blog entry. It is easily turned off in the options, but I believe the user needs to configure this for each rss feed.

It's an obsession

By

As I noted earlier, Perryn Fowler spotted the “deliberate” bug in the clock code. These two entries prompted some interesting commentary suggesting (possibly quite rightly) that I’ve been obsessing about unit tests.

While I think the points raised are valid, I’m compelled to note that my obsession lies with improving code quality and Test Driven Development (TDD) in general and not specifically with unit testing.

My focus recently has been on unit testing because I disagree with the idea that developers focus too much on unit tests. My experience is that developers are more than capable of writing great swags of integration and functional tests over poorly constructed, hard to understand and hard to maintain code. Not to mention that the tests are written as an after thought, are often difficult to automate and take countless hours to run even when they are automated.

I would never claim that one should only write unit tests. Rather, I would simply ask that you start with a test. Some have noted that TDD takes us back to the “good old days” of top down development :-)

FWIW, I write significant numbers of integration tests, often (though not always) before I’ve written the corresponding unit tests. Why? Because I need to test my assumptions about the behaviour of various layers, libraries etc. on which my code will depend. Then when I’ve verified my assumptions (probably learning much more than I had anticipated along the way) I am happy to ignore those layers for as long as possible.

And there is no doubting that there is an absolute, cannot do without, requirement for a comprehensive functional test suite. Frameworks such as Fit, jWebFit (part of the jWebUnit package) and Fitnesse are interesting in that they hold the promise of writing functional tests before writing the code! But as yet, I’ve no practical experience worthy of note using them. I assure you that when I do, I’ll let you know :-)

Although I would never recommend mocking infrastructure, people have used service stubs since the dawn of software development. There is no denying that these are vital when access to back-end systems is not always guranteed. In keeping with the fractal nature of software, I don’t see there is a difference between stubbing a mainframe application for testing business logic, and stubbing and application server for testing presentation logic.

None of this, however, in anwyay explains my interest in (obsession with?) TDD.

My strongly held belief is that TDD isn’t actually about testing. For one, it’s about documenting requirements and letting those requirements drive the design of the application. And importantly, the observation of many that easily testable code is designed well, is easier to understand and easier to maintain.

Why EasyMock Rocks

By

My favourite mock objects library is EasyMock. IMHO, if you need much else for mocking stuff on a new project at least, you’re mocking (read testing) the wrong thing.

It’s uses Javas built-in dynamic proxies, meaning you can mock out anything that is defined by an interface.

I was helping someone to write some tests recently and explining how to use the library when she noted that “it’s like a macro recorder.” I had not thought of it like this but I guess she’s right.

The idea is you create the mock object and then call it in exactly the way you expect the class under test to call it. The cool thing about this is that you get to use the same interface as the class under test. You setup expected method parameters, return values and even exceptions. Then when you’re done setting it up, you call the class under test and EasyMock handles the rest.

As an example, I thought I’d take the clock code and write a test. (P.S. Anyone spot the “deliberate” mistake? Perryn Fowler did.)

public void testThreadInterruptedWithTimeExpiredShouldNotSleep() {
  // Create the mock clockMockControl clockControl = MockControl.createStrictControl(Clock.class);
  Clock clock = (Clock) clockControl.getMock();

  // Create the mock taskMockControl taskControl = MockControl.createStrictControl(Runnable.class);
  Runnable task = (Runnable) taskControl.getMock();

  // Setup an alarm to go off at time=10
  Alarm alarm = new Alarm(task, 10, clock);

  // When run, the alarm should check the current time.
  // We'll tell it that the time=1clock.getCurrentTimeMillis();
  clockControl.setReturnValue(1);

  // This will cause the alarm to calculate the sleep time.
  // We pretend the thread was interrupted suffiently that the alarm
  // time has now expired, time=11, which should cause the task to be run
  // immediately.
  clock.getCurrentTimeMillis();
  clockControl.setReturnValue(11);

  // We want the task to be run once, and once only!
  task.run();

  // Tell the controls we're ready to rock'n'roll
  clockControl.replay();
  taskControl.replay();

  // And away we go...
  alarm.run();

  // Final check to ensure no expected methods are left outstanding
  clockControl.verify();
  taskControl.verify();}

Running this test should demonstrate the bug just nicely, resulting in the following exception (that’ll teach you to write the code without even running it!):

junit.framework.AssertionFailedError: Unexpected method call sleep(-1): sleep(-1): expected: 0, actual: 1
at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:41)
at $Proxy0.sleep(Unknown Source)
at Alarm.waitForAlarmTime(Alarm.java:30)
...

How easy is that! You’ll note that at least 50% of the “code” is actually comments I added for understanding, making it seem a lot longer than it really is.

Some traps for young players though:

  • Don’t forget to call replay() for each control prior to invoking the class under test. If you do forget, you’ll end up java.lang.IllegalStateException: missing behavior definition for last method call on the mock;
  • Don’t forget to call setReturnValue() or setThrowable() on the control after calling a method on the mock object. Again you’ll end up with java.lang.IllegalStateException: missing behavior definition for last method call on the mock; and;
  • It’s a good idea to call verify() on each control at the end of the test just to be sure.

About the only feature I can think of that I’d like added would be for a single control to handle multiple interfaces. That way I can have the ordering of calls across multiple interfaces checked as well. It should be relatively simple as dynamic proxies already support this. Without this feature, there’s no real way to tell if the tasks run() method was called at the correct point in time. I draw the line at creating a dummy interface that extends both Clock and Runnable purely for testing ;-).

Static imports

By

I have no idea which crack smoking monkeys thought this was a good idea. Talk about clash of the namespaces. Has no one ever tried to use java.util.Date and java.sql.Date in the same class? But while we’re at it, can we have pointer arithmetic back as well? Ooo…ooo…how about C#-like properties. Yeah! You know, I’d really like to be able to embed java-byte code directly into my source using some kind of assembler-like syntax too. Imagine how cool that would be!

I take comfort in the fact that large organisations (for whom I’m most concerned) are so slow to move, their developers won’t see JDK 1.5 for at least the next 3 years hehehe.

Oh well. I can see a new checkstyle plugin coming real soon.

Price / performance at what cost?

By

Whenever I find myself participating in the “I love IntelliJ” versus “I love Eclipse” debate, the old “Ya can’t beat price/performance” argument is rolled out faster than you can say “perspectives? what the…?”. So let’s do the math:

price / performance = 0 / anything = 0

or perhaps:

performance / price = anything / 0 = undefined

But seriously, Eclipse would be a great platform if I could just bend my head around to thinking the way Mr. Gamma wants me to.

It’s that old mental model thing. I admit I had the same problem when I first starting using IDEA. It really comes down to what you’re used to. And the fact that IDEA somehow knows what I want to do hehehe

I just thank my lucky stars I can use Eclipse 3.0. I’m even happier I don’t have to use WSAD. Sheesh at AU$10,000 / seat? How many games of golf did the IBM rep have to lose to convince the “Architects” that was a good purchase? ’nuff said!

So right now, my performance is approaching new lows as I reprogramme my tiny wee brain. But I’m getting there. Though, I still sneak home for a puff of the IDEA cigar every night just to feel that rush of endorphins again :-)

Analysis patterns

By

When I first moved over to the cool new world of OO, I just loved the fact that, especially in C++, I could use inheritence to do so many things. I could just create yet another sublcass, override some method/s and bingo problem solved. What I didn’t realise was that I was creating an enormouse mess of brittle, crufty, hard to maintain code. Personally, C++ multiple inheritence didn’t help! But let’s not go there just now shall we :)

So, for a simple problem with some very basic requirements:

  • We have bank accounts
  • We can transfer money from (debit) at most one account
  • We have 2 types of transfers
  • Single funds transfers allow crediting to one account
  • Multi-funds transfers allow, you guessed it, multiple credit accounts

Now, how would you have modelled this? There are of course no right or wrong answers but I’m curious to hear your thoughts.

You see, the most common solution I come across has two sub-classes, one for each type of transfer. One allowing a single credit and the other allowing a collection of credits.

As you’ve probably guessed however, this isn’t my preferred solution. I’d rather see a single class for a transfer with a collection of credits and some kind of constraint class that holds “rules” regarding minimum and maximum numbers of credit accounts.

I’d say the most influential books I’ve ever read to do with software developement, in the order I read them, were:

The last is probably not as well known as the first two but, quite aside from the patterns themselves, it fundamentally changed the way I model problems. For one, I stopped creating ridiculously deep class heirarchies to solve every problem I came across.

It’s been many years now since I read Analysis Patterns but I’ve had cause to refer back to it recently in group modelling sessions. If you’ve not read it I highly recommend that you do.