The Massive Benefits of Type Hinting

Type hinting is one of those arguments that every developer eventually get’s pulled into. More often then not, the anti-type hinters will win the argument with their standard go-to argument, “it makes the method less flexible”.  Let me explain why type hinting makes your code no less “flexible” then it was before.

Let’s assume we have a standard PHP array, with the names of several pieces of fruit making up the values.

$fruits = ['apples', 'bananas', 'raspberries', 'strawberries'];

Now we want a very simple method for displaying my list of fruits. I’ll leave out the type hint for now.

function listFruits($fruits) {
    echo '<h2>My Fruit List</h2>'; 
    echo '<ul>';
    foreach($fruits as $fruit) { 
        echo '<li>' . $fruit . '</li>';
    echo '</ul>';

Looks simple enough. However, is my code really more flexible because I left out the type hint? I can’t pass an integer, string or Class to this method. In fact, this method only works if you pass an array with strings as the values. Making this method work with ANY data type, would be a complete refactor. I’d most likely have to make several methods that handle each data type, and pass the data around like a hot potato. We would really be getting as far away from KISS as possible.

Now you might be thinking about passing an Object into this method, that implements PHP’s Iterator interface. That wouldn’t work either! This method expects only a single value in the array or object, and that value should be a string (technically it could also be a integer or float, and would print the number out, but it just wouldn’t make much sense).

Let’s add the type hint in now.

function listFruits(array $fruits) {

By making this small change, I’ve not only made my life easier (auto generating DocBlocks will put the array in the DocBlock for you), but you’ve also made the life of other developers easier. They will see that you have specified an array must be passed as the property, and even if they don’t, their code editor or IDE will scream at them.

Even if our little example was blatantly obvious that it needs to take an array, it’s still a great idea to type hint more flexible methods. If you haven’t tested for every possible data type, then just type hint what you want everyone to use, so you don’t create problems for yourself in the future. If you are expecting an Object, and they keep passing an array, you’ll spend about 30 – 45 minutes going back and forth with the person in Github issues, before one of you realizes their mistake. Save both of you some much precious time, and drop the type hint in to start.

Leave a Reply

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