Is it wise to implement functions that only call for other functions?

Asked

Viewed 253 times

12

I learned that functions should be small and concise. This rule would also apply to functions like this?

def run_game(self):
    process_input()
    update_state()
    render()

What I mean is: run_game appears to be trying to do more than one thing at the same time, but it seems to me that it is being used as an organization unit, performing the functions that would make up the labeled process run_game.

This invalidates the principle of "of one Thing well"? It is normal to use functions as units of organization and to gather related functions in a main function?

1 answer

9


Yes, this form of organization is normal. Its function run_game is not trying to "do more than one thing at the same time", it is simply operating in a higher level of abstraction.

For example, a function that reads a file and stores its contents in a data structure would do something like:

def foo(arquivo):
    with open(arquivo, 'r') as f:
        conjunto = set([x.strp() for x in f.readlines() if x.strip()])
    return conjunto

This function is making use of the file manipulation and set creation library. Each of them "just do one thing and do it well", but it takes combine their functionality to implement something more complex (get the set of non-empty lines from the file).

If another function bar needs a set of lines stored in a file, it will make use of of function foo as if it were a simple command like x + y: since at the level of abstraction of bar things like "getting a set of a file" are a simple operation - not a set of operations. In the same way, at the abstraction level of foo, things like "read all lines of a file" are one operation only, although in reality it involves a number of lower-level operations.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.