Why use single statement functions?


#1

I am wondering, why would we want to use functions that only have 1 statement?

This code:

def random_row(board):
    return randint(0, len(board) - 1)
def random_col(board):
    return randint(0, len(board[0]) - 1)

ship_row = random_row(board)
ship_col = random_col(board)

is essentially the same as:

ship_row = randint(0, len(board) - 1)
ship_col = randint(0, len(board) - 1)

What's the catch here? (Of course, other than being able to call the function multiple times with different inputs). Is such usage of functions an industry best practice? Just curious.


#2

i would like to quote donald knuth in this case:

Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.

okay, this might not be entirely speed related, but if you do one or the other is not that relevant (if you don't know who knuth is, please google this first)

one thing thought, i wouldn't do this:

ship_col = randint(0, len(board) - 1)

what if you decide to make an non-square board?


#3

Sometimes you want to abstract away an action so to not have to worry about how it's done, just that it is done. If the result is that reading the code becomes easier to grasp then you succeeded, otherwise not so much. Typically you also don't want to get into too much detail of how other parts of the code work because complicated interfaces makes it very difficult to make changes.


#4

Understood. Thank you! :slight_smile:


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.