Docsity

30 Days of Refactoring Code, Study Guides, Projects, Research of Computer Engineering and Programming

Partial preview of the text

Download 30 Days of Refactoring Code and more Study Guides, Projects, Research Computer Engineering and Programming in PDF only on Docsity!

31 Days of Refactoring

Useful refactoring techniques you have to know

October 2009

Sean Chambers, Simone Chiaretta

Originally released as a series of 33 blog posts on Sean Chambers blog:

http://www.lostechies.com/blogs/sean_chambers/archive/2009/07/31/

Majority of Refactorings courtesy of Martin Fowler via re

Converted to eBook by Simone Chiaretta (aka CodeClimber)

Originally released as a series of 33 blog posts on Sean Chambers blog:

http://www.lostechies.com/blogs/sean_chambers/archive/2009/07/31/31-days-of-refactoring.aspx

Majority of Refactorings courtesy of Martin Fowler via refactoring.com:

http://refactoring.com/

Converted to eBook by Simone Chiaretta (aka CodeClimber)

http://codeclimber.net.nz/

refactoring.aspx

Introduction

Refactoring is an integral part of continually improving your code while it moves forward through time.

Without refactoring you accrue technical debt, forget what portions of code do and create code that is

resistant to any form of testing. It is an easy concept to get started with and opens the door to much better

practices such as unit testing, shared code ownership and more reliable, bug-free code in general.

Because of the importance of refactoring, throughout the month of August I will be describing one

refactoring a day for the 31 days of August. Before I begin, let me prefix this series with the fact that I am

not claiming ownership of the refactorings I will describe, although I will try to bring some additional

description and perhaps some discussion around each. I have chosen not to list the full set of refactorings

on this first post until I actually post the refactoring. So as the month progresses I will update this post with

links to each of the refactorings.

First on the list is credit where it is due. The majority of these refactorings can be found Refactoring.com,

some are from Code Complete 2nd Edition and others are refactorings that I find myself doing often and

from various other places on the interwebs. I don’t think its important to note on each refactoring where it

came from, as you can find refactorings of similar names found on various blogs and articles online.

On that note, I will be publishing the first post starting tomorrow that begins the 31 day marathon of

various refactorings. I hope you all enjoy and learn something from the refactorings!

Refactoring Day 1 : Encapsulate Collection

In certain scenarios it is beneficial to not expose a full collection to consumers of a class. Some of these

circumstances is when there is additional logic associated with adding/removing items from a collection.

Because of this reason, it is a good idea to only expose the collection as something you can iterate over

without modifying the collection. Let’s take a look at some code

1: public class Order 2: { 3: private List _orderLines; 4: 5: public IEnumerable OrderLines 6: { 7: get { return _orderLines; } 8: } 9: 10: public void AddOrderLine(OrderLine orderLine) 11: { 12: _orderTotal += orderLine.Total; 13: _orderLines.Add(orderLine); 14: } 15: 16: public void RemoveOrderLine(OrderLine orderLine) 17: { 18: orderLine = _orderLines.Find(o => o == orderLine); 19: if (orderLine == null) return; 20: 21: _orderTotal -= orderLine.Total 22: _orderLines.Remove(orderLine); 23: } 24: }

As you can see, we have encapsulated the collection as to not expose the Add/Remove methods to

consumers of this class. There is some other types in the .Net framework that will produce different

behavior for encapsulating a collection such as ReadOnlyCollection but they do have different caveats with

each. This is a very straightforward refactoring and one worth noting. Using this can ensure that consumers

do not mis-use your collection and introduce bugs into the code.

AccountInterest accountInterest) 4: { 5: AccountAge = accountAge; 6: CreditScore = creditScore; 7: AccountInterest = accountInterest; 8: } 9: 10: public int AccountAge { get; private set; } 11: public int CreditScore { get; private set; } 12: public AccountInterest AccountInterest { get; private set; } 13: } 14: 15: public class AccountInterest 16: { 17: public BankAccount Account { get; private set; } 18: 19: public AccountInterest(BankAccount account) 20: { 21: Account = account; 22: } 23: 24: public double InterestRate 25: { 26: get { return CalculateInterestRate(); } 27: } 28: 29: public bool IntroductoryRate 30: { 31: get { return CalculateInterestRate() < 0.05; } 32: } 33: 34: public double CalculateInterestRate() 35: { 36: if (Account.CreditScore > 800) 37: return 0.02; 38: 39: if (Account.AccountAge > 10) 40: return 0.03; 41: 42: return 0.05; 43: } 44: }

