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 comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.