January 27, 2008

HELP: Developing with WebSphere

Listen to this articleListen to this article

I have to know. Is it just me or is the compile, deploy, debug cycle with WAS just so ridiculously long and slow that it's practically impossible to do anything productive with it? Does anyone ACTUALLY use WAS for development? If so, how do you manage? If not, what do you use instead and how do you then make sure that it still runs in WAS when it can take 10 minutes just to re-deploy an application? Is there some secret to determining why WAS silently rolls back transactions, for no apparent reason (WLTC0033W and WLTC0032W), before control has even returned to the container and with no exceptions; doesn't seem to be able set transaction isolation levels on SQL Server but instead creates extra connections with the correct isolation level (READ_COMMITTED) leaving the original one handed back from the DataSource as the default (REPEATABLE_READ); and mysteriously times-out waiting for Oracle connections from a pool of 10 even it only ever seems to need at most 3 when the maximum pool size is set to 100!

October 25, 2007

A Diamond in the Rough

Listen to this articleListen to this article

No, for once this has nothing to do with Ruby (deathly silence) rather, it concerns some problems many people have experienced when trying to use JNDI resources from Quartz jobs under Websphere.

In short, Websphere does not propogate any java:comp/env/ JNDI context to application created (ie non-container) threads. This is apparently by design with the upshot being that if you're using quartz you won't be able to use JDBC data sources from any jobs.

There a number of forum topics that discuss this problem along with various solutions including "use a 3rd-party connection pool instead." Hardly music to the ears when you've just spend the last 3 months converting a customer's entire application over to using JNDI resources. However, after much Googling, I happened upon an article that ultimately solved the problem in a Websphere-friendly manner. It even comes with sample code so you can get started almost immediately.

In essence, the solution makes use of Websphere's Asychronous Beans (and the Work Manager in particular) as a sort of thread pool. We then took this idea and adapted it around the use of Quartz's pluggable ThreadPool.

The final twist was the need to support both Websphere and Tomcat seamlessly without resorting to either build or deployment time configuration. For this we simply created a ThreadPool implementation that looks up the Work Manager in the JNDI context. If it exists, we assume that we're in Websphere and go from there; otherwise we use the default Quartz implementation and hope for the best :)

March 28, 2007

Leaking Locks

Listen to this articleListen to this article

Spoiler: JDK 1.5—and near as I can tell 1.6 even though it's supposed to be fixed—have a pretty fatal memory leak when using java.util.concurrent libraries.

How do I know?

Well, besides finding the earlier link via our good friends at Google, we recently switched from using the backport to the standard JDK libraries and the throughput of our application under load rapidly approached zero.

After spending some time creating a a quick-and-dirty load test on my own machine, I found I could easily replicate the problem with the added bonus of java.lang.OutOfMemoryErrors in under a minute. Running it under a profiler confirmed as much with the culprit being java.util.concurrent.locks.AbstractQueuedSynchronizer$Node.

"Never" cries the guy we work for. "Doug Lee's stuff has been around for a long time and I'll bet his stuff works and you guys have screwed something up!" he continues.

We all agreed and decided to replace the locking code in the class I'd just created (and presumably screwed up) with some good old-fashioned synchronisation.

Nope. The problem persists but it's not as bad this time. We clearly "fixed" something but not everything. Hmmm.

On further investigation we realised there was still some code in the call chain using the concurrent stuff so we decided, just for laughs, to revert back to using the concurrent stuff but use the backport libraries instead.

Voila! Suddenly the load test exhibited exactly the expected behaviour: no out-of-memory errors; no grinding to a halt; nice see-saw memory usage; and using only 2MB of heap instead of, well, as much as it could get (>64M in our case).

Stunned, we went back to the default JDK version. Yup! Problem is back and not just in our own locking code either, we noticed the problem in much of the concurrent classes including the collection implementations.

The good news is that using backport we now have a build that works.

The scary part is that I can only presume some Sun engineer decided he knew better and screwed the pooch right royally on this one.

March 05, 2007

Monitoring Java Processes under Mac OS X

Listen to this articleListen to this article

