The Advantages of Composition

Coupling at a Higher Level

Composition is a term used by software developers to describe a way to create software. It involves "composing objects" by putting them together externally from the objects themselves. Each object accepts other objects as dependencies, and if provided, can reuse the dependable objects functionality to accomplish business tasks.

Testable and Flexible

The technique involves identifying and separating distinct traits into self contained objects that can be reused. Composition works differently than classical inheritance. Inheritance works by extending an asbtraction to make it more concrete. Composed objects are themselves concrete, and self-sufficient. Composed objects can be combined in a number of ways, and combinations. Composition is more flexible than inheritance, but comes with many of the benefits, such as maximum code reuse, as well as additional benefits like Dependency Inversion.

Easy to Re-arrange

Composed objects are easy to re-compose and re-arrange without breaking other abstractions and concretions. If I create a concrete object that sends some text to Twitter:

class Tweet
{
	public function post($text)
    {
    	//...implementation of tweeting text to twitter
    }
}

I can reuse that in many other classes:

class WarnOfZombies 
{
	public function __construct(Tweet $Tweet)
    {
    	$this->Tweet = $Tweet;
    }
    
    public function warn()
    {
    	$warning = "Zombies are Here!!!!!";
    	return $this->Tweet->post($warning);
    }
}

I could also add new functionality to Tweet, and all my classes gain the benefits of that new functionality.

class Tweet
{
	public function post($text)
    {
    	//...implementation of tweeting text to twitter
        return $tweetId;
    }
    
    public function reTweet($tweetId)
    {
    	//...implementation details here
        return $tweetId;
    }
}

class ChewHumans 
{
	public function __construct(Tweet $Tweet)
    {
    	$this->Tweet = $Tweet;
    }
    
    public function respond($id, $text)
    {
    	$this->Tweet->reTweet($tweetId, $text);
    }
}

$WarnOfZombies = new WarnOfZombies(new Tweet());
$id = $WarnOfZombies->warn();

$ChewHumans = new ChewHumans(new Tweet());
$ChewHumans->respond($id, "Nom nom nom");