What Is Modular Code

Modular programming is a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect of the desired functionality. Modular code is code that is separated into independent modules. The idea is that software should hide the internal details of individual modules behind a public interface, making each module easier to understand, test, and refactor independently of others. Modularity is not just about code organization.

Functions Make Modular Code

Functions make programs easier to read, write, and debug. A function is a block of code packaged together with a name. They’re a core feature of all programming languages, yet depending on the language, they may be called subroutines, methods, or some other name, but it’s all referring to the same thing, a way to break up your code. In this tutorial, we’ll call them functions. You’ve already used a few functions like print() to show something on the screen and input() to get a response from the user. There are hundreds of other functions in Python that we’ve yet to explore. One key benefit of functions is that they help us avoid repeatedly writing the same lines of code. You can think of it this way. When you get ready to go to work, it’s almost always the same steps. Some steps include getting out of bed, showering, and eating breakfast. That sequence in code might look like this.

print('Get out of bed')
print('Take a shower')
print('Eat breakfast')
print('Turn on laptop')

We teach the computer how to do something one time, and from then on out, we call the function by its name, and the work gets done—no need to repeat ourselves. Without functions, we’d have to copy and paste this code repeatedly each time we wanted to go to work. We can turn something like this into a function to make it more modular.

def go_to_work():
    print('Get out of bed')
    print('Take a shower')
    print('Eat breakfast')
    print('Turn on laptop')

go_to_work()

You are probably half asleep when getting ready for work, so you might forget the four steps to prepare for work. By turning those steps into a function, there is only one step that needs to be taken. In other words, you call the function one time to accomplish four steps at once. I’m sure you can see how functions can be very productive.

Creating And Calling Functions

Functions in Python are created by using the define statement. That starts with the def keyword, which is short for define. This lets Python know that we are ready to make a function. Next, we need to give our function a unique name. We’re going to call this one say_hi. We have to give our function a unique name, just like variables. We could name it anything we want, but we have to make sure we respect the rules of the Python language. We next need to add an opening, closing parentheses, and then a colon. This is the requirement of Python syntax for creating a function. Once we hit Enter, the IDE automatically indents the following line of code because it’s trying to help us out. It knows that functions have to be indented. We often call the code block that belongs to a function its body, so when you hear function body, that’s simply another way of referring to the code that the function will execute. To get the hang of this syntax, we’re only going to have one line inside of our function’s body, and it’s going to be a print statement that says, “Hi There!”. Creating a function means that we taught the computer how to do some work, but to have that work done, we need to call the function first. In Python, you call a function using its name, followed by a set of open and closed parentheses.

def say_hi():
    print("Hi There!")


say_hi()
# Hi There!

This code example above defines a function called or invoked once. The great thing about a function is that you can reuse it over and over anywhere you like in your program. Now you know how to define and call your very own functions. While this may seem basic, soon, you’ll learn how powerful it is to incorporate functions in your programs.

Setting Parameters And Arguments

I can assemble my burrito differently when visiting my favorite Mexican establishment for lunch. Depending on the amount of money I’m willing to pay, I can add different ingredients and different amounts of ingredients to my burrito. Let’s see a function that simulates our Burrito ordering experience. This function is defined as order_burrito(), and then we have our open and close parentheses. Inside, we have our burrito assembly steps. First, we have the steps for the single meat offering. Then, a little further down, we have the steps for the double meat option. In the function definition, there is a parameter with the name amount_paid. A parameter is a placeholder for a value that will be passed into the function when it is called. When you call the function and pass in a value, it is referred to as an argument at that time.

def order_burrito(amount_paid):
    if (amount_paid == 10):
        print("Scoop of Steak")
        print("Scoop of Rice")
        print("Lettuce and Cheese")

    if (amount_paid == 12):
        print("Scoop of Steak")
        print("Scoop of Steak")
        print("Scoop of Rice")
        print("Lettuce and Cheese")


order_burrito(12)
# Scoop of Steak
# Scoop of Steak
# Scoop of Rice
# Lettuce and Cheese

When the function above gets called, and the value of 12 is passed in as the argument, we see that the result is a burrito with double meat assembled. Parameters and arguments are very important for functions because they allow the programmer to alter a function’s behavior based on the value passed into the function. If we only had $10 available, then the result of our order would be just a single meat offering.

order_burrito(10)
# Scoop of Steak
# Scoop of Rice
# Lettuce and Cheese

Returning Values From Functions

The Python return statement is a unique statement that you can use inside a function to send the function’s result back to the caller. A return statement consists of the return keyword and an optional return value. How does the return statement work in Python? Let’s look at this example.

def my_func1():
    print("Howdy!")
    return None


def my_func2():
    print("Howdy!")
    return


def my_func3():
    print("Howdy!")

They all return None, and that’s it. However, there is a time and place for all of these. The following instructions are how programmers should use the different methods, but they are not absolute rules, so you can mix them up if you feel necessary.

Using return None: This tells that the function is meant to return a value for later use, and in this case, it returns None. This value None can then be used elsewhere. return None is never used if there are no other possible return values from the function.

Using return: This is used for the same reason as a break in loops. The return value doesn’t matter; you only want to exit the whole function. It’s advantageous in some places, even though you don’t need it that often.

Using no return at all: This will also return None, but that value is not meant to be used or caught. It simply means that the function ended successfully. It’s the same as a return in void functions in languages such as C++ or Java.

Let’s modify our original burrito ordering function to use the return keyword.

def order_burrito(amount_paid):
    if (amount_paid == 10):
        print("Scoop of Steak")
        print("Scoop of Rice")
        print("Lettuce and Cheese")
        return "You got the single meat burrito!"

    if (amount_paid == 12):
        print("Scoop of Steak")
        print("Scoop of Steak")
        print("Scoop of Rice")
        print("Lettuce and Cheese")
        return "You got the double meat burrito!"


result = order_burrito(10)
print(result)
# Scoop of Steak
# Scoop of Rice
# Lettuce and Cheese
# You got the single meat burrito!

Functions Across Languages

We’ve seen functions that fall into four main categories. Those with no parameters and no return value, no parameters but return a value, those with parameters that don’t return a value, and finally, those with both parameters and a return value. But so far, we’ve only seen these functions in Python. Let’s take a look at how a few other languages handle functions. First up is Java. This is the no parameters and no return value example of a function.

void say_hi() {
    System.out.println("Hi!");
}

The curly braces are used to mark off the function’s body, like how we saw curly braces used for the code block of an if statement. Also, we have the function name followed by empty parentheses, just like we do in Python, but what’s different here? It’s the void keyword in front of our function name. It means that our function doesn’t return a value, similar to how we can’t get any money back from a voided check. It has no value. Unlike Python, Java requires that you specify the return type of a function explicitly, even when that function isn’t going to return a value. As you explore programming languages now, I encourage you to compare languages, as it makes it easier to learn.