Update: After a bit of googling I discovered that it's a bug which is fixed in Java 6 (Mustang) and relates to, wait for it, user names containing an underscore. Go figure!

So today, after I don't know how many years of doing Java development, I find out there is a command to list all the running Java processes. It's available on all platforms I could find and it's called jps. On most platforms it'll display something like:

1170 Jps -lm
1162 org.apache.tools.ant.launch.Launcher -cp  dist

Except under Mac OS X where you'll get something more like:

1170 Jps -lm
1162 -- process information unavailable

Pretty bloody useless!

So, I wrote a little ruby script to simulate the desired behaviour as much as possible (by using the built-in jps to collect the process ids; then filtering the output from ps accordingly):

#!/usr/bin/env ruby

require 'set'

pids = Set.new

`#{ENV['JAVA_HOME']}/bin/jps`.each_line do |line|
  pids.add($1) if line =~ /^(\d+) /
end

`ps -x -w -w -o pid,command`.each_line do |line|
  print line if line =~ /^ *(\d+) / && pids.include?($1)
end

Which, when run, produces output similar to (line continuation not included):

1162 /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home/bin/java \
  -classpath /opt/local/share/java/apache-ant/lib/ant-launcher.jar \
  -Dant.home=/opt/local/share/java/apache-ant \
  -Dant.library.dir=/opt/local/share/java/apache-ant/lib \
  org.apache.tools.ant.launch.Launcher -cp  dist

Granted it does produce lots more output than standard jps but it does at least produce something useful to look at when monitoring Java processes. Best of all, it means we can automate the monitoring in a manner that works across most platforms.

If anyone has a Better Way™, I'm all ears.

February 14, 2007

Semantic APIs

Listen to this articleListen to this article

I was chatting with my brother today (somewhat of a professional student with degrees in neuroscience, physics and maths) about software development. I was explaining how yesterday had a been a rather unpleasant day working out how to integrate with Crystal Reports. You see, what I wanted was an interface that looked something like this:

CrystalReport report = new CrystalReport("report.rpt");
report.setParameter("Posting Year", "2007");
report.setParameter("Account Number", "5678");

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

report.writeTo(outputStream);

outputStream.close();

Only instead what I got was this:

ReportClientDocument document = new ReportClientDocument();
document.open(_reportName, OpenReportOptions._openAsReadOnly);

DataDefController dataDefController = document.getDataDefController();
ParameterFieldController parameterFieldController = dataDefController.getParameterFieldController();

parameterFieldController.setCurrentValue("", "Posting Year", "2007");
parameterFieldController.setCurrentValue("", "Account Number", "5678");

InputStream inputStream = document.getPrintOutputController().export(ReportExportFormat.PDF);

int b;

while ((b = inputStream.read()) != -1) {
    outputStream.write(b);
}

inputStream.close();

document.close();

The first is nice and semantic; it's pretty obvious what the code is doing. The second requires you to read, very carefully, each line in order to work out what is going on. Talk about leaky abstractions. Apparently my Document's connected to my, DataDefController; my DataDefController's connected to my, ParamaterFieldController; ...

My brother drew an analogy with explaining to someone how a telephone works. In the first case, we've gone through a very simple explanation with just enough information to allow someone to have a go themselves; in the second example, we're now explaining how the spin of each electron determines the probability of it going down the wire and thus contributing to the current that ultimately makes the phone call possible.

At first I was concerned: Having just recently ranted (for the umpty umpth time) that developers don't seem to understand even the most fundamental principles of software development, here I was lamenting the fact that most APIs weren't simple enough. My brother then asserted that perhaps the reason software is (in general) so poorly written is precisely because the APIs we are forced to use are so primitive. That because we are forced to follow so many steps in achieving something that is conceptually so simple (such as producing a report) that the likely-hood of failure is much greater.

The scary thing is, this is certainly not an isolated example. Have you ever tried using the javax.mail packages? JNDI anyone?

In the end, I wrote a class named, unsurprisingly, CrystalReport with an interface exactly as in the first example and implemented almost exactly as in the second. But I seem to need to do this quite a lot when dealing in the "Enterprise" Java world.

