RubyGuides
Share this post!

Introduction to Refactoring

If you aren’t familiar with the term, refactoring is the act of improving the quality of code without changing what it does. This will make your code a lot easier to work with. In this post you will learn some common refactoring techniques, let’s get started!

Extract Method

One of the most common refactorings is the one known as ‘extract method’. In this refactoring you move some code from an old method into a new method. This will allow you to have smaller methods with descriptive names.

Let’s take a look at an example:

We can start by extracting the ugliest part of this method, the current date generation.

This already reads better, but we can go a bit further. Let’s extract a few more methods to end up with this code:

Yes, the code is longer now, but isn’t this easier to read? Don’t be afraid of small methods, they are good for your code.

Refactoring Conditionals

You can also refactor complicated conditionals into methods to make them more readable.

Example:

The second part of this if statement is not super-readable, so let’s extract it into a method:

What we have done here is to give our condition a descriptive name, which makes things a lot easier for future readers of this code (including you!).

Replace Method with Method Object

Sometimes you have a big method that got out of control. In this case it might be hard to refactor because big methods tend to have many local variables. One solution is to use the ‘Method Object’ refactoring.

“Big methods are where classes go to hide.” – Uncle Bob

Let’s see an example:

To perform the refactoring we can create a new class and promote the local variables into instance variables. This will allow us to further refactor this code without having to worry about passing data around.

Hey! Want to improve your Ruby skills in a big way? Check out my New Ruby Course 🙂

This is the MailSender class after the refactoring:

And this is the new class we introduced:

Conclusion

Using these refactoring techniques will help you adhere to the Single Responsibility Principle and keep your classes and methods under control.

If you enjoyed this article please share it with your friends so they can enjoy it too 🙂