Today I’ll be continuing my review of a book I’m reading called Refactoring Ruby Edition.
Replace Temp with Chain
This is fairly new to me, but there are times when we can improve the ease and speed with which our code can be restored after failure by using method chaining instead of a temporary variable. Lets look at an example that closely resembles whats in the book.
class MovieQue def movies @movies ||=  end def add_movie(title) movies << title end end rental = MovieQue.new rental.add_movie("Shawshank Redemption") rental.add_movie("Flight of the Navigator") rental.add_movie("Happy Gilmore")
Now lets take a peak at how to perform this refactor:
selffrom methods that you want to allow chaining from
- Step2: Test (Make sure the target piece(s) of code is/are performing as before)
- Step3: Remove the local variable and chain the method calls
- Step4: Test Again
Following the guidance in the book, our first step is to define a method which creates the
MovieQue instance and adds a movie’s title.
class MovieQue def MovieQue.with_movie(title) rental = MovieQue.new rental.movies << title rental end end rental = MovieQue.with_movie("Shawshank Redemtion") rental.with_movie("Wag the Dog") rental.with_movie("Bill and Ted's Excellent Adventure") rental.with_movie("Barbarians at the Gate")
Our next step is to change the method that adds our titles to return
self so it can be chained.
class MovieQue . . . def add_movie(title) movies << title self end end rental = MovieQue.with_movie("Shawshank Redemption").add_movie("Superman IV").add_movie("Mad Max Beyond Thunderdome")
Lastly, the authors instruct us to rename the
add_movie method to something that reads more fluently, such as “and”.
class MovieQue def self.with_movie(title) rental = self.new rental.movies << title rental end def movies @movies ||=  end def and(title) movies << title self end end rental = MovieQue.with_movie("Saturn 2").and("Saturn 3").and("Blade Runner")
I hope this has been as informative for you as it has been for myself. I welcome any of you reading this post that have had some experience using this refactoring pattern to leave a comment. Feel free to also share when you find this pattern to be best used and maybe some cases where it may not make the best use of your time.