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 14,500+ Swift developers and enthusiasts who get my weekly updates.

  • Stepan

    I’d go with a type for each loan, all conforming to a Loan protocol.

    • The book is going into more detail on how to refactor it further (via the strategy pattern), so just going with it.

      • MarcSteven

        Hi,what book?Tell me ,thank you so much……

  • Andy Van Ness

    This reminds me very much of SpriteKit’s SKAction.

  • Jean-François Brouillet

    Your next step is to move all the the createXXXXLoan **out** of the loan class. Think about it: right now you are coupling what a loan _is_ with _how you intend to use it_!

    I use some variant of a WellKnown struct through my own projects, where the factories (your example) and singletons are declared _outside_ the class(es) and finally make Loan like classes reusable from project to project:

    struct WellKnown {
    struct LongTerm {}
    /// in some other file
    extension WellKnown.LongTerm {
    static let longTermLoan = Loan(…)

  • harish

    minimum number of lines that will be needed to make “N” squares how can I do this These squares can share edges and also do not consider nested squares