NewNewton
NewNewton

Reputation: 1065

python, functions in general: return string and print function OR just print statement in function?

At first: This is only a question about the "cleanest" way to code.

I've written a Python script/programm with several classes and functions, to store some spanish vocabulary. At the end all comes together in the interface function, which passes on some user input. Roughly like this:

if __name__ == "__main__":
    while True:
    answ = raw_input("Please select an option below:\n"
                     "(1) New Vocab\n"
                     "(2) Testing Vocabs\n"
                     "(3) Search vocab (Edit|Delet)\n"
                     "(4) List all vocabs\n"
                     "(5) Show Boxes\n")
                     #...blabla

    os.system("clear")

    if INPUT(answ,"1"):
        IF_new_vocab(book)
        book.save_dic()

    elif INPUT(answ,"2"):
        IF_voc_query(book)
        book.save_dic()

    elif INPUT(answ,"3"): 
        book.search_vocab()
        book.save_dic()
    elif INPUT(answ,"4"):
        print book.show_cache()    #A

    elif INPUT(answ,"5"):
        book.update_boxes()
        book.show_boxes()          #B
    #...blabla

Now my QUESTION is: Should I return a string and use print as late as possible, which would be the "interface" in this case. (e.g. option A)? Or should the output, which is in most cases a string, be printed by the method/function itself (e.g. option B)?

I know it doesn't affect the overall output at all. But I was always wondering if there is a convention or reason to prefer one option.

Upvotes: 1

Views: 3857

Answers (1)

Teddy Ward
Teddy Ward

Reputation: 450

Definitely have the function return the string and print as late as possible!

Printing early would violate the open-closed principle. That is, in general your code should strive to be closed to modification. This ensures that if you decide, later, that you want to print the string output twice, or pass the string output to an API, or save the string output in a file, you don't have to modify the original code which puts together the string (the book.show_cache function)

In some scenarios, you may want to sometimes print the output, sometimes save it in a file, sometimes pass it to an API, and sometimes do something else. In this case, you would be happiest if your code up to that point had been open to extension, so that you can simply add different functions / interfaces / handlers to deal with the output in different ways, rather than having to rewrite variations of the show_cache function 3-4 different times to handle the different usages. This is the basis of the strategy design pattern!

You might then end up with something that looks like this:

def print_cache():
  print book.show_cache()

def save_cache_to_file():
  save(book.show_cache())

def search_google_for_cache():
  // google.search(book.show_cache())

Which is a lot shorter than:

def print_cache():
  vocab = ['hola', 'como', 'estas', 'bien', 'y', 'tu']
  // more code?
  print vocab

def save_cache_to_file():
  vocab = ['hola', 'como', 'estas', 'bien', 'y', 'tu']
  // more code?
  save(book.show_cache())

def search_google_for_cache():
  vocab = ['hola', 'como', 'estas', 'bien', 'y', 'tu']
  // more code?
  // google.search(vocab)

Plus, in the second example, if you want to add more vocab, you have to remember to do it in three different places, making your code easier to maintain!

Upvotes: 2

Related Questions