When should functions be used?

I would like to know, when should functions be used, because i see a lot of guys making functions to continue the code instead of parsing arguments and returning the result.

I mean functions like these:

def foo():
   print("How are you?")

print("Hi.")
foo()

(This code is non-sense and unpractical. It is just an example.)

Why should we use functions at all instead of just having the code in one continous place?

Upvotes: 0

Views: 76

Answers (1)

timgeb
timgeb

Reputation: 78680

What's easier to read and maintain?

Version 1:

db = init_database()
connect_to_database(db)
target = 'funny_cats'
cats = db.fetch(target)

Version 2:

5000 lines of code resembling the bodies of the above function calls

What's easier to read and maintain?

Version 1:

for user in lots_of_users:
    if not polite(user):
        ban(user)

Version 2:

for user in lots_of_users:
    30 lines of code for body of polite
    30 lines of code for body of ban

Consider that you want to execute the same piece of code at different locations in your program.

some_function()
[100 lines]
some_function()
[100 lines]
[conditional branch possibly calling some_function()]

With a function, you just call that function at the desired locations. Without a function, you need to replicate the code everywhere. When you want to change the behavior of these code blocks, you will have to look for all the places you replicated the code instead of just adjusting the one function. If you miss one location, you will introduce a bug.


Functions are first class objects in Python, which is fancy talk for the fact that they behave just like any other more trivial object - you can put them inside lists or use them as arguments to other functions.

This allows you to view functions as self-contained pieces of code that can be executed by other pieces of code dynamically, for example by passing a sorting criterion to the built in sorted function.

>>> def criterion(sequence):
...     return sequence[-1]
... 
>>> list_of_sequences = [(1, 2), (5, -1), (2, 10)]
>>> 
>>> sorted(list_of_sequences, key=criterion)
[(5, -1), (1, 2), (2, 10)]

Upvotes: 4

Related Questions