October 27, 2006

Plugging a Team City Security Hole with a Little Obfuscation

Listen to this articleListen to this article

If you're not sure what I'm talking about, have a quick read of my earlier post.

The trick—as far as I can tell—to plugging the hole is to: disable guest logins to the server; and ensure each build configuration requires each agent to have a secret environment variable set to a, secret, value—something like a generated WEP key for example.

This seems to be a reasonable solution until JetBrains figures out a better mechanism. That said, in many respects, it's not that different to the way WEP authentication works anyway.

Oh, an why the need to disable guest login? TeamCity shows all logged in users—yes, even guests—which agents aren't compatible and, in particular, why.

Of course there may well be a way to interrogate programatically what the requirements are in which case, you're hosed anyway :(

October 25, 2006

A City Full of Code Thieves

Listen to this articleListen to this article

After nearly falling over at the ease with which I could use TeamCity to crush helpless machines, it suddenly occurred to me that I may have found yet another security hole.

As you probably already know, the TeamCity server doesn't do the builds itself; rather, it farms the work off to build-agents. You can connect as many build-agents as you like to a server: simply download (or otherwise obtain) a copy of the build-agent code; configure it to point at the server; and start it up. No server-side credentials are necessary.

When a build is required, the server checks out the source code and sends a delta to the agent. This has a number of benefits, one being that you can securely configure the source-code-repository credentials in one place—the server—and the agents will be sent the source code as needed. This also poses a potential security risk.

Let's imagine that disgruntled developer X from our previous exploit wants to obtain a copy of source code from a repository for which he has no access but for which he knows there is a TeamCity build. He simply configures his build-agent to connect to the server and waits. When the server decides it's his machine's turn to do a build, the server dutifully sends him a copy of the source-code...!

October 19, 2006

A City of Trojan Ants

Listen to this articleListen to this article

As much as I've bitched about IntelliJ performance, and as much as I wish I didn't have to do Java development on a regular basis, the fact of the matter is I do and IntelliJ just rocks my world in terms of features—I guess I'll just have to wait for the new Core 2 Duo MacBook Pro to address the performance issue— so today I purchased a copy of the latest version.

IntelliJ 6.0 comes with TeamCity, a continuous-integration/build-server tool. It would appear that TeamCity isn't just restricted to building applications, but could really do anything assuming you do in ant script.

TeamCity has the concept of build agents so all the real work is farmed off to other machines, so I setup my machine as a build-agent which required opening up a port—9090 is the default—through the firewall on my machine. This immediately rang warning bells in my head: I had just run the agent using sudo and any application run using sudo that needs ports opened up scares me. In the end I realised I could easily run the agent as a non root user and all was happy. Excellent!

That did get me thinking however, as to what would happen on say, M$ Windoze machines where developers typically run with administrator priveleges or even poor saps like me who had stupidly run using sudo or even just as my own login.

Imagine a team of 20 developers, all of whom have obligingly run a build-agent so that their spare CPU cycles don't go to waste. One day developer X becomes disgruntled with his employer and decides to run wild. Before he goes home at night, he checks in a change to build.xml. Not a large change, nothing special, just a one line change that recursively deletes everything starting at the root directory or even just the user's home directory.

This change quickly makes it to the TeamCity server and then out to a build machine which dutifully executes the script, destroying everything taking down the machine with it!

Thankfully, the TeamCity server detects that the agent has gone down and, doing it's best to utilise the resources at its disposal, re-schedules the build on the next available agent...

To be fair, TeamCity isn't really to blame, if a developer runs build.xml without first ensuring that it does nothing macilicious, it's really no different to running an un-verified shell script. TeamCity just makes it really easy to setup agents and ensure that the script is executed.

Me thinks it's time make a seperate, locked-down account for running the build-agent!

October 01, 2006

Zip and Preserve File Permissions with Ant

Listen to this articleListen to this article

Yes, it's been a while since I posted an entry related to Java! Believe it or not, we still do Java development, lots of it in fact, but it's mostly large-scale re-factoring and cleanup work on what can best be described as "legacy" applications so there's rarely much if anything to write home about. That said, I have a couple of posts just itching to be written when I find some time. Until then, a relatively short entry will have to do :)

