I’m deviating a little from my XML anglebracket warfare today so let’s all rejoice. Done rejoicing yet? Too bad! I’m moving on. Today’s topic is about writing developer friendly code. Developer friendly code (yes, developer friendly code! How many times should I say it?) amounts to APIs that are actually fun to use. How many of you have ever used JMock? Raise your hand. (Put it down you fool! I can’t see your hand. Besides, you got people looking at you sideways.) Now how about the StringBuffer class? How many of you had fun chaining method calls together to build complicated dynamic Strings? What do these APIs have in common? What’s that you say about return values? Wrong! They’re all alike because you can build slick looking shapes and pictures in your editor as you use them. I once drew the Statue of Liberty with a slew of StringBuffer appends and clever indentation. Besides re-creating works of DaVinci, these APIs make you feel good because… well just because they’re just fun to use. I’m going nowhere with my discussion here so let me elaborate, specifically on JMock. When you write a unit test with JMock it almost reads like pure English. Those clever JMock developers did everything in there power to enforce English-like readability short of requiring you to use a comma between clauses. How did they do that? Well they chose clever method names like once() and will() and making sure that return values from certain methods can be passed into other methods in a way that it builds a sentence in english grammar. They really thought hard about readability and as a result you get to write:
mock.expects(atLeastOnce()).method("updateCounter").with(eq(expectedIncrement))
.will( onConsecutiveCalls(
returnValue(10),
returnValue(20),
throwException(new CountOutOfRangeException("Cannot count past 20")) ) );
And when you supplement that with comments you get:
mock.expects(/*a call*/ atLeastOnce()). /*to*/ method("updateCounter")
.with(/*a parameter*/eq( /*to our*/expectedIncrement))
/*and it*/.will( onConsecutiveCalls(
returnValue(10),
returnValue(20),
/*and finally*/throwException(/*like this*/new CountOutOfRangeException("Cannot count past 20")) ) );
You can filter the comment delimiters mentally (and Intellij Idea helps by coloring them a dull grey) and read the sentence, “mock expects a call at least once to method ‘updateCounter’ with a parameter equal to our expected increment and it will on consecutive calls return value 10, return value 20, and finally throw an exception like this. new CountOutOfRangeException().” I don’t know about you but I get a thrill when I write code that looks as good as I do. (…and I look pretty good for a geek.)
That’s not the point today. I didn’t drag you away from that porn site to preach how good JMock is. Instead I wanted to share a pattern I started noticing in my coding recently. Anytime I get the urge to return void from a method I instead declare the return to be the instance type. I then code “return this;” at the footer of the method and my APIs start to look quite pretty. I’ll give you a tour of an interface that I’m still back-patting myself over. (By the way, it’s never a good idea to feel good about some code you wrote as that’s normally a sign of bad code, but off back patting I go.)
The interface in the spotlight is called XMLDocumentBuilder. I use it to build XML strings from Tabels, Lists, maps, maps of lists, and sometimes the chewing gum from under the table. Here’s a unit test method demonstrating the use of the interface.
public void testGetGreatGrandParent()
{
XMLDocumentBuilder greatGrandChild = getXMLDocumentBuilderFactory()
.createBuilder("greatgrandparent")
.createSubElement("grandparent")
.createSubElement("parent")
.createSubElement("greatgrandchild");
XMLDocumentBuilder greatGrandparent = greatGrandChild.getGreatGrandParent();
assertEquals("greatgrandparent", greatGrandparent.getName());
}
You see here a factory that returns an instance of the XMLDocumentBuilder using a string which represents the root element. You then see a series of calls chained together to create the hierarchy that is the XML document. (You don’t see how I actually hard-coded the implementation in my unit test because I changed that code to a bogus getFactory() call right after I pasted here. I know, that’s cheating, right? Sue me.) Each call to createSubElement() returns the instance that was just created. There are methods defined on the interfacethat allow you to create and walk into a nested element as well as methods designed to let you walk back up the heirarchy. The unit test demonstrates the ability to walk up three levels in the hierarchy in one step. The interface was designed to replace a series of calls the a series of Concretes and interfaces on a specific 3rd party API. The idea was to generalize what we were trying to do while minimizing our number of dependancies. Where the old code had to deal with Node objects, Attribute objects, Documents and the like the revised code performed the same task using a single interface. The code was then generalized and no longer depended on the 3rd party API directly. I then implemented a wrapper around the 3rd party API and hid it behind the interface. In doing so I realized that the API was really not necessary as the majority of the implementation delegated to methods on the interface. (That’s just how powerful the interface was, it practically implemented itself.) There is a small amount of 3rd party code in the implementation which could easily be replaced by some simple custom coding.
So there you have it. A discussion that has nothing to do with XML has ended in a discussion about an XML building interface. I’m really not that big of an XML fanatic, really. I honestly hate XML because of how verbose it is and all the overhead involved in processing it. I’m just like the rest of you anti-XML zealots. C’mon, can I be down with y’all? I made posters and all. They say stuff like “XML is Bad! BAD BAD BAD!”, and “Give a whistle if you can’t stand DSSSL!”, and also “My CORBA service can kick your web service’s Ass!” I guess I should just get to the moral huh? The moral to the story is, the better you make your interfaces the more cool your fellow developers will think you are and then they’ll take you to the bar and get you drunk and then you can write a blog about it where somebody will stumble across your pathetic site and stuff a wad of Franklins in your pocket because they think you sound smart and smart people shouldn’t be without money so here take this $100000 (is that enough zeros?) because you’re so cool. There, that’s the moral. Aesop would be proud! Talk to me people…

