Help a C++ coder see the light

holger krekel pyth at devel.trillke.net
Thu Jan 30 13:21:40 EST 2003


Mark Charsley wrote:
> I've been coding C++ for years now and Python for a few months. 
> Incidentally, I'd say that Python's greatest strength is that it took me 
> about two months to become as competent at Python as I was after two years 
> of C++.
> 
> However, what's nice flexibility in a small Python project (we're using 
> python to script a callback interface, and its very easy to support 
> arbitrary functions taking arbitrary arguments) would give me the 
> screaming heebie-jeebies in a larger project.
> 
> I'm used to the compiler/linker giving me a lot of reassurance that my 
> code works. Python removes that reassurance and just leaves it to runtime 
> errors.

I understand this situation and had it myself.  But i learned 
from people here on this list that writing "unit tests" is a
brilliant solution for the problems at hand.

Basically, type checks only ensure correct behaviour at a very
low level.  You can cover much more ground if you write little
tests (really twoliners in many cases) that check that your
methods actually perform as expected in a *semantic* way. 
 
> The most annoying is typos along the lines of:
> 
> if myVar < 0:
>     myVal = -myVar
> CalculateSquareRoot(myVar)

If this would be in a function 'square_root_abs' you would write

    def test_square_root_abs(self):
        obj = cls()
        self.assertEquals(1,square_root_abs(1))
        self.assertEquals(1,square_root_abs(-1))
        self.assertEquals(2,square_root_abs(4))

Of course you would continue to define what behaviour
you want for floats etc.pp.  Now this test catches a lot
more behaviour problems than compile-time type-checking
can do. 

Having a lot of tests like this makes a programmer's live
really less stressfull.  And python is good language to
write down simple tests.  With C++ & Java i never really
cared that much for fine-grained tests.  It was just to
painful especially during refactoring. 

    holger





More information about the Python-list mailing list