[RAD stands for Ruby Ape Diaries, of which this is part III.] This little illustration of a programming idiom is solely designed to horrify newcomers from the Java world, and will look mundane to existing Rubyists. Problem: I want to check a URI to make sure it’s appropriate for use in the Atom Protocol, and if not, report a coherent error message

The problem is, for network operations I don’t want the Ape chasing off after anything but http: and https: URIs. For identifiers, you can use all the tag: and urn: URIs you want. But for GETting and POSTing and PUTting and and DELETEing, http is what you want. You never know, some black-hat might try to convince the Ape to follow a file: pointer.

So there’s this little teeny class called AtomURI with one class method check. You give it a string that you claim is a URI and it either gives you back a URI object, or an error message explaining why it isn’t suitable.

So, in Java, you could actually create an instance with methods for checking and retrieving the result and the error message if any. Alternatively, you could throw an exception if the URI wasn’t kosher (Ruby’s own URI.parse method does this).

Phooey. If the URI is OK, my Ruby method returns the URI object, otherwise it just returns the error message. So the caller does something like this:

uri = AtomURI.check alleged_uri
if uri.class == String
  # oops
  report_error uri
  return
end
request = Net::HTTP::Get.new(uri.path)

I’m quite sure that a seasoned Rubyist would have an even more elegant, idiomatic, and minimal way to do this kind of thing. But having strong, dynamic typing changes how you think.

I suppose in Java, you could kind of do the same, just return an Object and type-check it. But then you’d have to cast, and furthermore, in Java, That Would Be Wrong.

The title is a reference to the term Duck Typing.


author · Dad
colophon · rights
picture of the day
August 19, 2006
· Technology (90 fragments)
· · Dynamic Languages (45 more)
· · Java (123 more)
· · Ruby (93 more)

By .

The opinions expressed here
are my own, and no other party
necessarily agrees with them.

A full disclosure of my
professional interests is
on the author page.

I’m on Mastodon!