Simple enough!

Refactoring Day 3 : Pull Up Method

The Pull Up Method refactoring is the process of taking a method and “Pulling” it up in the inheritance

chain. This is used when a method needs to be used by multiple implementers.

1: public abstract class Vehicle 2: { 3: // other methods 4: } 5: 6: public class Car : Vehicle 7: { 8: public void Turn(Direction direction) 9: { 10: // code here 11: } 12: } 13: 14: public class Motorcycle : Vehicle 15: { 16: } 17: 18: public enum Direction 19: { 20: Left, 21: Right 22: }

As you can see, our Turn method is currently only available to the car class, we also want to use it in the

motorcycle class so we create a base class if one doesn’t already exist and “pull up” the method into the

base class making it available to both. The only drawback is we have increased surface area of the base

class adding to it’s complexity so use wisely. Only place methods that need to be used by more that one

derived class. Once you start overusing inheritance it breaks down pretty quickly and you should start to

lean towards composition over inheritance. Here is the code after the refactoring:

1: public abstract class Vehicle 2: { 3: public void Turn(Direction direction) 4: { 5: // code here 6: } 7: } 8: 9: public class Car : Vehicle 10: { 11: } 12: 13: public class Motorcycle : Vehicle 14: { 15: } 16: 17: public enum Direction 18: { 19: Left, 20: Right 21: }

Refactoring Day 5 : Pull Up Field

Today we look at a refactoring that is similar to the Pull Up method. Instead of a method, it is obviously

done with a field instead!

1: public abstract class Account 2: { 3: } 4: 5: public class CheckingAccount : Account 6: { 7: private decimal _minimumCheckingBalance = 5m; 8: } 9: 10: public class SavingsAccount : Account 11: { 12: private decimal _minimumSavingsBalance = 5m; 13: }

In this example, we have a constant value that is duplicated between two derived classes. To promote

reuse we can pull up the field into the base class and rename it for brevity.

1: public abstract class Account 2: { 3: protected decimal _minimumBalance = 5m; 4: } 5: 6: public class CheckingAccount : Account 7: { 8: } 9: 10: public class SavingsAccount : Account 11: { 12: }

Refactoring Day 6 : Push Down Field

Opposite of the Pull Up Field refactoring is push down field. Again, this is a pretty straight forward

refactoring without much description needed

1: public abstract class Task 2: { 3: protected string _resolution; 4: } 5: 6: public class BugTask : Task 7: { 8: } 9: 10: public class FeatureTask : Task 11: { 12: }

In this example, we have a string field that is only used by one derived class, and thus can be pushed down

as no other classes are using it. It’s important to do this refactoring at the moment the base field is no

longer used by other derived classes. The longer it sits the more prone it is for someone to simply not touch

the field and leave it be.

1: public abstract class Task 2: { 3: } 4: 5: public class BugTask : Task 6: { 7: private string _resolution; 8: } 9: 10: public class FeatureTask : Task 11: { 12: }

Refactoring Day 8 : Replace Inheritance with

Delegation

All too often inheritance is used in the wrong scenarios. Inheritance should only be used in logical

circumstances but it is often used for convenience purposes. I’ve seen this many times and it leads to

complex inheritance hierarchies that don’t make sense. Take the following code:

1: public class Sanitation 2: { 3: public string WashHands() 4: { 5: return "Cleaned!"; 6: } 7: } 8: 9: public class Child : Sanitation 10: { 11: }

In this instance, a Child is not a “Sanitation” and therefore doesn’t make sense as an inheritance hierarchy.

We can refactor by initializing an instance of Sanitation in the Child constructor and delegating the call to

the class rather than via inheritance. If you were using Dependency Injection, you would pass in the

Sanitation instance via the constructor, although then you would need to register your model in your IoC

container which is a smell IMO, you get the idea though. Inheritance should ONLY be used for scenarios

where inheritance is warranted. Not instances where it makes it quicker to throw down code.

1: public class Sanitation 2: { 3: public string WashHands() 4: { 5: return "Cleaned!"; 6: } 7: } 8: 9: public class Child 10: { 11: private Sanitation Sanitation { get; set; } 12: 13: public Child() 14: { 15: Sanitation = new Sanitation(); 16: } 17: 18: public string WashHands() 19: { 20: return Sanitation.WashHands(); 21: } 22: }

Refactoring Day 9 : Extract Interface

Today we look at an often overlooked refactoring. Extract Interface. When you notice more than one class

using a similar subset of methods on a class, it is useful to break the dependency and introduce an interface

that the consumers to use. It’s easy to implement and has benefits from loose coupling.

1: public class ClassRegistration 2: { 3: public void Create() 4: { 5: // create registration code 6: } 7: 8: public void Transfer() 9: { 10: // class transfer code 11: } 12: 13: public decimal Total { get; private set; } 14: } 15: 16: public class RegistrationProcessor 17: { 18: public decimal ProcessRegistration(ClassRegistration registration) 19: { 20: registration.Create(); 21: return registration.Total; 22: } 23: }

In the after example, you can see we extracted the methods that both consumers use and placed them in

an interface. Now the consumers don’t care/know about the class that is implementing these methods. We

have decoupled our consumer from the actual implementation and depend only on the contract that we

have created.

1: public interface IClassRegistration 2: { 3: void Create(); 4: decimal Total { get; } 5: } 6: 7: public class ClassRegistration : IClassRegistration 8: { 9: public void Create() 10: { 11: // create registration code 12: } 13: 14: public void Transfer() 15: { 16: // class transfer code 17: } 18: 19: public decimal Total { get; private set; } 20: } 21: 22: public class RegistrationProcessor 23: { 24: public decimal ProcessRegistration(IClassRegistration registration) 25: { 26: registration.Create();

Refactoring Day 10 : Extract Method

Today we look at the Extract Method refactoring. This is an extremely easy refactoring with several

benefits. First, it helps to make code more readable by placing logic behind descriptive method names. This

reduces the amount of investigation the next developer needs to do as a method name can describe what a

portion of code is doing. This in turn reduces bugs in the code because less assumptions need to be made.

Here’s some code before we apply the refactoring:

1: public class Receipt 2: { 3: private IList Discounts { get; set; } 4: private IList ItemTotals { get; set; } 5: 6: public decimal CalculateGrandTotal() 7: { 8: decimal subTotal = 0m; 9: foreach (decimal itemTotal in ItemTotals) 10: subTotal += itemTotal; 11: 12: if (Discounts.Count > 0) 13: { 14: foreach (decimal discount in Discounts) 15: subTotal -= discount; 16: } 17: 18: decimal tax = subTotal * 0.065m; 19: 20: subTotal += tax; 21: 22: return subTotal; 23: } 24: }

You can see that the CalculateGrandTotal method is actually doing three different things here. It’s

calculating the subtotal, applying any discounts and then calculating the tax for the receipt. Instead of

making a developer look through that whole method to determine what each thing is doing, it would save

time and readability to seperate those distinct tasks into their own methods like so:

1: public class Receipt 2: { 3: private IList Discounts { get; set; } 4: private IList ItemTotals { get; set; } 5: 6: public decimal CalculateGrandTotal() 7: { 8: decimal subTotal = CalculateSubTotal(); 9: 10: subTotal = CalculateDiscounts(subTotal); 11: 12: subTotal = CalculateTax(subTotal); 13: 14: return subTotal; 15: } 16: 17: private decimal CalculateTax(decimal subTotal) 18: { 19: decimal tax = subTotal * 0.065m; 20: 21: subTotal += tax; 22: return subTotal;

25: private decimal CalculateDiscounts(decimal subTotal) 26: { 27: if (Discounts.Count > 0) 28: { 29: foreach (decimal discount in Discounts) 30: subTotal -= discount; 31: } 32: return subTotal; 33: } 34: 35: private decimal CalculateSubTotal() 36: { 37: decimal subTotal = 0m; 38: foreach (decimal itemTotal in ItemTotals) 39: subTotal += itemTotal; 40: return subTotal; 41: } 42: }

To apply this refactoring take the condition that is being tested and place it in it’s own class that adheres to

a common interface. Then by passing the enum as the dictionary key, we can select the proper

implementation and execute the code at hand. In the future when you want to add another condition, add

another implementation and add the implementation to the ShippingCalculations dictionary. As I stated

before, this is not the only option to implement the strategy pattern. I bold that because I know someone

will bring this up in the comments :) Use what works for you. The benefit of doing this refactoring in this

manner is that none of your client code will need to change. All of the modifications exist within the

ShippingInfo class.

Jayme Davis pointed out that doing this refactoring really only ceates more classes because the binding still

needs to be done via the ctor, but would be more beneficial if the binding of your IShippingCalculation

strategies can be placed into IoC and that allows you to wire up strategies more easily.

1: using System.Collections.Generic; 2: 3: namespace LosTechies.DaysOfRefactoring.SwitchToStrategy.After 4: { 5: public class ClientCode 6: { 7: public decimal CalculateShipping() 8: { 9: ShippingInfo shippingInfo = new ShippingInfo(); 10: return shippingInfo.CalculateShippingAmount(State.Alaska); 11: } 12: } 13: 14: public enum State 15: { 16: Alaska, 17: NewYork, 18: Florida 19: } 20: 21: public class ShippingInfo 22: { 23: private IDictionary<State, IShippingCalculation> ShippingCalculations { get; set; } 24: 25: public ShippingInfo() 26: { 27: ShippingCalculations = new Dictionary<State, IShippingCalculation> 28: { 29: { State.Alaska, new AlaskShippingCalculation() }, 30: { State.NewYork, new NewYorkShippingCalculation() }, 31: { State.Florida, new FloridaShippingCalculation() } 32: }; 33: } 34: 35: public decimal CalculateShippingAmount(State shipToState) 36: { 37: return ShippingCalculations[shipToState].Calculate(); 38: } 39: } 40: 41: public interface IShippingCalculation 42: { 43: decimal Calculate(); 44: } 45: 46: public class AlaskShippingCalculation : IShippingCalculation 47: {

48: public decimal Calculate() 49: { 50: return 15m; 51: } 52: } 53: 54: public class NewYorkShippingCalculation : IShippingCalculation 55: { 56: public decimal Calculate() 57: { 58: return 10m; 59: } 60: } 61: 62: public class FloridaShippingCalculation : IShippingCalculation 63: { 64: public decimal Calculate() 65: { 66: return 3m; 67: } 68: } 69: }

To take this sample full circle, Here is how you would wire up your bindings if you were using Ninject as

your IoC container in the ShippingInfo constructor. Quite a few things changed here, mainly the enum for

the state now lives in the strategy and ninject gives us a IEnumerable of all bindings to the constructor of

IShippingInfo. We then create a dictionary using the state property on the strategy to populate our

dictionary and the rest is the same. (thanks to Nate Kohari and Jayme Davis)

1: public interface IShippingInfo 2: { 3: decimal CalculateShippingAmount(State state); 4: } 5: 6: public class ClientCode 7: { 8: [Inject] 9: public IShippingInfo ShippingInfo { get; set; } 10: 11: public decimal CalculateShipping() 12: { 13: return ShippingInfo.CalculateShippingAmount(State.Alaska); 14: } 15: } 16: 17: public enum State 18: { 19: Alaska, 20: NewYork, 21: Florida 22: } 23: 24: public class ShippingInfo : IShippingInfo 25: { 26: private IDictionary<State, IShippingCalculation> ShippingCalculations { get; set; } 27: 28: public ShippingInfo(IEnumerable shippingCalculations) 29: { 30: ShippingCalculations = shippingCalculations.ToDictionary( calc => calc.State); 31: } 32: 33: public decimal CalculateShippingAmount(State shipToState) 34: { 35: return ShippingCalculations[shipToState].Calculate();