Archive for February, 2010

CodeKata – Binary search (chop) in Ruby

Wednesday, February 24th, 2010

On Monday I was home with manflu and, facing a terrible lack of sympathy from a considerably pregnant wife, decided to start learning Ruby. I finished the Ruby Koans, a set of failing tests that walks you through aspects of the language. I now think that, after ‘Hello, World!’ and some basic algebra, TDD would be the best way to teach and learn programming in general.

Last night I found my way to CodeKata and started at Kata 2 for instant gratification. Kata 2 is to implement a binary search algorithm. My first try was just a linear search, which passed the tests, but wasn’t a binary search and for very big sets of test data is impractical. My second try is a recursive binary search:

def chop(needle, haystack)
  # Special cases
  return -1 if haystack.length == 0
  if haystack.length == 1
    return 0 if haystack[0] == needle
    return -1
  end

  # find the middle element
  mid = (haystack.length / 2).round
  return mid if haystack[mid] == needle

  if haystack[mid] > needle
    #needle is in first half
    return chop(needle, haystack[0..(mid-1)])
  else
    #needle is in second half
    result = chop(needle, haystack[mid..haystack.length])
    return result == -1 ? -1 : result + mid
  end
end

My third try converts the recursive algo into an interative one:

def chop(needle, haystack)
  depth = 0

  while true
    # Special cases
    return -1 if haystack.length == 0
    if haystack.length == 1
      return depth if haystack[0] == needle
      return -1
    end

    # find mid point
    mid = (haystack.length / 2).round
    return mid + depth if haystack[mid] == needle

    # trim haystack based on which end to follow
    if haystack[mid] > needle
      #needle is in first half
      haystack = haystack[0..(mid - 1)]
    else
      haystack = haystack[mid..haystack.length]
      depth += mid
    end
  end
end

I found that while I was writing the different implementations I had a lot of love for these little chips of Ruby. Maybe it was the very expressive syntax (such as the Yoda-esque return X if condition) or just the nature of TDD itself. Either way I’m really enjoying Ruby.

Dependency Injection inside a loop vs via a factory – part 2

Saturday, February 6th, 2010

In my last post I compared calling Ninject inside a loop during object contruction vs calling Ninject once and using a factory class to return a singleton. That wasn’t an entirely fair comparison as Ninject was creating a new instance of the injected class every time, which I thought may be part of the cause of the difference in performance. So I’ve changed my test a bit so that Ninject uses a singleton as well.

Originally the Ninject kernel binding was like this:

NinjectContainer.Kernel.Bind<IAdditionProvider>().To<AdditionProvider>();

That tells Ninject to create a new instance of AdditionProvider every time. To get it to use the same instance – in effect a singleton – I changed the binding to this:

NinjectContainer.Kernel.Bind<IAdditionProvider>().ToConstant(new AdditionProvider());

I expected to see a huge performance gain, and feel like an idiot. There was a bit of a gain:

That’s roughly 8 seconds (or 12%) less then the 1m5s taken the first time around. So there’s a good gain to be had using ToConstant() to avoid creating unnecessary instances of the injected class, but still nothing like the benefits of only directly using Ninject outside of the loop.

Dependency Injection inside a loop vs via a factory

Saturday, February 6th, 2010

I may have gone overboard with implementing dependency injection using Ninject on a project at work. I ended up with multiple calls to the kernel when creating each object. Worse yet I’ve used the [Inject] attribute to implement the binding, building up hundreds of dependencies on the Ninject library. At the time this seemed to make implementing things easier, especially as this was the first time I had used a dependency injection library, and I didn’t see a problem with a dependency on what seems like a core component.

I separated out 30 or so repositories, set up a heap of fakes, hooked up a handful of tests, and jumped into implementing the latest feature. Everything went well in development, I deployed, and all was shiny. Then the trouble started.

First the users started complaining about speed. Some operations were taking 10-20 times as long to run as before. That was because of calls to Ninject happening whenever many objects were being created, and inside of loops. Then some older Winforms components turned out to crash in the designer. That was due to the Ninject kernel not being set up when the component is executed by the designer – the new dependency on Ninject was failing. Then I read an article by Bob Martin and several of his tweets on the subject where he talks about the dependency framework itself becoming a dependency. Got that right.

