Refactoring Day 28 : Rename boolean method

Today’s refactoring doesn’t necessarily come from Fowlers refactoring catalog. If anyone knows where this “refactoring” actually comes from, please let me know.

Granted, this could be viewed as not being a refactoring as the methods are actually changing, but this is a gray area and open to debate. Methods with a large number of boolean parameters can quickly get out of hand and can produce unexpected behavior. Depending on the number of parameters will determine how many methods need to be broken out. Let’s take a look at where this refactoring starts:

   1: public class BankAccount

   2: {

   3:     public void CreateAccount(Customer customer, bool withChecking, bool withSavings, bool withStocks)

   4:     {

   5:         // do work

   6:     }

   7: }

We can make this work a little better simple by exposing the boolean parameters via well named methods and in turn make the original method private to prevent anyone from calling it going forward. Obviously you could have a large number of permutations here and perhaps it makes more sense to refactor to a Parameter object instead.

   1: public class BankAccount

   2: {

   3:     public void CreateAccountWithChecking(Customer customer)

   4:     {

   5:         CreateAccount(customer, true, false);

   6:     }


   8:     public void CreateAccountWithCheckingAndSavings(Customer customer)

   9:     {

  10:         CreateAccount(customer, true, true);

  11:     }


  13:     private void CreateAccount(Customer customer, bool withChecking, bool withSavings)

  14:     {

  15:         // do work

  16:     }

  17: }

This is part of the 31 Days of Refactoring series. For a full list of Refactorings please see the original introductory post.

About Sean Chambers

I am a Senior software developer from Palm Coast, Florida. An advocate of Domain Driven Design, Behavior Driven Development, creator of FluentMigrator and community activist. I am married to my beautiful wife Erin and am the proud father of two wonderful children. I currently reside at ACI, a local insurance industry/mortgage software company that excels in creating solutions using Agile methodologies.
This entry was posted in Uncategorized. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • more a case of refactor methods with lots of arguments isn’t it? unsure if this is a good example / good advice tbh

    nice series though!

  • rhu

    Or use a builder:

    BankAccount ba = new AccountBuilder().customer(cust).withChecking().withSavings().create();

  • How about a [Flags] enumeration:

    CreateAccount(customer, AccountCreationOptions.WithChecking | AccountCreationOptions.WithSavings)