This is not really language-specific, but I’ll use Python to explain my question.
My program has several nearly self-contained functions. The command line arguments select one of these functions, and provide the input file name. The function is then executed:
# main.py:
import functions
def main():
filename = sys.argv[1]
function_name = sys.argv[2]
function = getattr(functions, function_name)
result = function(filename)
# do something with result
# function.py contains all the functions:
def function1(filename):
# ...
I had a feeling that I should probably use classes rather than functions, so I wrapped each function in a class. But now each class looks pretty silly: it’s only instantiated once, and all it does is execute its constructor, which does exactly what my old functions did. Then I can call a certain method to retrieve the return value:
# new version of main.py:
import classes
def main():
filename = sys.argv[1]
cls_name = sys.argv[2]
cls = getattr(classes, cls_name)
calculation = cls(filename)
result = calculation.result()
# do something with result
# classes.py:
import functions
class Class1:
def __init__(self, filename):
self.result = functions.function1(filename)
def result(self):
return self.result
# functions.py is unchanged
This doesn’t seem to be any better than when I had functions. Is there a way to make my code object-oriented in a more useful way?
If you were writing Java or C# then you would implement these functions as static methods. In those languages all methods have to be part of a class due to the design of the language. In Python, whilst you can emulate a static method, there is absolutely no need to do so for this example.
Python’s creator, Guido van Rossum, has argued in favour of the use of functions rather than methods.
Whilst this is not directly related to your question it does challenge the sometimes dogmatic stance that methods are always to be preferred to functions.
In my opinion, in Python, using functions is a better solution than creating classes.