Deciding What Goes into a Function

Learn about the use of functions and how to write a function.

What goes into a function?

A function is a way for us to package a code block and give it a name. This is a good idea for several reasons. Previously, we talked about software modules and how it’s wise to divide our code into small parts because it will give us code that’s easier to read, update, and maintain. The same reason applies to functions because they also package our code into smaller units. Another reason we want to use functions is so we can easily reuse parts of our code.

When deciding what will go into a function, we can have one rule of thumb. A function should always do only one thing and it should be named in a way that reflects that. What this means is that if we have a function called send_email_and_print_invoice, we’re doing things wrong. This function does two distinct tasks and should, therefore, be two separate functions. We can rephrase this rule with a quote by Robert C. Martin, the author of an excellent book on writing clean code:

“A function should do something or answer something, but not both.”

Get hands-on with 1400+ tech skills courses.