Is code duplication allowed in this instance?

Lie Ryan lie.1296 at gmail.com
Fri Jul 3 08:49:21 EDT 2009


Klone wrote:
> Hi all. I believe in programming there is a common consensus to avoid
> code duplication, I suppose such terms like 'DRY' are meant to back
> this idea. Anyways, I'm working on a little project and I'm using TDD
> (still trying to get a hang of the process) and am trying to test the
> functionality within a method. Whoever it so happens to verify the
> output from the method I have to employ the same algorithm within the
> method to do the verification since there is no way I can determine
> the output before hand.
> 
> So in this scenario is it OK to duplicate the algorithm to be tested
> within the test codes or refactor the method such that it can be used
> within test codes to verify itself(??).

When unittesting a complex output, usually the first generation code
would generate the output and then you (manually) verify this output and
copy the output to the test code. The testing code should be as dumb as
possible to avoid bugs in the testing code itself. The most important
thing is not to use a possibly buggy algorithm implementation to check
the algorithm itself. If your test code looks like this:

# this the function to be tested
def func(a, b):
    return a + b

class TC(unittest.TestCase):
    def test_foo(self):
        a, b = 10, 20 # worse: use random module
        result = a + b
        self.assertEqual(func(a, b), result)

then something is definitely wrong. Instead the testing code should be
simple and stupid like:

class TC(unittest.TestCase):
    def test_foo(self):
        self.assertEqual(func(10, 20), 30)

There are exceptions though, such as if you're 100% sure your
first-generation program is correct and you simply want to replicate the
same function with different algorithm, or probably optimizing the
function. For that case, you could do something like this:

def func(a, b):
    # some fancy new algo
    pass
class TC(unittest.TestCase):
    def original_func(self, a, b):
        return a + b
    def test_foo(self):
        self.assertEquals(func(a, b), self.original_func(a, b))



More information about the Python-list mailing list