I decided to replace the direct dependency injection via Ninject with a factory. This way the factory is the only place with the dependency on Ninject, and has the option of returning a mock if there is Ninject isn’t configured (to deal with the designer issues). It also lets me inject the dependency only once and reuse the result.

I set up a simple test to see what effect moving the dependency injection out of the loop would have on the speed. The first consumer of the test is has the DI on construction:

class InjectionTester
{
    [Inject] public IAdditionProvider Adder { get; set; }
    public int DoAdd(int a, int b) { return Adder.Add(a, b); }
}
...
// test using injection in the loop
for (int i = 0; i < 1000; i++)
{
    for (int j = 0; j < 1000; j++)
    {
        var tester = NinjectContainer.Kernel.Get<InjectionTester>();
        tester.DoAdd(i, j);
    }
}

The second consumer of the test uses a factory to get the dependency:

class AdditionProviderFactory
{
    public static AdditionProviderFactory Instance = new AdditionProviderFactory();

    IAdditionProvider additionProvider;
    object additionProviderLock = new object();
    public IAdditionProvider AdditionProvider
    {
        get
        {
            lock (additionProviderLock)
            {
                additionProvider = additionProvider ?? NinjectContainer.Kernel.Get<IAdditionProvider>();
            }
            return additionProvider;
        }
    }
}
class FactoryTester
{
    IAdditionProvider Adder = AdditionProviderFactory.Instance.AdditionProvider;
    public int DoAdd(int a, int b) { return Adder.Add(a, b); }
}
...
// test using the factory
for (int i = 0; i < 1000; i++)
{
    for (int j = 0; j < 1000; j++)
    {
        var tester = new FactoryTester();
        tester.DoAdd(i, j);
    }
}

The results are pretty impressive (looping a million times):

Thinking about it now it’s pretty obvious that DI is going to be a bit expensive, but seriously, using a factory is over 200 times faster. That should keep em quiet.

Using Jeditable for inline editing

Thursday, February 4th, 2010

Using the Jeditable plugin for jQuery enables inline editing of a block of text. This makes it easy to take a static view and simply drop in editability. Say we start with the following HTML:

<label>Name:</label> <span class="employeeName">Ben Scott</span><br/>
<label>Rating:</label> <span class="employeeRating">Highly awesome</span>

We want to be able to edit the employeeName and employeeRating spans. We need two actions (asssuming an MVC framework) to update the name and rating. The URLs might be something like /employee/set_name/{id} and /employee/set_rating/{id}. Each action should accept HTTP POST, take the new value in $_REQUEST['new_value'] or similar, and return a HTTP status of 200 on success and 500 on failure, with the error message in the response. For example, using Slab (my PHP5 MVC framework, in development) the set_name action might be like this:

class EmployeeController extends AppController {
	function set_name($id) {
		$this->Employee->save(array(
			'id' => $id',
			'name' => $this->data['new_value']);
		));
		return $this->ajaxSuccess($this->data['new_value']);
	}
}

Slab catches uncaught exceptions and returns an AJAX failure with the exception message as the body of the response.

To hook up the fields to the actions, modify the HTML to include the URLs to the actions. While this means the markup has behavioural elements and isn’t purely presentational (and has a non-standard attribute), it makes the script a bit simpler and easy to move into a static .js file, and is a quick way to get a page working.

<label>Name:</label> <span class="employeeName" editUrl="/employee/set_name/7">Ben Scott</span><br/>
<label>Rating:</label> <span class="employeeRating" editUrl="/employee/set_rating/7">Highly awesome</span>

Now for the script itself:

$(function(){
	$('.employeeName, .employeeRating').editable(
		function(value, settings) {
			return $.ajax({
				url: $(this).attr('editUrl'),
				data: { 'new_value': value },
				async: false,
				type: 'post'
			}).responseText;
		}, {
			indicator: 'Saving...',
			tooltip: 'Click to edit',
			onblur: 'submit'
		}
	);
});

The first argument is a function that returns the new value of the field. This is important when doing things like replacing line breaks with <br/> which we’re not worrying about, but it also gives us the ability to write our own AJAX code. By default Jeditable makes assumptions about how the update is done. The async option in the call to $.ajax() blocks until the call returns, and lets the function return the response of the AJAX call. The second argument are options to set some text to show while calling the update function, the tooltip to display when hovering over the span, and to submit changes on blurring the input which makes it seem a bit more usable when there are multiple fields.