Pergunta

consider (python):

assume global functions: default_start(), main_behaviour(), default_end(), custom_start(), and custom_end() just as code filler for illustration purposes.

class Parent:
    def on_start_main(self):
        default_start()

    def main_behaviour(self):
        main_behaviour()

    def on_end_main(self):
        default_end()

    def main(self):
        self.on_start_main()
        self.main_behaviour()
        self.on_end_main()

class Child(Parent):
    def on_start_main(self):
        custom_start()

    def on_end_main(self):
        custom_end()

vs

class Parent:
    def main_behaviour(self):
        main_behaviour()

    def main(self):
        default_start()
        self.main_behaviour()
        default_end()

class Child(Parent):
    def main(self):
        custom_start()
        Parent.main_behaviour(self)
        custom_end()

I don't know which of these is preferable, but I suspect the second. Is this a matter of taste or are there concrete reasons why one is better than the other?

Thanks

Foi útil?

Solução

I would prefer the first solution for one simple reason:

What if you want in the Child class to override just the on_start_main and leave the on_end_main unchanged.

If you choose the first solution, then you just override the on_start_main method and your done. You don't have to know or even care what the Parent class does in it's on_end_main.

If you choose the second solution you have to know exactly what the Parent class exactly does in the main method, so not only you have to dig into the source of the Parent class but also duplicate the code already written.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top