...

/

Deciding What Goes into a Function

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.”

What this means is that a function either should have a very well-specified task and only do that task and nothing else, or it should answer a well-specified question and only answer that question and nothing else. A single function should absolutely not do both of these things. Another quote from Robert C. Martin about functions is as follows:

“The first rule of functions is that they should be small.” ...