Laravel Idea for PhpStorm - Full-featured IDE for productive artisans!

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.

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
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

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
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
Rector logo

Rector

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

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Asymmetric Property Visibility in PHP 8.4 image

Asymmetric Property Visibility in PHP 8.4

Read article
Access Laravel Pulse Data as a JSON API image

Access Laravel Pulse Data as a JSON API

Read article
Laravel Forge adds Statamic Integration image

Laravel Forge adds Statamic Integration

Read article
Transform Data into Type-safe DTOs with this PHP Package image

Transform Data into Type-safe DTOs with this PHP Package

Read article
PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell image

PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell

Read article
Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3 image

Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3

Read article