The transition to a dynamically typed language

The first thing I have to say, is that I love dynamically typed languages. They make it easy to play around with code, and are very productive in many ways. When a programmer that is used to programming in C/C++/Java/C# makes the switch to a scripting language, there is something weird that happens though.

For a part this switch is incredibly easy. I’ve never heard a single programmer complain of no longer having to press a compile button, or no longer having to specify the type for every variable declaration.

int orderCount = 1;


$orderCount = 1;

The hard part is the fact that there is a lot less static analysis that supports the programmer. A lot of decisions that used to be taken at compile time are now done at run time. Which means that if that code is never run, no-one will find out that it doesn’t work. Until it goes live probably.

A simple example of when this needs to be in the back of your head is when renaming or removing a certain function: you’ll have to find all relevant occurrences and fix them yourself. And when the original programmer decided that this method should be called perform(), then you’re going to have a bad time.

Anyway, it’s not like PHP does not have type hints. For example, you can type hint an argument to a function. But what happens when you then call a method that does not exist on that type?

interface Vehicle {

  public function drive();

class Car {

  public function drive()
    echo 'Driving';

  public function break()
    echo 'Breaking!';

function doStuff(Vehicle $vehicle)

What should this code do? In a lot of languages you’d get a compile time error, the method break() isn’t listed in the interface, and thus shouldn’t be called. In PHP, this will just work. So the type hint will make you all warm and fuzzy inside, since you think you know something about this object. But if it walks like a duck, it must be a duck! This is called ducktyping.

Code that is depending on ducktyping can usuablly be a bit improved, in this case you should either add this break() method to the interface, or make the type hint more specific. Though a lot of people in the python corner think that you shouldn’t.

Leave a Reply

Your email address will not be published. Required fields are marked *