My First Refactor

Over the last Christmas I was thinking about investing so I developed a small tool which I was using to analyse stock market data. I was interested in checking what the rate of return on various stocks actually was if you use the Dollar Cost Averaging method of investment.

Google Finance - Download to Spreadsheet
Google Finance – Download to Spreadsheet

I retrieved the data from Google Finance – you can download daily stock prices for any stock you’d like.  I then imported that data into a MySQL database so I could write simple queries for the data from php. Finally I wrote a single little php script that took the value in Euros which you wanted to invest per month and calculated how much your money would grow (or decline) in value over the time you chose.

For the moment, both the stock you invest in and historic period over which you invest in are hard-coded in the php code. These could be both made into fields for the users of the tool to change later.

However, as I made progress the PHP was growing larger and longer without much redesign. So I thought it was perfect piece of code to practise refactoring on! The code as it is today is pasted below. As you can see there is no clear structure to the code, just variables, constants and a loop that echos out the response. There are no tests so I have to re-load the page and examine it manually every time  I make a change to make sure I haven’t broken it.

Clearly I need to clean this code up! The first step will be to write a test around it – I’m going to try writing a characterisation test for this. Then I can begin refactoring. Once I’m happy with the refactor I can go back and refactor my tests so they aren’t so fragile and tied to the response output.

Join the conversation

1 Comment

Leave a comment

Your email address will not be published. Required fields are marked *

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