Refactoring IV – Finally There

On the previous post, we moved validation functionality to the Scraping object. The resulting function was this:

[code language=”csharp”]

private void btnStockSales_Click(object sender, RoutedEventArgs e)
{

TickerDataCollection = new ObservableCollection<TickerData>();

var stockList = ReadStockData();

foreach (var item in stockList)
{

Scraper y = new Scraper();
TickerData x = y.Scraping(item);

TickerDataCollection.Add(new TickerData(x.Ticker) { High = x.High, Low = x.Low, Found = x.Found, TransactionDate = x.TransactionDate });

}

LstStocks.DataContext = TickerDataCollection;
}
[/code]

There is still too much going on. The next step is to extract a method to process the items on the list, I called this method ScrapeStockData

[code language=”csharp”]
private void ScrapeStockData(List<StockData> stockList)
{

TickerDataCollection = new ObservableCollection<TickerData>();

foreach (var item in stockList)
{
Scraper y = new Scraper();
TickerData x = y.Scraping(item);

TickerDataCollection.Add(new TickerData(x.Ticker)
{
High = x.High,
Low = x.Low,
Found = x.Found,
TransactionDate = x.TransactionDate
});
}
}

[/code]

The resulting function would be, you can get an idea of what is happening in this function without having to read the code.

Code should be self explanatory, and should read like a book, other developers should be able to understand what is happening with little or no comments.

[code language=”csharp”]

private void btnStockSales_Click(object sender, RoutedEventArgs e)
{

var stockList = ReadStockData();

ScrapeStockData(stockList);

LstStocks.DataContext = TickerDataCollection;
}
[/code]

So there is a final step to this refactoring, we can still make this function smaller:

[code language=”csharp”]

private void ReadAndScrapeStocks()
{
var stockList = ReadStockData();

ScrapeStockData(stockList);
}

[/code]

The final product is a far cry from the original function – click here to see it again.

[code language=”csharp”]
private void btnStockSales_Click(object sender, RoutedEventArgs e)
{
ReadAndScrapeStocks();

LstStocks.DataContext = TickerDataCollection;
}
[/code]


One thought on “Refactoring IV – Finally There

Leave a Reply to JulieCancel reply