-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?

Karl Bielefeldt
  • 146,727
  • 38
  • 279
  • 479
JungleDiff
  • 109
  • 2
  • 1
    Possible duplicate of https://softwareengineering.stackexchange.com/questions/350187/are-private-methods-with-a-single-reference-bad-style/350314#350314 – Samuel Jun 14 '17 at 19:57
  • 2
    Possible duplicate of [Should I extract specific functionality into a function and why?](https://softwareengineering.stackexchange.com/questions/166884/should-i-extract-specific-functionality-into-a-function-and-why) – gnat Jun 14 '17 at 20:10

2 Answers2

3

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.

Timothy Truckle
  • 2,336
  • 9
  • 12
  • 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
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.

Gaboik
  • 16
  • 1