Answer the question
In order to leave comments, you need to log in
Is it good practice to use many methods/functions all the time?
Imagine a task: you need to make a function that should calculate some geometric characteristics based on some data. And there are a lot of these characteristics.
So, to find each characteristic, is it better to have its own function?
And are there any recommendations on the length of lines in functions?
Answer the question
In order to leave comments, you need to log in
It's best to take it out, it's a good practice to put different code into separate functions. Then it’s more convenient to read and refactor and whatever.
if the intended block of code will be used several times in different places, then do it as a function. If not, separate with comments what this block is for and that's it.
The more compact the code, the better. Functions and procedures exist precisely for this task, and you should always try to find common features in different algorithms and take this common feature into a separate function (if, of course, there are many of them).
> And are there any recommendations on the amount of lines in functions?
Depends on the language.
Simple rules that I read in one of the books and try to use:
1. 1 case = 1 function.
Those. in your case - there should not be a function that immediately calculates both the surface area and the volume of the object
2. if the code is used in more than 1 place - we take it into a separate function
3. the normal length of the function is no more than 1 screen.
If more - it is worth considering how to share it.
4. Ideally, the function should not deal with several things:
count, crawl into the database, take up the output.
there should be 1 function for each task.
Sometimes each characteristic has its own function.
Sometimes, if the set of characteristics is in some sense homogeneous (projections of the model onto three coordinate planes, the number of red / green / blue edges ...), you can pass some attribute of the characteristic as a parameter - then one function will calculate any of several characteristics.
Sometimes, if it is convenient to calculate several characteristics together, and they are logically related to each other (and with a high probability will be required together) - combine them into a structure and force the function to fill it all.
Sometimes - when to calculate the characteristics it is no longer necessary to climb into the giblets of the object, but you can use other characteristics, and, possibly, some iterators, and besides, the calculation itself is time consuming and requires complex algorithms - move this calculation to a separate class.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question