The Type Hint Tight Couple

Anybody who does object oriented development quickly learns about type hinting - the process by which you can indicate to one object another object it should expect. Remember this example from the last post?

<?php
class MyClass() {
  public function __construct(MyObject $mobj) {
    $this->myObject = $mobj;
  }
}

But type hinting alone is not sufficient to loosely couple our objects. In fact, even though we are injecting our dependency in the initial example, we're type hinting on a concrete object, meaning that we are tied to that specific object for all future iterations. Sure, we can mock it for testing (which is an advantage), but we can't easily subclass it and use it elsewhere.

Fixing the Type Hint Tight Couple
It's easy to fix this particular tight coupling problem. To do so, we can draw back on our knowledge of SOLID principles, namely the Dependency Inversion Principle, which states:

Objects should rely upon abstractions, not concretions.

Fixing this tight couple requires only that we abstract the creation of the interface from the implementation of the object, and then type hint on it. For example:

<?php
interface MyObjectInterface {
  // some methods to define interface in here
}
class MyObject implements MyObjectInterface{
  // The implementation of the interface
}
class MyClass{
  public function __construct(MyObjectInterface $mobj){
    $this->myObject = $mobj;
  }
}

So, here instead of relying solely upon MyObject to type hint, we can now type hint on the interface, MyObjectInterface. This loosely couples our objects, because MyClass no longer cares about the implementation of MyObject; it only cares about knowing the right interface!

So, do all my objects need interfaces?
In short, no, they don't. The illustration I've provided is for objects that might have reuse potential later on, or are part of a library; when you're working with specific objects that are unlikely to change, there may not be a need for this level of decoupling.

Remember, the principles of object oriented design (like loose coupling) are about offering best case solutions, not final solutions or absolute hard-and-fast rules. It's up to you, the designer, to make good choices.

Comments

Popular posts from this blog

Navigating the Jungle of Web Traffic: A Technical Team Lead's Guide to "I'm a Celebrity, Get Me Out of Here"

TCP Handshake over IPv6

The Vital Importance of Secure Wi-Fi Networks