Chapter 8. Reuse your code: Clean it with function detergent

 

This chapter discusses one of the most interesting and important topics: functions!

This chapter covers

  • What a function is
  • How a function is created and used
  • How to pass data to a function
  • How to receive data from a function

You’ve reached the eighth milestone: reuse your code. Before you get started, here’s the main thing you need to know about functions: functions exist so that you can reuse and clean your code.

Read on, and I’ll explain why you might want to have reusable code.

Reuse and clean your code with functions

You’re about to find out what a function is. I’ll start with a simple example.

Imagine that you’re playing a game on your computer. In this game, your character needs to jump over obstacles. You have three ways to make your character jump:

  • Press the J key.
  • Press the up-arrow key.
  • Press the spacebar.

Although it sounds like a simple thing, making a character jump in a game could take 40 lines of code or more.

Now think about the jump taking 40 lines of code. I won’t put a big block of code here, but look at the diagram in figure 8.1.

Figure 8.1. Painting a picture of a function

All three blocks of code do the same thing: make the character jump. As shown in the figure, you could type the same 40 lines of code for jumping for all three events, but there are a few problems with that:

Giving info to your reusable code

Getting info from your reusable code

Check your app knowledge

App-Exercise: Virtual Dice

App-Exercise: Rock Paper Scissors

App-Exercise: Money Denomination