A client distributes one particular Java-based web application to hundreds of customers using a zip file. The distribution contains, among other things, the war file and some scripts for database migration, etc. It's these scripts that cause us some headaches as they need to have execute permission. The problem arises because Ant's built-in zip task specifically doesn't handle file permissions. So, naturally, we concocted our own using macrodef:

<macrodef name="zipdir">
    <attribute name="destfile"/>
    <attribute name="sourcedir"/>
    <echo>Building zip: @{destfile}</echo>
    <exec executable="zip" dir="@{sourcedir}">
        <arg value="-qR"/>
        <arg value="@{destfile}"/>
        <arg value="*"/>
        <arg value="-x *.svn* "/>
    </exec>
</macrodef>

This simply calls the operating system's—read *nix—zip command to compress the specified directory thus preserving all the file permissions that SVN lovingly maintains.

January 09, 2006

Databases: A Necessary Evil?

Listen to this articleListen to this article

It's an attitude that I see all too often in developers, especially those that label themselves Object-Oriented Purists who are supposedly capable of precise, rational thought, above and beyond that which we might expect from your mere mortal developer.

Ever since my little rant on the subject over a year ago now I have been tempted time and time again to write something more but each time I go to put finger to keyboard I'm overwhelmed with a sense of resignation to the fact that when it comes to relational databases, most people just don't get it. If I only had a dollar for every time a developer has adamantly told me that foreign keys are a waste of time and that somehow primary keys are a neccessary evil to satisfy the requirements imposed by the database so that we can look up a record. "Why would I need all that nonsense?" they chortle rhetorically, "my application handles all that stuff just fine." Sure it does, so prove it!

What I find even more frustrating is the FUD spread by those I expect to know better. Case in point. I was doing some reading of old Ruby On Rails—yes, my shiny, not so new, toy—newsgroup postings when I came upon this from none other than Mr. Rails himself:

"And let it be no secret that I consider the database a necessary evil for the object-oriented domain model. Not the other way around. Hence, when given the choice between implementations that pit OO model against database purity, I will almost always side with the OO model."—David Heinemeier Hansson

Now the statement just quoted was apparently a justification for Single Table Ineritence and the absence of Mutliple Table Inheritence in rails. Fine. I have no issue with this at all. In fact one of the things I like about Rails is the fact that it is unashamedly "Opinionated Software": stuff works the way it does in Rails because, well, because that's the way someone decided it should. So why shy away from this with some spurious argument about what is/isn't good database design? Why not just admit that it's a personal preference and indeed that's the real reason it's like that? Would you consider Active Record a necessary evil or simply a design choice? I guess it depends who made the choice ;-)

So anyway, let's clear a few things up. Firstly, I'm fairly sure that when he (DHH) says database what he actually means to say is relational database—surely he doesn't mean Object-Oriented Database? Secondly, even though he means to say relational database, what he actually should be saying is SQL database—believe it or not there's a BIG difference!

Admittedly C. J. Date is not the most exciting read for many people but if you take the time to read some of his work on Relational Database theory, you might be compelled to re-consider your notion of the so-called "impedence mismatch" between Object-Oriented Design and Relational Databases:

"... As far as I'm concerned, an object/relational system done right would simply be a relational system done right, nothing more and nothing less."C. J. Date

I found it fascinating when I spent some time at a university many years ago that database theory was the least popular subject. Maybe it's just me? Maybe I really enjoy the subject because I see elegance and simplicity and yet enormous power in Relational Databases and it Just Made Sense™.

Relatonal Databases surely aren't as sexy as Ruby or Rails but neither are they glorified record management systems. They are very precise and provably correct repositories for our data. So, do what you will with databases, treat them as evil if you wish. but I think it behooves us to try and understand what we actually think we've supposedly moved beyond.

Update 18 January 2006: Primary Keyvil, Part I

December 28, 2005

How To Write eql?() in Ruby

Listen to this articleListen to this article

