Stop calling Interfaces Interface

Stop calling Interfaces Interface!

It's relatively common in the PHP industry to have a very maddening tendency to overcomplicate what should be a simple enough thing. Naming. Of course I know the old adage 'naming is hard' because naming is hard. But there are a few things that make it harder and teach newer programmers what is I believe bad practice.

This all started with Zend and Symfony back in the mid to late 2000s. Ruby on Rails was the new big thing and PHP didn't really seem to have an answer having only added visibility support relatively recently (5.0 if you're curious). Interfaces were something new as well, and for many developers PHP was their only language. So the Frameworks started, the most prominent ones being Synfony and Zend. The first problem was that there was no namespacing, so we had ridiculous class names like ~Zend_Model_View_ViewHelperAbstract~ which made your code utterly maddening to read. But this also started the first problem, calling things what they were in the code as well as in the overall logic. For example:

abstract class ViewHelperAbstract {
    ...
}
interface ViewHelperInterface {
    ...
}

So then if you're type-hinting in your code:

function doThing(ViewHelperInterface $viewHelper);

So what, to the reader does the Interface part actually add? It tells you there's an interface which should have implementations to give the functionality that you require. How is that helpful? The calling code doesn't care what it is that is providing the functionality, just that it's there. It can also cause this problem:

class OnlyEverOne implements OnlyEverOneInterface {
   ...
}

Seems fine right? And in most cases it will be, further classes will implement the interface and everything keeps on working. However, you've got an interface which you don't need. You should only add interfaces when you actually need them. If you've only got one implementation, why do you need an interface? Yes you might have further use cases in the future but for now it's just taking up time, space and memory (Any class in PHP takes up 1KB of memory just to define it). In the future, you can replace the original class with an interface and add the more specific classes in a refactor, which requires almost no changes in your typehints or calling code:

class OnlyEverOne {
   ...
}

function doThing(OnlyEverOne $one)
{
    ...
}

Becomes:

interface OnlyEverOne {
   ...
}

class OnlyEverMysql implements OnlyEverOne {
   ...
}

class OnlyEverMongoDb implements OnlyEverOne {
   ...
}

function doThing(OnlyEverOne $one)
{
    ...
}

Following these rules should reduce the amount of code you have to write, make your code easier to read and force you to make better naming decisions. So instead of having ~DatabaseLookupInterface~, have ~DatabaseLookup~ which is implemented by ~MysqlDatabaseLookup~ and ~PostgresDatabaseLookup~. Name your things what they do, rather than what they are.

Tags: php