Search code examples
design-patternslanguage-agnosticsoftware-design

Unused argument in parent class, that is used in subclass. Bad policy?


I have a parent class with an unused argument in private function _f(i)

class Parent:
    def _f(i):
        return range(m)

    def g():
        for i in range(n)
            for j in _f(i)
                # do something

which is intended to be used in overriden method in subclasses

class Child:
    def _f(i):
        return range(i, m)

Having an unused argument feels ugly, but it saves me from code duplication in method g(). Is there any suggested way to avoid it, or should I leave it as it is?


Solution

  • It looks like the objective is to reuse the code in the g function such that the range of the second for loop can be changed through class extension. A better solution would be to get rid of the i parameter from the f function altogether and use instance variables instead.

    Parent class

    class Parent:
        def _f():
            return range(m)
    
        def g():
            for i in range(n)
                for j in _f()
                    # do something
    

    Child class

    class Child:
        def __init__(self, i):
             self.i = i
    
        def _f():
            return range(self.i, m)
    

    An immediate advantage of this approach would be that the contract for the f function doesn't need to be changed if one chooses to add more inputs that need to be used within the function in the future.

    Note : This question has been marked as language agnostic. Any syntactical errors in the above code are intentional.