Logan Bailey

Adventures In Web Development

Blog, About, GitHub, and LinkedIn

Roughly two years ago, I was getting my first introduction to Symfony and I hated it. I wasn't even looking at the framework, just one of the components. The coding drove me up a wall. The issue was S.O.L.I.D. Each concrete object did one thing and had an interface. To trace down how a single public api method was implemented, you'd have to look through what seemed like 20 different classes each doing one item. Yesterday, I came across this quote.

Whenever a task looks too hard for a good object to perform by itself, it looks for others to share in the workload. Successive passing of hard work to others results in no object doing anything really difficult, and usually in a collective solution that is intrinsically simpler than would have been possible if the work had remained where originally assigned.

-- West, David (2004-02-11). Object Thinking (Developer Reference)

I realized, I completely agreed with it. Something happened to that developer from 2 years ago who hated interfaces. As I've begun testing code and striving for readable code, I've begun to see the real benefit in sharing the work load between objects. To me, this benefit is maintainability. When updating older projects, I have to grok what a huge file is doing. But when that work load is shared across many objects, you only need to grok the functionality you're updating.

In the following code sample, you see two methods which create a post. But one has passed the validation logic over to it's own method. If I had to update this method to return the created post, I'd rather have to update the first method. It's just so much simpler to understand everything that is happening.

function createPost($title, $body) {
    $this->postValidator->validate($title, $body);
    $this->dm->persist(PostFactory::create($title, $body));
}

function createPost($title, $body) {
    if (strlen($title) > 40) {
        throw new InvalidInputException('Title cannot be more than 40 characters');
    }

    if (strlen($title) < 10) {
        throw new InvalidInputException('Title cannot be less than 10 characters');
    }

    if (empty($body)) {
        throw new InvalidInputException('Body is required.');
    }

    $slug = preg_replace('/[^\pL\pN\-]/u', '-', strtolower($title));
    $post = new Post($title, $slug, $body);
    $this->dm->persist($post);
}
Posted In:
Programming Quote