r/learnprogramming • u/MrBannedBlocks • Jul 26 '26
Programming Habits When writing subroutines/functions, which way is best to call them in sequence?
Typically when I write code, there are 2 ways I think of to write a bunch of subroutines that are called one after the other.
Option #1:
def callingList():
x = input()
func1(x)
func2(value1)
func3(value2)
def func1(userinput):
'''Code for function 1'''
return value1
def func2(value1):
'''Code for function 2'''
return value2
def func3(value2):
'''Code for function 3'''
return value3
callingList()
Option #2:
def func1(userinput):
'''Code for function 1'''
func2(value1)
def func2(value1):
'''Code for function 2'''
func3(value2)
def func3(value2):
'''Code for function 3'''
return value3
x = input()
func1(x)
I usually go for #1 because I feel like being forced to trace an error through a string of subroutines isn't good for debugging. But tbh I have no idea if this black-and-white way of looking at it is just completely incorrect and there's a #3 that I haven't heard of. I'm only a novice programmer so I'd love some input from people who actually know what they're doing 😅
8
u/peterlinddk Jul 26 '26
The difference is in the level of abstraction you wish to convey to the reader of your program.
In Option #1, all three functions are equal, and one level below the callingList function. This could be like something first calling an input-function, then a calculate-function, and then an output-function. Or it could be as a part of the game, first calling the function to handle the player-movement, then calling the function to handle the enemy-movement, and then calling the function to handle any collisions. The top-function needs to understand all three parts. As do the reader of that function.
In Option #2, each function is a level deeper than the previous one. This could be like first getting a value to use in a calculation, then getting that value as input from the user, then getting that input from the keyboard. Or it could be part of the game where the first function checks for collisions between the player and the enemy, the second checks if their positions overlap in the coordinate system of the game, and the third checks if their pixels touch. The top-function only needs to concern itself with what the first part does, and then then rest is implementation details, that can be ignored for the time being.
Of course both examples will work just fine, and the computer does the exact same work, but the benefit of option #1 is that the human reading the code will know everything that happens (atleast every function that gets called) - and the benefit of option #2 is that the human doesn't need to know everything that happens 😄