3

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?

5

If you are working on a script where you know (or suspect) that it will later be used as a library in a larger project, then it is easier to start out with writing the functionality in a library and then tagging on a driver script to use the library from the command line.

There are no specific design patterns to help in creating good API's. It requires mostly a shift in thinking from "a script that produces human readable output" to "a library whose output can be easily used by other software components". The biggest change there is that a library usually does not interact directly with the user.

  • 1
    so you can think of a command line as a form of GUI. Put parameter parsing in a command line app that does nothing but call the library. The problem then becomes one of choosing whether to build the library as static or dynamic. – gbjbaanb Jul 9 '14 at 13:16
  • change your brain to change your code ;) well then i will try to do this! – reox Jul 10 '14 at 9:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.