Refactoring to: Creation Method

As I spoke at and attended several conferences last month, the book Refactoring to Patterns (affiliate link) kept coming up again and again, especially in my favorite talks. I finally have a little time to read it (before all the after-WWDC-announcement craziness ascends), and I’d like to document the patterns I like for future reference. I also found it better to remember the information by translating the Java in the book to Swift.

The first pattern is the Creation Method.


Let’s say you have a model, such as a Loan, that has a lot of different initializers. In this case each initializer is there for a reason – each one corresponds to a different loan type:

Looking at this code, you would have no idea (unless you implicitly know all the loan types) of which initializer to use. Of course, someone new coming to this code base might not be familiar with the business information, so they might use the wrong initializer, further confusing the intent of all the initializers.

Time to refactor!


The Creator Method refactors this to the following:

Notice how beautiful the result is! When you initialize a loan, you now know the intent.

While I’m generally not big on these type of class initializers and there might be a better way to do this in Swift depending on the actual code situation (e.g enums), I will definitely consider refactoring to this pattern in cases where it would make my code this much more readable and clearer.

Join me for a Swift Community Celebration 🎉 in New York City on September 1st and 2nd. Use code NATASHATHEROBOT to get $100 off!

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.