I like self-returning methods too, and have been using them more and more of late. A nice article can be found here:
http://www-128.ibm.com/developerworks/java/library/j-jtp04275.html
By: Jim Yingst on June 23, 2006
at 5:30 pm
[...] I linked to my last topic, “Avoid a void” from some Java forums and got some feedback that I’m still trying to interpret. The people on this one forum, who were all smart and stuff, opened a debate using words like othogonal, and referring to concepts like unidirectional and bidirectional method dependencies. I tried to follow. I really did but when I found myself plugging copied text into my online dictionary widget (it’s the little magnifying glass and text box thingy that you can sit in your taskbar on the Linux KDE desktop that tells you what smart people mean when they say stuff like “incommensurable development with pragmatic interfaces and implementations that are adscititious to the project.”) I posted a dumb response in the smartest way possible. In my stoopid reply I attempted to smartly say, “Hey, you guys sound all cool and stuff with the high level thinking and million dollar words but I don’t know what you’re saying. I was just sharing some ideas.” What came out was just as mangled and insignificant sounding as what I was replying to, only my words were garaunteed nonsense. I wanted in on the debate but I was stuck on the sideline feeling like a foriegner sent to his first NFL football game trying to find the goalie. (You know how you swear you know what you’re getting into but then people take it in a whole different direction on a whole new level?) Blew my mind they did. [...]
By: Can’t see nothing but the source code » Wow, I’m dumb… on June 26, 2006
at 10:39 am
[...] Let me explain a line or two from the above example. First off, regarding code style, you’ll notice in my examples I use a mixture of Java style and Groovy style. I tend to avoid semi-colons because they’re not necessary in Groovy. I also avoid parenthisis around method arguments as I can because they too are optional. You won’t see it in the above example but I may sometimes use GPath expressions and groovy style bean property assignments in places. I don’t do so often because I had a scenario where using them didn’t work as expected and since I want to keep the project moving without senseless debugging I’ll tend to use what I know works. The last thing I’ll mention about style is how I avoid void methods. Every method that declares a void return I change to return the current instance or the “this” reference. That’s just a personal preference of mine and you can use your own discretion here. In the example, there is a call to createBufferStrategy() which is a method on the super class java.awt.Canvas. We pass a literal “2″ as the argument. That indicates that we’ll be using double buffering, a technique where graphics are drawn to an offscreen bufferand that buffer is swapped up to the monitor. (The buffering strategy is actually a little more complicated than that but for the purpose of my tutorial that’s as far as we need to know about it.) [...]
By: Can’t see nothing but the source code » Groovy Invaders III on August 7, 2006
at 3:57 pm
[...] What’s really good people? My apologies for not continuing the GroovyInvaders series in a long time. I will pick up on that tomorrow or the next day. I’m getting clowned by my own efforts of refactoring our company project to use Spring dependancy injection. Today I had a hell of a time getting certain BeansFactories to share configs. (A factory for a JMS bean and a factory for a WAR to be specific.) While I think I fixed that problem I got bitten by my own arrogance trying to avoid a void. Because I like to define my beans with all of their setters being self returning Spring decided to ignore all of my flavorful setter methods and throw PropertyNotFound exceptions. I suppose there’s a real valid reason for doing so either that or the self returning idiom isn’t as wide spread as it should be. Whatever the case it looks like I’ll have to make my interface dumber to appease Spring. I’m not happy! [...]
By: Can’t see nothing but the source code » Why you shouldn’t avoid a void on August 14, 2006
at 3:53 pm
[...] I was reading a post titled Avoid a void at http://codeforfun.wordpress.com/ on the subject of using self-returning methods in an API. A very good and informative read (the author has quite a humorous writing style too). [...]
By: viewPosts(); » Blog Archive » Self-returning methods on August 14, 2006
at 9:41 pm
[...] I typically don’t care one way or another about XML or most languages. As a matter of fact, I’ve said before that I’m normally on the other band wagon beating the drum like, “XML is bad! Down with all parsers!” But sometimes I have to make a point when people misunderstand me. My point here is what? I am not here to preach the gospel of XML or any other language (except for maybe Groovy) even though my earlier musings would have you believe otherwise. However, to call such a language a “general pain” is a bit of an overstatement, one which could indicate lack of understanding or familiarity. XML has its place just as does every other language and it is no more painful to use than say, PHP. T, I ain’t mad at’cha but you should know that when you knock the technology that stands behind my weapons of mass obstruction that I ain’t gonna sit idly by either. Break me off somethin’… [...]
By: Can’t see nothing but the source code » Ouch! My XML Hurts… on August 21, 2006
at 9:39 pm
[...] him and others such as Kathy Sierra who taught us the importance of coding like a girl. I’ve taken a stab at writing fluent interfaces in the past and later learned that practicality sometimes becomes more [...]
By: GSpec for Java BDD « Can’t see nothing but the source code on April 11, 2007
at 8:13 am
[...] and functional languages. Mastering each skill gives you the ability to consider such things like expressing a domain specific problem in a more imperative language rather than conforming the requirements to the language’s syntax. Expressing high level ideas [...]
By: Why so many languages? « Can’t see nothing but the source code on April 17, 2007
at 10:05 am