So, as I've been delving into Ruby more and more of late and I needed to write an eql?() method for one of my classes. (eql?() is the Ruby equivalent of equals() in Java.)

Understanding how to write an equals() method in Java is one of the most fundamental yet poorly understood practices (if you're not worried about equals() or hashCode() then I suggest you never use a HashMap) and I wondered if the same was true of Ruby.

The most common mistake looks like this:

public boolean equals(Object object) {
    if (this == object) {
        return true;
    } else if (!(object instanceof MyClass)) {
        return false;
    }

    MyClass other = (MyClass) object;

    return this.x == other.x && this.y == other.y;
}

Spot the mistake? It's subtle yet very VERY wrong. Thankfully—now that we've largely managed to get over our obsession with deep inheritence hierarchies—it's effects aren't felt that often. The problem is that equals() needs to be symmetric: a.equals(b) should return the same result as b.equals(a).

Now, imagine a class Person with attributes of name and address and another class Employee extends Person with an extra attribute of company. Given the previous implementation of equals, what do you think the chances that the following two statements will return the same result?

person.equals(employee);
employee.equals(person);

So anyway, unlikely or not, it's still no excuse not to be precise so, in Java the canonical form of an equals() method should look roughly—give or take some formatting and style—like:

public boolean equals(Object object) {
    if (this == object) {
        return true;
    } else if (object == null || getClass() != object.getClass()) {
        return false;
    }

    MyClass other = (MyClass) object;

    return this.x == other.x && this.y == other.y;
}

Now we're comparing based on the actual class and as such the implementation is symmetric; no more problems.

Assuming I still know next to nothing about Ruby, I decided I wouldn't let my Java habits get in the way of learning something new so I searched the 'net for some examples of how to implement eql>().

After failing dismally to find anything non-trivial, I realised that Rails probably had something in ActiveRecord::Base and I was rewarded with:

def eql?(object)
  self == (object)
end

def ==(object)
  object.equal?(self) ||
    (object.instance_of?(self.class) &&
      object.id == id &&
      !object.new_record?)
end

Nothing too outrageous: eql?() simply delegates to == (nice syntactic sugar); and == does pretty much the same thing as we would have done in Java only a little more terse. (object.instance_of?(self.class) is Ruby's way of saying getClass() == object.getClass(); the Ruby equivalent of Java's instanceof is kind_of?().) We could easily re-write this—although I wouldn't in practice—as:

def ==(object)
  if object.equal?(self)
    return true
  elsif !object.instance_of?(self.class)
    return false
  end
  
  return object.id == id && !object.new_record?
end

So it seems—I trust the Rails guys to get this stuff right— that the same rules apply in Ruby as in Java. (I had no real reason to suspect otherwise but hey, it s nice to have it confirmed.)

Now if only someone could explain to me why Hash#reject() and Hash#select() aren't symmetric: one returns a Hash; the other an Array.

December 17, 2005

The Ruby Way(tm)

Listen to this articleListen to this article

I can't help but be amused at the number of times I see the term "The Ruby Way" (or similar) used as a euphemism for "Better than {Java,C#,Python,Perl,etc.}" It seems to be one of those terms (like "Un-Australian" and "Un-American") that can be used to support or attack anything based largely on personal preference.

Case in point: The discussion and ensuing ruckus over Humane Interfaces. What seemed (to me at least) to be an interesting talk on the subject rapidly (as seems to happen all too frequently) into a "mine's better than your's" sledging match.

Unfortunately, Fowler did begin his discussion with "Hanging around the ruby crowd..." and followed that up with "...compare the list components in Java and Ruby" which amounts to pouring gasoline on a bbq. However, what almost everyone fails to see (or possibly I fail to see that they see) is that the concept has almost nothing to do with the underlying language and far more to do with the people (surprise surprise).

Java is full of Swiss-Army classes as is Ruby. Ruby seems to have some very intelligent and articulate pracitioners as does Java. In many ways, Ruby (like Perl) seems to almost encourage bad habits in those less versed in The Ways™. Java OTOH attempts to prevent these same problems and yet creates a whole slew of others.

Disclosure: I like Ruby, alot! but I don't hate Java as a consequence. In fact I find that besides some really nice language features that I really like, I don't find that I think that much differently in either. Then again, I've never liked Struts, I've put up with Hibernate and left the J2EE stack along time ago. Alas, ActiveRecord is not much better (yet). It lacks many things that I've come to appreciate in ORM tools but, in its defense, it's still relatively early days and what is there is relatively clean (from the point of view of one using the library) but take a look at the code and tell me there aint a whole lotta spaghetti in there!

Most people (probably myself included) don't get software development, don't get OO, don't get "it" in general. So let's not get sucked into thinking that somehow the language is to blame. Sure it has an influence but honestly now, horses for courses: People think differently, taste differently and smell differently. Get over it!

Maybe look at yourself first and ask the question "Do I get what they intended?" If you think the answer is yes, then ask again. If the answer is still yes, then how about taking aim at the people involved in creating the frameworks next. The underlying language is a very soft target.

First come up with a definition for "good" and then prove to me there is a direct correlation with the language.

November 06, 2005

Mocking my Visitors

Listen to this articleListen to this article

I mentioned in a comment earlier this week that I like Builders as they allow me to separate out the ickyness involved with construction from my nice pristine objects. Besides anything else, it allows me to layer on functionality: first implement the domain objects, assembled by hand for testing purposes; then create another layer—the builder—that will automate the construction process.

Of course being the good little TDD weenie that I aspire to be, at some point I want to test that the builders are generating the correct structure.

IMHO, the utterly evil-broken-and-wrong approach is to expose all the properties on all the nodes in the graph—I use the terms node and graph generically here to refer to objects related in some fashion—for reasons I've harped on about more than enough.

Another approach—that maintains encapsulation—is to implement equals() for all the nodes in the graph. The idea for testing then is to create the expected structure by hand (just as I had already been doing) then use the builder to create another and assert that the two are identical. I have actually used this approach before and while it worked just fine, it never really felt Good™. I'm not sure why; just an intuitive ookyness.

More recently though I tried a different approach: using a visitor. Again the approach was similar: constructed the expected structure by hand; then use the builder to make another; and finally assert that the two are identical. This time however, the idea was to traverse the expected structure and match, node-for-node, with the actual. The neat thing about this approach though was that because my visitor class was an interface, it was trivial to use EasyMock to do all the grunt-work for me. (EasyMock also allows mocking classes however I still prefer interfaces.)

The idea is to create a mock visitor using EasyMock and pass that to the accept() method of the structure I had created by hand to set-up the expectation. Once that was done, I could then simply pass the same mock to the accept() method of the structure constructed by the builder:

public void testBuilderMakesIdenticalStructureToOneBuiltByHand() {
    // Create the two structures
    Node createdByHand = createByHand();
    Node createdByBuilder = createByBuilder();

    // Visit the one created by hand to set-up the expectations
    NodeVisitor visitor = EasyMock.createStrictMock(NodeVisitor.class);
    createdByHand.accept(visitor);
    EasyMock.replay(visitor);

    // Visit the one created by the builder to verify
    createdByBuilder.accept(visitor);
    EasyMock.verify(visitor);
}

private Node createByHand() {...}

private Node createByBuilder {...}

Note: I'm using the latest version of EasyMock that supporst JDK 1.5 generics however I'm not (nor will I ever be) using static imports as suggested in the documentation!

This time, it felt Good™. I could use the same visitor for testing, reporting and persistence, all without the need to break encapsulation.

Now while I'm really not keen on igniting a religious flame-war over mock objects in general nor mock object libraries in particular, the fact that EasyMock works against the real interfaces—as opposed to using string descriptions ala JMock— was a huge advantage in this case.

October 19, 2005

Domain Specific Languages: Objective-C, Ruby and Java (and Groovy)

Listen to this articleListen to this article

I'm forever trying to "improve" my coding and design skills; I say "improve" because there is always the risk that I'm making changes for change sake. One thing I really try hard to do is remove any notion of getting/setting properties of objects and instead focusing on behaviour.

Now I've always tried hard to do this but it's a skill that definitely takes some time and constant practice. TDD certainly has made my life easier by giving me some tools for this but more recently I've really been making an effort to try and "design" my classes in a way that creates Domain Specific Languages (DSL). DSLs enable you to write code that is hopefully more readable and understandable and therefore easier to write, debug and maintain. (At least that's the ide in principle anyway.)

