I sometimes find myself writing classes (in Python, in my case) that are used like this:
MyClass(some_args).go()
In other words, there's only one method in the class that any external code would call, and it will only ever get called once. There might be a return value from go()
but often there isn't, and when there isn't, I could even call go
from the class's __init__
.
So why even bother with the class, instead of just writing go()
as a standalone function? Because what goes on inside go
is complicated. There may be several levels of nested function calls, and there are certain pieces of information that are needed in different spots. If I try to write all this without a class, I end up with a many of the functions returning multiple values. Sometimes the argument lists also get uncomfortably long. If I wrap everything up inside MyClass
, then I can put all this information in member variables of the MyClass
instance. These become not-quite-global variables, and they're generally stuff that feels like it make sense to store in a class.
Does this practice have a name? Is it a pattern, or an anti-pattern? And if the latter, how should I structure my code instead?
MyClass
instance handles that for me.