Archive for the ‘programming’ Category

My previous discussion on Inversion of Control raised some questions so I want to take a step back and discuss Dependency Injection. Dependency Injection is a pattern where software components (classes, methods or functions) are given their dependencies as parameters and these software components do not instantiate their dependencies directly.

Dependency Injection is an important pattern to use when you wan to create classes that are easier to reuse and unit test. Since the dependencies are external, they can be configured and maintained outside class or function and there’s no need to change the code in order to reuse it. Also, when dependencies are injected into a class or a function it is possible to substitute a mock implementation of the dependency. In unit tests, mock objects are used as replacement for the real implementation, this helps isolate the functionality being tested.

A simple example

The following function has it’s dependencies, a list of numbers, passed to it, and since calculate_average only talks to a list of numbers it is easy to reuse.

def calculate_average(list_of_numbers):
  x = sum(list_of_numbers)
  return x/len(list_of_numbers)

Imagine a similar function which uses a database connection, retrieves a list of numbers then calculates the average.

def calculate_average():
  sql_query = "select numbers from table"
  list_of_numbers = db.query(sql_query)
  x = sum(list_of_numbers)
  return x/len(list_of_numbers)

This function is difficult to reuse because it depends on the database, future users of this function will have to either modify the function or create and maintain a database just to use it. More importantly it’s difficult to test this function. A test would require a database connection and a fixture to populate the database with data.

You should be thinking, but Shey, I would never do this with a simple function like this. You’re right, you wouldn’t do this with a simple function, but as soon as calculate_average turns into a more complicated calculation such as calculate_value_at_risk we start instantiating or dependencies.

A slightly less contrived example

The BillingService class is responsible for charging your customers a fee.

class BillingService
  def initialize(credit_card_processor)
    self.processor = processor

  def charge(account, amount):
    if account.has_balance:
      result = processor.charge(account.cc_number, amount)
    if result == "success":
      account.deduct(amount)

Lets assume that Authorize.net is offering better rates than PayPal. If the class accepts an implementation of a credit card processor as a dependency it is possible to switch to the authorize.net implementation of the credit card processor class without changing the BillingService class. Similarly during unit testing, a mock implementation of a credit card processor can be used to alwasy return “success” and isolate the charge functionality of the BillingService.

class mock_credit_card_processor:
  def charge(cc_number, amount):
    return "success"

    def test_charge():
      bs = BillingService(mock_credit_card_processor)
      a = Account(cc_number="411111111111111", balance=300.00)
      bs.charge(a, 300.00)
      assert(a.balance == 0)
Share and Enjoy:
  • del.icio.us
  • Reddit
  • Facebook
  • Identi.ca
  • TwitThis

Moneytrackin is a cool online accounting application that lets you track expenses and income, unlike other accounting applications it lets you add tags to each transactions. I love it!  Tagging transactions makes it easier to track exactly where my money is going; not only can I see how much money I’ve spent on junk food but also at which store, and all without having to explicitly create an account for that store.

Unfortunately Moneytracking has an annoying limitation which prevents you from tracking tags across accounts, so if you’re buying junk food with cash and credit tagging loses it appeal.  Luckily, they provide an API which will allow us to easily get around the tagging limitation programmatically. 

I can imagine some pretty cool analytics and infographics coming out of 6 months of data so I wrote Moneytrackin.rb, a Ruby interface to the MoneyTrackin API.  It exposes easy-to-use methods to interact with your Moneytrackin account. While it only implements the methods exposed by their API but I intend to add more functionality like tag searches across all accounts soon, imagine piping an amounte-weighted stream of tags to wordle!

With two gems, HTTParty and Mash, I was easily able to create the client interface.  I included the HTTParty module within connection class and it gave it a "get" method that retrieves data over HTTP.   Usage is simple:

response = self.class.get(self.class.base_uri + '/listProjects/')

Then I passed the response to Mash which converts the XML response into a hash that acts more like a an object., it also also recursively descends down the response converting hashes into Mashes making it easy to get the transactions and the tags associated with them.

Share and Enjoy:
  • del.icio.us
  • Reddit
  • Facebook
  • Identi.ca
  • TwitThis

SQLite is a great little embeddable database engine but the installation of the Ruby library is not obvious or straightforward on Windows XP or Vista.  To install SQLite for Ruby 1.8, perform the following steps:

  1. download sqlitedll-3_6_18.zip,
  2. copy the two files that are part of the archive to your Ruby bin directory;
  3. run “gem install –version 1.2.3 sqlite3-ruby” from the command prompt.

Enjoy!

Share and Enjoy:
  • del.icio.us
  • Reddit
  • Facebook
  • Identi.ca
  • TwitThis

Search