PHP in Action

Type hints are more useful for scalars than objects

dagfinn | 06 September, 2008 23:46

Max Horvath has implemented a library for type hinting scalars. That interests me, since I find that type hinting for objects has limited usefulness.

I tried using type hints extensively from an early beta version of PHP 5. I mostly gave up on them for three reasons:

  1. They make refactoring harder since you get lots of dependecies on a particular class name.
  2. Making sure an object is the right class has limited usefulness. If you pass an object of the wrong class to a method without type hinting, you're still alerted to the error the moment you try to call a non-existent method (one belonging to the class it was supposed to be as opposed to the class it actually is). This typically happens early.
  3. My experience is I hardly ever see actual bugs in practice that would have been caught earlier if there had been a type hint. I (nearly) always have good unit test coverage. It may be different if you don't, but that's not an advisable way to live.

I admit that these jugdments are hard to make. I could be wrong, more or less. Type hints are probably useful when code becomes stable enough and at the boundaries between modules. But I still tend to avoid using them until I get an actual bug that might have been prevented by a type hint. Their usefulness is and has to be an empirical question. The purpose of using them has to be catching errors earlier, so if they don't have that effect, there's no point.

For the purposes of this blog post, reason 2 is the important one. The idea is that type hints are more useful for arrays and scalars than for objects. Why? Because they have the potential to catch errors that would otherwise be hard to find or escape unnoticesd. As I said, if you pass an object of the wrong class, you will usually get a "non-existent method" error quickly. The same thing happens if you try to pass an array or scalar instead of an object. But if you try to pass an object instead of an array, an array instead of a scalar or vice versa, you can keep using the passed array or scalar for some time before it blows up. The problem becomes harder to track down. I've used type hints for arrays, and found them more meaningful and less troublesome than object type hints.

One case I've seen in which scalar type hinting would be useful is a simple homegrown date and time object that is initialized by passing a Unix timestamp as an argument to the constructor. A couple of times I've made the mistake of passing an object instead. The ensuing error can be hard to figure out. If I could type hint to make sure it's an integer, that would be helpful.

 
Accessible and Valid XHTML 1.0 Strict and CSS
Powered by LifeType - Design by BalearWeb