-3

Say I have this function

def function_A():
    blah
    blah
    blah
    return A

When is it justified to make that long function_A into smaller pieces, say function_B and function_C and then call function_B and function_C inside the function_A?

0

A function or method is meant to only accomplish ONE purpose. If the functions is called add(x, y) you can't have the function add the numbers and then divide them. These are two separate operations.

Also, to reiterate what was said by Timothy, if you feel the need to comment your function (other than the function header documentation), there's a good chance it is too complicated.

Also, an even more general rule of thumb that can be useful to keep in mind is that your functions probably don't need to be longer than 35 lines.

2

a possible rule of thumb is:

when you feel the need of placing comments to "structure" the method the parts separated by these comments should go into separate method with names derived from the comments you might want to place.

It is a good habit to keep a single layer of abstraction in your methods. That means that you either call other methods or do calculations, not both.

  • 1
    "That means that you either call other methods or do calculations." I don't think there's much else you can do. Or do you mean "Don't mix method-calling and calculations"? – JAB Jun 14 '17 at 21:01
  • @JAB Yes, that's what I meant. – Timothy Truckle Jun 14 '17 at 21:05
  • 1
    I like this answer personally. Though i would say that also, your method should do one thing, or focus on one thing. So take the function_A example. Its focus might be on finding an item in a database, then passing it to another function. Functions should only do one thing, and as such once it doesn't, you need to start breaking it down. – Rhys Johns Jun 14 '17 at 22:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.