A blog by Gary Bernhardt, Creator & Destroyer of Software

Why dynamic typing is useful

23 Dec 2006

Steve Yegge's Parabola has thrown a little more fuel on the static vs. dynamic fire. The comments so far have been mostly constructive, which is a nice surprise. However, there has been some back-and-forth about dynamic typing, mostly concerning why it's useful and what it actually entails. In a recent comment, "Matt" said

"I don't see how software could possibly attempt to handle anything it did not anticipate, except to gracefully fail, which T.S. did."

I've seen this sentiment before, almost always from people whose programming experience is limited to statically typed languages. If that's your background, then you've not seen the wonderful flexibility that dynamic typing adds. Here's a very simple example written in Python. Don't worry - Python is called "executable pseudo code" for a reason!

def process_many(things):
    for thing in things:
        thing.process()

Looking at this, you might expect things to be a list. That's possible, but it could also be a set, or an iterator, or even a dictionary (a hash table). As the programmer, you don't have to worry about it. As long as Python can figure out how to iterate over your things argument, everything will just work.

So, to return to Matt's statement above: this is one way code can handle situations that the programmer never considered. Maybe the guy who wrote process_many never even thought that someone might pass in a dictionary. That doesn't matter; it will work anyway.

Of course, you can get this effect in Java using interfaces. The problem with interfaces is that you have to make decisions about them ahead of time. If you were writing process_many in Java, you might not consider the case of passing in anything but a list. Then, if someone using your code wanted to pass in a set, iterator, dictionary, etc., they'd be out of luck.

This is a recurring theme with static vs. dynamic languages. In explicitly typed static languages, you have to spend time figuring out what type every little thing should have. Then, when you're finally done, there will always be some case you didn't consider, like a hand-written note telling you to call the ticket counter.