Use statements – Rob Allen's DevNotes


: 7

I was having a discussion on IRC about use statements and whether they improved code readability or not.

The choices

Consider this hypothetical code:


The first snippet is completely unambiguous at the expense of verbosity. Those longer class names make it a little hard to quickly parse what it going on. The second is clearly less cluttered, but is at the expense of ambiguity. Exactly what class is User? I would have to go to the top of the file to find out. Should I use aliases? If so, how should I name them?

This is even more interesting in the context of pull requests where the use statement is already in place in the file. As a result the diff you are reviewing doesn't have the use statement in it, so you have to go a different view to check that the class in use is actually the correct one. If fully qualified class names are used, then the PR's diff is self-contained and easier to review.

Getting advice

As with a lot of things in programming, there are pros and cons, so I reached out to the people who follow me on Twitter and asked them:

There were a number of interesting responses, including:

There seemed to be consensus around the use of use statements. The main reasons appeared to be the ability to see the class dependencies at the top of the file and improved code readability (less clutter).

Some people also pointed out that you can introduce clarity when importing:

If you consistently name your aliases, then the code is shorter and also just as clear. If we take Brandon's approach, then the example above becomes:

Now the "aliases" are codified by the PHP namespace name and so you aren't at the mercy of the developer who names the alias. However, the list of use statements is no longer a list of dependent classes, it's a list of dependent namespaces.

My thoughts

Having thought about all the responses I received and having slept on it, I think that it's preferable to be able to organise your code and name your classes such that when importing we minimise ambiguity. If we reorganised, we could come up with something like this:

We have now flattened our class hierarchy which has resulted in clearer class names. Of course, this is not always possible and in those cases, I think that consistent naming of aliases is the way to go.

Have I missed something obvious? How do you import classes?