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: }
</div> </div>
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: }
7:
8: public void CreateAccountWithCheckingAndSavings(Customer customer)
9: {
10: CreateAccount(customer, true, true);
11: }
12:
13: private void CreateAccount(Customer customer, bool withChecking, bool withSavings)
14: {
15: // do work
16: }
17: }
</div> </div>
This is part of the 31 Days of Refactoring series. For a full list of Refactorings please see the original introductory post.