I use a variety of languages in my day-to-day work and I've found that the effort required in creating a DSL to be vastly different depending on the language. Of the few languages I've actually used in anger (Smalltalk unfortunately not being one of them) Objective-C really does provide a nice syntax for creating DSLs (once you get your head around the square brackets).

For example, take the age-old problem of transferring money from one account to another. In Objective-C, assuming we have an Account class with a transfer() method, we can write something like this:

id source = ...;
id destination = ...;

[source transfer:20.00 to:destination]

* Using floats for currency is generally a bad idea but it'll do for illustrative purposes here :-)

Notice the use of named parameters to really help convey the intent. This is actually an optional feature—you can still use positional arguments if you like—but one I use exclusively.

The transfer() method might look like this:

-(void)transfer:(float)amount to:(id)destination {
    [self debit:amount];
    [destination credit:amount];
}

Again, ignoring the unfamiliar method declaration (you'll just have to trust me when I tell you that you do get used to the language and even love it), it's all pretty nice and readable.

Essentially, when calling the method, the identifier that preceeds a colon serves as the name of each argument—ie as used by the caller— with the method name itself serving as the name of the first argument and to for the second.

Once inside the method, the identifier after the colon serves as the name of the argument to be used: amount and destination.

All up, Objective-C is very concise and allows for the creation of fairly nice DSLs without much effort at all. In fact from what I can tell, most Objective-C code turns out to be more-or-less DSL-like; it's typical to see methods calls that look like:

[report printTo:printer withPagination:YES]

The next example I whipped up uses Ruby. Now, I have to admit that I have all of about 3 days of Ruby experience so if you can come up with a better way please, please, please let me know. So, caveats aside, here is the same example in my bestest Ruby, again starting with the usage:

source = ...
destination = ...

source.transfer :amount=>20.00, :to=>destination

This uses a ruby hash—an associative array like a HashMap or Hashtable in Java. You usually need to wrap the hash definition in curly-braces but this can be omitted when the hash is used as the last—or only—parameter.

Now for the method itself:

def transfer params
    amount = params[:amount]
    self.debit amount
    params[:to].credit amount
end

Pretty good really but I still have a preference for the Objective-C use of named parameters. I did read in Programming in Ruby that named parameters was to be a feature of Ruby at some point but hasn't yet made it. I also read somewhere recently that Ruby 1.9 will have a slightly simpler calling syntax so the invocation will look like this:

source.transfer amount:20.00, to:destination

The only Ruby-based DSL I know of is Rake but again my experience with Ruby is somewhat limited.

And finally Java, IMHO the ugliest of the bunch. To achieve something similar in Java seems to me at least (and again, somebody prove me wrong puhlease!) that named parameters with an even remotely useful syntax requires a combination of inner-classes and method chaining. So, to achieve a calling syntax like this:

Account source = ...;
Account destination = ...;

source.transfer(20.00).to(destination);

Requires something at least as complicated as this:

public class Account {
    ...

    public Transfer transfer(float amount) {
        return new Transfer(amount);
    }

    public class Transfer {
        private final float amount;

        Transfer(float amount) {
            this.amount = amount;
        }

        public void to(Account destination) {
            Account.this.debit(amount);
            destination.credit(amount);
        }
    }
}

The best example of a Java-based DSL that I can think of would probably be JMock.

And finally, by popular demand, a Groovy example. Groovy currently supports named parameters for calling methods that accept a Map so the calling syntax is a lot like Objective-C:

def source = ...
def destination = ...

source.transfer(amount:20.00, to:destination)

The transfer() method itself then becomes something like:

void transfer(params) {
    def amount = params.amount
    this.debit(amount)
    params.to.credit(amount)
}

Which looks unsurprsingly like Ruby. Alas, I have no real-world example of a Groovy-based DSL to show you.