Dependency Inversion is Good
Inversion of dependency is good, it:
- Simplifies unit-testing
- Reduces coupling, allowing software components to be used interchangeably
- Keeps instantiation logic for a given object in fewer places, preventing repetitive code.
For these reasons, I avoid instantiating objects within classes; preferring instead to pass in factory classes as a dependency. However, I am wondering if this is excessive for some types of objects.
Are Value Objects Exceptions?
Value objects are, by definition, simple objects with simple construction.
In my experience, there is rarely any complication in the instantiation logic, unit-testing is not compromised as value objects can be regarded as any other data type, and coupling is not a concern because all classes must rely on data-types of some description (caveat, see My Concern).
Collection Objects too?
A special associated case is that of collection objects.
My opinion is that collection objects, like value objects, require no real instantiation. They are, in effect, a specialised form of array; a value object.
Example:
class PencilCase
{
private $pencils=[];
public function construct()
{
// blah blah
}
public function emptyPencils()
{
$pencils = $this->pencils;
$this->pencils = [];
return new PencilsCollection($pencils);
}
}
class PencilsCollection implements \Traversable
{
public function __construct($pencils=[])
{
// blah blah
}
}
My Concern
In general I have avoided this type of coupling because I may well want to change the package that is providing some of the data types being used; in the example above I may be using a value object provided by Dixon
and then change to those provided by Staedtler
.
This type of refactoring could be expensive.
Question
Should I instantiate value & collection objects with factories and injected dependencies or should I instantiate in-class?
int
is anint
). Not sure about collections; my guess is they should be treated like any other object.