PHP Class Cohesion and Separation of Concerns

Separation of Concerns (SoC)

SoC means that you try to separate objects by what they should be really concerned about and is a design principle that splits an application up into its relevant categories (concerns).

Cohesion

Cohesion is the extent to which proximate procedures are related to one another. Highly cohesive Object oriented designs are focused and organized in related modules. Learning about “concerns” is important in determining how to organize functions and classes to be highly cohesive. If methods and classes are highly cohesive, you are able to easily split off entire groups without affecting the design. Designs with high cohesion offer the opportunity for lower coupling.

When a design has low cohesion, it has classes and methods that are not grouped well. To avoid low cohesion don’t write relatively generic classes AND follow the single responsibility principle.

Low Cohesion


class Utils
{
    public static function formatAddress($formatType, $address1,
        $address2, $city, $state)
    {
        return "some address string";
    }

    public static function formatPersonName($formatType, $givenName,
        $familyName)
    {
        return "some person name";
    }

    public static function parseAddress($formatType, $val)
    {
        // real implementation would set values, etc...
        return new Address();
    }

    public static function parseTelephoneNumber($formatType, $val)
    {
        // real implementation would set values, etc...
        return new TelephoneNumber();
    }
}

High Cohesion


class AddressUtils
{
    public static function formatAddress($formatType, $address1,
        $address2, $city, $state)
    {
        return "some address string";
    }

    public static function parseAddress($formatType, $val)
    {
        // real implementation would set values, etc...
        return new Address();
    }

}

class PersonUtils
{
    public static function formatPersonName($formatType, $givenName,
        $familyName)
    {
        return "some person name";
    }

    public static function parsePersonName($formatType, $val)
    {
        // real implementation would set values, etc...
        return new PersonName();
    }
}