Tuesday, September 18, 2007

Get it real. Coding examples.

Enough theory, lets code. I guess you could prove all of your algorithms on paper. But most of the time we use an algorithm from a paper or from examples on the Internet and all you wanna do is to ensure that you've got it right.

Lets take a sorting method as an example. You wouldn't wanna invent an new algorithm for this, you probably wanna stick to quicksort or mergesort. These algorithms has already been proved so... let's go:

First write a test like:

def test_typical_sort()
array1 = [ 1, 5, 7]
array2 = [ 2, 4, 6 ]
sorted_array = sort(array2, array1)
assert sorted_array == [1, 2, 4, 5, 6, 7]

this will definitely break, I mean, we don't even have the method. So lets implement it.

def sort(array1, array2)
# insert random sort algorithm here

Now your test will work just fine. So lets test for some extremes.

def test_empty_test()
assert sort( [] , [] ) == []

And you could go on like that, you probably wanna test for some errorprone data, and so on. So when do you stop? Some say: 'test everything that could possible break'. I don't know if I agree, but it's a good thought. Some very useful hints on what to test are showed in this railscast. (Railscasts are a site with free video tutorial for rails but I think many of the stuff there is applicable for webprogramming in general. Check it out. )

No comments: