I have a class in which there are several methods that can act as an “entry point” to its private innards (or the “fruit” thereof).
Said functions might be called multiple times throughout a single “pipeline” as triggered by such an entry point, but only the first call should act as the actual entry point in that it performs a certain initialization action.
Similar use cases show up in situations that aren’t necessarily object oriented, of course (off the top of my head: wrappers of recursive functions which initialize something before the recursion itself begins).
Here are examples of two ways by which I’d consider approaching this, illustrated Pythonically:
1. Wrapper Auxiliary Method
...
def cool_stuff(self):
self.__init()
self.__cool_stuff()
def __cool_stuff(self):
actual_coolness() # Might invoke __cool_stuff again.
...
2. Flag Argument With Default Value
...
def cool_stuff(self, _do_init=True):
if _do_init:
self.__init()
actual_coolness() # Might invoke cool_stuff again, albeit with init=False.
...
I was wondering if one is considered “preferable” given a language that supports both options, or if it’s purely a matter of “taste” (or, in other words: if a convention exists, and if it does, then whether it is mostly-arbitrary or more involved).
An upside I see for #1 is that it leaves implementation-y stuff out of the API (see my admittedly-hesitant use of a leading underscore in #2’s _do_init
to hint that it is by-design a strange “private argument”), while an upside I see for #2 is that it seems to usually be aesthetically neater, I think.
Shay is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.