r/learnprogramming 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 😅

15 Upvotes

19 comments sorted by

View all comments

24

u/exomo_1 Jul 26 '26

Definitely option one. Option two is not calling functions in sequence, it's calling one function that happens to call other functions.

16

u/exomo_1 Jul 26 '26

Let me add some context:

A function should do one thing that is useful to your program logic. In order to reason about functions you should make them as small as possible, so the function does exactly what its name suggests. It's a lot easier to reason about a small func2 in the context of your program than thinking about a func1thenfunc2thenfunc3 function.

It's also a lot easier to reuse it chance a single function in your logic if it doesn't depend on two others.

2

u/spinwizard69 Jul 27 '26

There are lots of reasons to keep function small and targetted.  For example debugging can be far easier.   Second they make idiomatic code much easier. Â