Review: Refactoring to Collections

Published on by

Review: Refactoring to Collections image

“Never write another loop again.” A strong promo sentence used by Adam Wathan to market his Refactoring to Collections book, but does it hold the promise? Well, together we will explore how close that claim is to reality.

If you are a Laravel developer, chances are you’ve heard about the collection pipeline before. While I use it a little in my projects I hadn’t realized the possibilities of this approach until I read Refactoring to Collections. It brought me to another level of thinking about utilizing the power and capabilities of functional programming.

Imperative Versus. Declarative Programming

At the beginning of the book, Wathan discusses the difference between imperative and declarative programming and why he prefers the declarative approach. Instead of writing your code in an imperative way (using intermediate variables, loops, conditional statements, and focuses on implementation details) Adam advises you to take a look at the opposite style which focuses on telling the computer what we need it to accomplish instead of caring about implementation details.

Take a look at the following example:

// Imperative Programming
function getUserEmails($users)
{
$emails = [];
 
foreach ($users as $user) {
$emails[] = $user->email;
}
 
return $emails;
}
// Declarative Programming
function getUserEmails($users)
{
return $users->map(function ($user) {
return $user->email;
});
}

Notice how we didn’t need to use loops or intermediate variables in the declarative programming way? Of course, this is a very simple example to show you the basics; the book covers far more complex and useful examples.

The Journey

Refactoring to Collections outlines higher-order functions and their usefulness. It also covers some fundamental higher-order functions like Each, Map, Filter, Reduce, etc. and their implementation. Wathan has also done a good job explaining when to use one higher-order function over another. He gives you some good indicators to help you choose which higher-order function will best meet your needs.

Next, the book discusses the problem of “inside-out” code, the difficulty of reading it, and introduces you to the solution: the collection pipeline which reads from left to right.

In one of my favorite parts of the book, Wathan goes through an implementation of the simple Collection class and makes it possible to use collections in place of arrays and make them countable.

The last part of the book is a walkthrough in a lot of practical examples. Wathan does an awesome job at choosing real-world problems you may encounter in your apps and shows how to solve these problems by using imperative programming, then refactor the solution to declarative programming to show you how declarative programming will make your code more simple and easy to read.

Also, all of the examples are provided as screencasts so you can see Wathan refactor and solve the examples problems step by step, which is my preference.

Honestly, while I advanced through the examples of the book, I was amazed by the process Wathan invented for solving these problems, and I’m sure you will also be surprised by the advanced nature and complexity of the examples.

A Lot to Learn

The nice thing about this book is that you will have a lot to learn, not just about collections. Personally, I learned some great refactoring techniques, and even some PHP tricks, like using forEach to iterate over object public properties.

Even if you aren’t a PHP developer, you can learn from this book as its concepts can be applied to other languages easily.

As always, with any programming skill, you must practice these new ways and techniques and make it part of your everyday workflow to make it click and stick with you. Luckily, the book comes with exercises divided into three categories: Beginner, Intermediate, and Pro to practice what you learned. The solutions for these exercises are included so you can compare them with your solutions and benefit, my advice is not read the solutions until you try to solve the exercises by yourself as the practice a key way can’t be avoided in learning new programming skills.

Efforts

Another wonderful aspect of the book is the amount of effort Wathan has put into every aspect, from the easy to understand writing style to divide the problems into steps and tackling them one by one to achieve the final solution. The quality of the screencasts and seeing Wathan do the refactors live will give you a pleasurable learning experience.

Also, in many examples, I appreciated the effort Wathan put into searching other languages for collection pipeline methods to reach the optimal solution and implement these methods in PHP like he did with the chunkBy and sliceBefore methods.

Even the overall style of the book—the fonts and syntax highlighting color scheme for code blocks—were great choices.

He also created his own Markdown syntax and processing layer for syntax highlighting lines in code blocks and pointed out specific pieces of code to draw the attention to it and gray out the remaining lines.

Here is an example from the book, notice the syntax highlighting and grayed out lines:

And take a look at the beautiful diffs he uses to show the changes happening to code blocks:

I like it!

Hope

The first hope is PHP accepting the Arrow Functions RFC, which will make using the collection pipeline style easier and more beautiful. Take a look at this example:

// Before
function getUserEmails($users)
{
return $users->map(function ($user) {
return $user->email;
});
}
 
// After
function getUserEmails($users)
{
return $users->map(fn($user) => $user->email);
}

Another hope is for Refactoring to Collections to be updated to reflect the new changes introduced to the Laravel framework after the publication of the book. For example, the book talked about how to implement a collection pipeline method called pipe, but a pull request for this method was merged in Laravel, so it would be better to reflect this update and mention it in the book.

The book could also be updated to reflect the new higher-order messaging for the Collections feature which was introduced in the Laravel 5.4 release; it will make the book code examples look more intuitive and more beautiful.

Take a look at this example:

// Before
$employees->reject(function($employee) {
return $employee->retired;
})->each(function($employee){
$employee->sendPayment();
});
 
// After using Higher Order Messaging for Collections
$employees->reject->retired->each->sendPayment();

Much better!

And, if there was a price drop for at least in the first two packages of the book, that may encourage more developers to buy it.

Refactoring to Collections has three tiers of pricing. The Bare Essentials package which includes the book and exercises at $39. The Premium Training Package which includes the screencasts at $79. The Complete Reference Package which includes the source code of an example Laravel application called Nitpick CI at $179.


That’s it; if you want to learn a new nice way of programming that’s easier to read and more expressive to a look at Refactoring to Collections.

Diaa Fares photo

Laravel Artisan, Web Developer, Tech Geek

Filed in:
Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project.

Visit No Compromises
Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
LoadForge logo

LoadForge

Easy, affordable load testing and stress tests for websites, APIs and databases.

LoadForge
Paragraph logo

Paragraph

Manage your Laravel app as if it was a CMS – edit any text on any page or in any email without touching Blade or language files.

Paragraph
Lucky Media logo

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
DocuWriter.ai logo

DocuWriter.ai

Save hours of manually writing Code Documentation, Comments & DocBlocks, Test suites and Refactoring.

DocuWriter.ai
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector

The latest

View all →
Launch your Startup Fast with LaraFast image

Launch your Startup Fast with LaraFast

Read article
Embed Livewire Components on Any Website image

Embed Livewire Components on Any Website

Read article
Statamic announces next Flat Camp retreat (EU edition) image

Statamic announces next Flat Camp retreat (EU edition)

Read article
Laravel Herd releases v1.5.0 with new services. No more Docker, DBNGIN, or even homebrew! image

Laravel Herd releases v1.5.0 with new services. No more Docker, DBNGIN, or even homebrew!

Read article
Resources for Getting Up To Speed with Laravel 11 image

Resources for Getting Up To Speed with Laravel 11

Read article
Laravel 11 is now released! image

Laravel 11 is now released!

Read article