I develop quite often scripts that are primary used as a console application but later they are used in other scripts, webservices and other things where it is very convenient, to just import the script and call methods directly rather than using a Process and parsing stdout.
The question is now, what is a good design strategy to develop such scripts? I have an example here in python:
def main(): # do stuff print("Found several results here:") for foo in bar: print("result: %s" % foo) if __name__ == "__main__"(): main()
this one could be easily rewritten to something like this:
def main(): result = some_function() print("Found several results here:") for foo in result: print("result: %s" % foo) def some_function(): # do stuff return bar if __name__ == "__main__"(): main()
But in most of my cases this is not so easy. But how to deal with this problem when the program does quite a lot of output, like different analyses or several steps or the return value of an API function would be something like a list of dict of list of tuples (or even more complicated structures)? Would it be good to encapsulate every step into a single method and run them one after another? What design patterns can be used to write good progamms that can be easily reused as APIs?