4 Jul 2007

Code Duplication

You might have heard people talking about not duplicating code so that it becomes easy to maintain. Back those days, I didn't know all these and used to make a hell lot of mistakes while programming. By the word mistake, I mean doing something that makes developing and maintaining software harder than it ought to be. Of course, that helped me learn a lot of principles. The first thing I learned from my mistakes is not to duplicate code/ideas. Since I was bit by duplicated code very often, I try my best to reduce duplication as much as possible. In this post I am giving a few examples to show how I try to avoid duplication. Obvious Duplication The first pattern I recognised in my code was something like the following.
if exam.mark >= 35:
    exam.result = 'pass'
    logging.debug('Setting result to pass.')
    return 'pass'
else:
    exam.result = 'fail'
    logging.debug('Setting result to fail.')
    return 'fail'
Obviously this code is duplicating ideas, so must be refactored. How will you refactor this to take away the duplication? I will write it this way:
if exam.mark >= 35:
    exam.result = 'pass'
else:
    exam.result = 'fail'
logging.debug('Setting result to ' + exam.result)
return exam.result
(To be more precise, I will also replace the literals 35, 'pass', and 'fail' with appropriately named constant variables.) More Subtle Cases This is (part of) a PyUnit test case for an imaginary function double, that takes a number and multiplies it by 2.
def testDouble(self):
    inp = 5
    expected = inp * 2
    actual = double(inp)
    self.assertEqual(expected, actual)
Here, I have used the variable inp to avoid having to duplicate the test input I am passing to double. As another example, see this code that assigns a grade to a student based on the mark they have scored.
if mark < 35:
    grade = 'N/A'
elif mark >= 35 and mark < 50:
    grade = 'D'
elif mark >= 50 and mark < 70:
    grade = 'C'
elif mark >= 70 and mark < 90:
    grade = 'B'
else:
    grade = 'A'
I would rewrite this code like this to avoid duplication of the boundary values (although this is a very small duplication).
if mark < 35:
    grade = 'N/A'
elif mark < 50:
    grade = 'D'
elif mark < 70:
    grade = 'C'
elif mark < 90:
    grade = 'B'
else:
    grade = 'A'
Tell me about the ways you follow to make your code more maintainable.

No comments:

Post a Comment