Tight coupling in OOP


What Is Tight Coupling?
It would help to define exactly what the problem is, in order to solve it.

Tight coupling, in object oriented application, is an abnormal dependency between two unrelated objects. This usually manifests itself in a few different ways; today we're going to talk about the first type: the object creation tight couple.

The Object Creation Tight Couple
Have you ever seen or written code like this?

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

We've all probably observed this. Even if it's in another method besides the constructor, we've all seen code that creates other objects. The culprit here is the new keyword. This keyword creates an object, but the creation of an object tightly couples one object to another. It's impossible to easily swap one object for another.

Solving The Object Creation Tight Couple
There are a few easy ways to solve this particular type of problem. The first is with dependency injection. Dependency injection is the process of inserting an object at runtime, rather than creating it in an object, and looks like this:

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

With this approach, we are injecting the object, which makes it possible to swap the object out with a mock object for testing or another object to modify the application. But this isn't the only way we can solve this problem.

We can also use a factory to create the object we need at run time, but abstract the creation to another object or group of objects (like the Abstract Factory pattern). Using a factory looks like this:

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

Now, the real power of this isn't shown in the constructor; it's shown when the getInstance() method is used in a method that requires it. But, you can easily see the power of the factory here to create an object on demand, yet still follow the best practices of dependency injection and testability.

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