Refactoring IV – Finally There

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


  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;
        }

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

 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
                });
            }
        }

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.


private void btnStockSales_Click(object sender, RoutedEventArgs e)
        {

            var stockList = ReadStockData();

            ScrapeStockData(stockList);

            LstStocks.DataContext = TickerDataCollection;
        }

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


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

            ScrapeStockData(stockList);
        }

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

 private void btnStockSales_Click(object sender, RoutedEventArgs e)
        {
            ReadAndScrapeStocks();

            LstStocks.DataContext = TickerDataCollection;
        }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s