Book Review: Refactoring to Collections

« »

Note: I received a free review copy with the promise to write a review. However, this review is my own review and reflects my viewpoints alone.

What is wrong with this code sample?


$emails = [];

foreach ($users as $user) {
    if ($user->allowed) {
        $emails[] = [$user->email, $user->getFullName()];
    }
}

We’ve all written code that looks just like this. In fact, for many of us this is a default way of coding. But what we’re doing here is imperative programming. In his book, Adam Wrathan teaches us that declarative programming, or programming by expressing what we want to accomplish rather than the steps needed to accomplish it, can help us achieve our goals.

Consider the following code sample instead:

$emails = $userCollection->filter(function($user) { return $user->allowed; })
                         ->map(function($user) { return [$user->email, $user->getFullName()]; })
			 ->toArray();

This is far more expressive. And this is the whole point of Adam’s book.

I’ll admit that when I first took a look at the book I was skeptical. After all, many writers publish books every year, but few write a book that is groundbreaking in the PHP world. And yet as I started reading Refactoring to Collections I started realizing how truly powerful Adam’s point of view is.

Imagine never writing a loop ever again, or eliminating most of the if statements you currently write inside loops. It’s not just possible, it’s explained in Adam’s book. This book lives up to its marketing page. The exercises also make it amazingly easy to learn Adam’s book, too.

Of course there are certain things about the book that I didn’t care for as much. For example, the book leaves out an in depth discussion of existing array functions in PHP (most of which already match exactly what Adam is trying to accomplish); I can imagine beginner-level developers implementing the each(), map(), filter() and reduce() methods, instead of relying on functions like array_walk() and array_filter(). But then again, that’s not always the end of the world.

Adam’s book is going to make changes in the way I program, and if you take a read, it will change the way you develop as well. I wholeheartedly recommend it for all PHP developers intermediate and greater.

Adam has generously offered readers of this blog a discount code for 25% off any package of the book. I receive nothing for this offer; it’s offered solely because Adam is a good guy who wants to help you write better code. To get your discount, use discount code savage-refactoring on the book’s website. Enjoy!

Brandon Savage is the author of Mastering Object Oriented PHP and Practical Design Patterns in PHP

Posted on 6/14/2016 at 8:00 am
Categories: PHP

There are currently no comments.

« »

Copyright © 2023 by Brandon Savage. All rights reserved.