Refactoring III -Why is this here?

On the previous post I moved URL parsing code by extending the StockData class and creating a property called Url, now we are left with this code, but if you look at the highlighted code, there are way too many things happening here!.

[code language=”csharp” highlight=”14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29″]

private void btnStockSales_Click(object sender, RoutedEventArgs e)
{

TickerDataCollection = new ObservableCollection();

// no longer care where the data is coming, we just get the data
var stockList = ReadStockData();

List results = new List();

foreach (var item in stockList)
{

TickerData x = new TickerData();
x.Ticker = item.Ticker;
Scraper y = new Scraper();
x = y.Scraping(item.Url);
if (x == null)
{
x = new TickerData();
x.Found = false;
}
else
{
x.Found = true;
}
x.Ticker = item.Ticker;
x.TransactionDate = item.Date.Value;

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

}

LstStocks.DataContext = TickerDataCollection;

}
[/code]

First you see negotiations between StockData and TickerData, validations. This functionality needs to be moved into the Scrapping Object, which yes, this is in VB, this is legacy code.

[code language=”vb” highlight=”12,13,14,15,16,17,18,19″]
Public Function Scraping( stockToSearch As StockData) As TickerData

Dim current As TickerData = New TickerData(stockToSearch.Ticker)

Try

Dim strHtml As String = GetStrHtml(stockToSearch)
ReadHTML(strHtml, current)

‘validate results
if current is nothing Then
current = new TickerData(stockToSearch.Ticker)
Else
current.Found = True
End If

current.TransactionDate = stockToSearch.Date
Return current

Catch ex As Exception
current = new TickerData(stockToSearch.Ticker)
return current
End Try
End Function

[/code]

Notice that as we refactor, code starts to get cleaner and easier to maintain. So now our function will look like 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 some more refactoring to do here, but we are getting closer. This cleanup will continue on the next post.


One thought on “Refactoring III -Why is this here?

Leave a Reply