In order to provide a practical, real-life example of the open-closed principle, we'll use a heavily-modified version of existing code from the Laracasts codebase, itself. This should open up all sorts of refactoring possibilities. Now before we get started, let's first take a few minutes to discuss what we're working with, and where we want to go.
Let's begin our refactoring by applying the squint test. If we squint our eyes and scan the Query
, what immediately jumps out at us? Indentation? Common method names? Multiple return types? Let's see!
Let's keep going. In this episode, I'll show you how to remove a conditional by reassigning the "check" to the underlying class.
Let's take the only remaining thing that changes in our Query
class, and extract it to a service provider. With this tweak, you'll never have to modify the Query
class again. Instead, create a new featured collection, add a new item to your service provider's $collections
array, and you're done.
As we reach the end of this series, let's take a few moments to discuss responsibility and awareness. I find that it's useful to frequently ask myself, "Should this class be aware of that particular thing?"