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:
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.
| « | September 2008 | » | ||||
|---|---|---|---|---|---|---|
| Su | Mo | Tu | We | Th | Fr | Sa |
| 1 | 2 | 3 | 4 | 5 | 6 | |
| 7 | 8 | 9 | 10 | 11 | 12 | 13 |
| 14 | 15 | 16 | 17 | 18 | 19 | 20 |
| 21 | 22 | 23 | 24 | 25 | 26 | 27 |
| 28 | 29 | 30 | ||||