A Quick Controversial Lesson on Type Hints

Let me show you something.

Have a quick look at this code:

Simple display of user id passed into function

Now look at the rest of it:


Yes, it is crappy example code, but you know how I made the mistake? I used my PhpStorm’s parameter autocomplete, which filled in $userId for me, and looked perfectly normal. Since I’m passing in an integer, good chance it will pass all my tests unless I’ve been diligent. (You are being diligent with your tests, right? Thought so.)

This won’t be perfect, but at least it can guarantee that I’m not only displaying an id, but the right kind of id. If you think about this even further, you’ll realize that this is coming from passing object to one another, instead of just procedural “do step 1, do step 2” type thinking.

One lesson I’ve learned the hard way, even when testing, is that you like to write your tests from a clean database. So you make a factory User whose id is 1, and a factory Customer whose id is 1, and two factory Products whose ids are 1 and 2… It is very easy to make your tests pass with the wrong values being inserted if you aren’t careful.

This is the exact same idea behind why this first code is less error-prone than the second:

In both this and the type hint example above, we are not just making sure that the right data type is being used, but also that it is the right right data type.

Now, if the only code you ever work on is your own, written in your own way with all the proper testing and safe guards, you can probably get away without worrying about this as much.

If on the other hand you tend to have to work on code that has been pre-loved by six other developers over as many years, on a team of 4 developers — each with their own naming style, and it is a bit more complicated and messy than my examples above, I would recommend doing whatever little tricks you can to help keep things working and understandable.

Hope that helps!