Archive for the ‘Development and Design’ Category

Long if-else statements and tall case statements are scary. As the number of lines and conditional branches grow, the more difficult it becomes to fit the program’s logic inside your head and the more likely you are to introduce bugs into the code.

We rely on polymorphism and design patterns to help reduce complexity; often those solutions are well suited for static programming languages like Java, but feel ceremonious in languages like Python and Javascript. If you’re programming in a dynamic programming language that supports dictionaries out of the box, then you may find the Dispatch Table “pattern” a useful way to simply your code.

The pattern uses a dictionary where the keys represent possible actions, and the value of each key contains a callable that does the actual work. Compared to if-else statements, dispatch tables require fewer lines of code, and we know fewer lines of code equals fewer bugs.

Here’s a mostly real world example that creates handlers for webhooks. You can imagine how long the if-else statement, that is used to decide which handler to instantiate, can become, especially when the consuming code has to respond to multiple keys.

Neat.

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

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

Coming from a .NET background and having applied SOLID principles to software development, I was surprised by the lack of inversion of control containers for Python.

The few discussions I read online implied that Python doesn’t need an IoC framework because it is a dynamically typed language.  Dynamically typed languages eliminate the need to use interfaces, they do not do away with the need for inversion of control.

IoC is used to decouple components of an application, remove direct dependencies so that replacing a component will not have a side effects on the rest of the system.  As Dave Thomas explains

a DI application is written as a set of loosely coupled components. These components contain no knitting code: nothing in the application code itself is responsible, for example, for making sure that the necessary objects somehow get an instance of the database connection. Instead, the components all run in a container. This container is given a description of the knitting to be done (typically using an XML file). The container then instantiates objects and sets them into components that need them

I’m new to the language and there maybe a more “pythonic” way to handle inversion of control than using a container. Here is small and contrived example of inversion of control using Pinsor, a IoC container in Python. Those coming from a .NET or Java background will find Pinsor easy to use, but slightly lacking in features.

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

Search