SRP states ...
There should never be more than one reason for a class to change.
But why a class? Why not use granularity of a function/method? What instead of separating my functionality into separate classes, I separate it into separate functions?
I don't claim that this works or is advisable in all cases, but in some cases with a few modifications it is fairly similar. When something needs to change I can go to that function and change it. While it may not be applicable to all situations, I often come across situations where I create a new class to single out a responsibility when I can just create a new function inside a class and it will work just as well.
Example -- Before Separation
class ProductDataMapper
{
function findById($id)
{
// data retrieval concern i.e. read info from DB
$data = array('name' => 'Mike');
// data-to-object mapping concern
$productParams = array();
$productParams['name'] = $data['name_column'];
$product = new Product($productParams);
return $product;
}
}
Example -- After Separation
class ProductDataMapper
{
function findById($id)
{
$data = $this->dataConcern($id);
$productParams = $this->mappingConcern($data);
$product = new Product($productParams);
return $product;
}
function dataConcern($id)
{
$data = $db->get("SELECT...$id");
return $data;
}
function mappingConcern($data)
{
$productParams = array();
$productParams['name'] = $data['name_column'];
return $productParams;
}
}
So if My SQL table changes but data remains the same, I only need to change one method ::dataConcern()
. If my binding changes between the schema and object parameters, all I need to change is ::mappingConcern()
.
Why create a whole other classes to handle those responsibilities?