Use of functions in Python

Asked

Viewed 243 times

3

I know that it is possible to create functions in the Python to perform certain tasks that normally need to be performed several times within an application.


Ex: Paint shop program that calculates the area to be painted and the amount of paint needed.

def areaTinta(altura, largura):
    area = altura * largura
    tinta = area / 2
    print('-' * 50)
    print(f'Serão necessários {tinta:.2f}l de tinta para pintar uma parede de {area:.2f}m².')

The point is:

  • Functions really only should be used in cases that there is repetition of code?
  • It is wrong to use them for simpler cases where there is no, for reasons of Clean Code or system optimization?
  • IF be used "unnecessarily" what the consequences of that in my application?.

3 answers

4


Think of a function whenever you want to do something specific. Let’s use your code as an example:

def areaTinta(altura, largura):
    area = altura * largura
    tinta = area / 2
    print('-' * 50)
    print(f'Serão necessários {tinta:.2f}l de tinta para pintar uma parede de {area:.2f}m².')

Your job is to do four different things,

  1. Calculate the area to be painted.
  2. Calculate the amount of paint needed.
  3. Display the - fifty times on the island.
  4. Display the message to the user stating the area to be painted and the amount of paint to be used.

Note that you have assigned various responsibilities to your role areaTinta(), see that the function’s name by itself says a thing and the function proves other things.

Abstraction

Isolate something from the whole, isolate the operations contained in its function areaTinta(). This applies as a form of generalization, whether with parameters or not. And bearing in mind that the function makes a only thing, we can isolate some parts of the whole.

Take the example:

def calcularArea(altura, largura):
    return altura * largura

def calcularQuantidadeTinta(area):
    return area / 2

I divided your function areaTinta() in two, one that calculates only the receiving area as parameter altura and largura, and another that calculates the amount by dividing the area for 2, thus isolate the data processing in separate functions, giving more abstraction and meaning to the code.

And you apparently don’t need to display the message to the user within the function itself? Since there is no context, let’s use the function print the overall scope of the programme.

Behold:

def calcularArea(altura, largura):
    return altura * largura

def calcularQuantidadeTinta(area):
    return area / 2

area = calcularArea(2, 6)
tinta = calcularQuantidadeTinta(area)

print(f'Serão necessários {tinta:.2f}l de tinta para pintar uma parede de {area:.2f}m².')

Exit

It will take 6.00l of paint to paint a wall of 12.00m².

Realized the difference now in the use of functions?

Note that now the two functions have assumed unique responsibilities, that is, to do a single thing. And it is interesting that you learn more about abstractions of functions and study about the DRY.

3

The use of the functions is not only for repeated code. They can be used to encapsulate snippets of code and improve reading.

Imagine a code that is dealing with the solution of a problem and in the middle of it is necessary the configuration of a device to proceed. Because of the configuration you totally lose the line of reasoning and disturb the understanding of the code. In such cases it is worth encapsulating in function.

On the other hand, unnecessary encapsulation can cause discomfort and difficulty for those reading the code. Imagine a code that encapsulates everything in functions and, for you to understand, you have to jump from one side to the other. An absurd example would be a code to add up two numbers and print them on the screen and you do one function to print and another to add up. Quite unnecessary, don’t you think?!

In the end, what defines this is you adopting a form of presentation of your code to better expose your idea. You always have to keep in mind that your program should be intelligible to whoever comes after. Empathy and putting yourself in your colleague’s shoes is essential in those hours.

2

The functions or methods are very important and serve to divide the code and keep it organized, when we start to create several objects or modules (link 1) in Python we need to divide the code snippets so that each has a unique responsibility, this rule is part of a set of good practice rules called SOLID (link 2). As your code grows, you will be grateful for having done everything separately and organized. Follow the links for more information.

1 - A module is the same as a Python class?

2 - https://medium.com/equals-lab/princ%C3%Adpios-s-o-l-i-d-o-que-s%C3%A3o-e-porque-projetos-devem-utiliz%C3%A1-los-bf496b82b299

Browser other questions tagged

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