Understanding Functions

There is a very short list of programming structures you have to learn to be reasonably comfortable in most modern object-oriented languages. Functions are one of them.

Bang on De Drum All Day

Here’s a secret about programmers: they are inherently lazy. The less typing a programmer can do, the better. Programming is all about dreaming up complex tasks that programmers don’t want to do, and delegating those tasks to a computer so that the programmer can blow off and watch cartoons the rest of the day.

Many programming structures are designed to make a programmer’s life easier. And a programming rule of thumb is generally that if you have to type something twice, there’s an opportunity to make your code more efficient.

Functions make your code more efficient. Let’s imagine a game where we need to create a bunch of monsters. If you’ve read Understanding Loops, you know that you can set up a loop to run an action multiple times. i’ll use a combination of pseudocode (in comments) and real code to demonstrate:

// Make 50 monsters.
var totalMonsters:int = 50;
var i:int = 0;
for(i=0; i<totalMonsters; i++)
{
    // make a monster
}

So far so good. But there are a few other things we have to do with these monsters we create. We need to put each one on a hill. Then we need to dress each monster up in a Power Hat. Next, we need to hide a key to each monster’s hilly domain. Let’s modify the loop:

// Make 50 monsters.
var totalMonsters:int = 50;
var i:int = 0;
for(i=0; i<totalMonsters; i++)
{
    // make a monster
    // put the monster on a hill
    // put a power hat on the monster
    // hide a key
}

Mmmm … we’re almost there. Now we need to create a portrait for that each monster and put it inside the castle, so that when the hero defeats a monster, the portrait gets a big checkmark on it. Then we need to create a magic gem that will kill each monster. Each gem needs to be buried somewhere underground. Finally, we need to create a villager for each monster in the game. Each villager will give you a clue as to where to find the monster-killing gem.

// Make 50 monsters.
var totalMonsters:int = 50;
var i:int = 0;
for(i=0; i<totalMonsters; i++)
{
    // make a monster
    // put the monster on a hill
    // put a power hat on the monster
    // hide a key
    // create a portrait
    // put the monster's face on the portrait
    // put the portrait inside the castle
    // create a gem
    // bury the gem underground
    // create a villager
    // give the villager a gem clue
}

Oh man. This loop is getting real ugly, real fast. There’s so much STUFF in there. It’s getting out of control.

If we take a close look, we see that we’re running a few tasks that can be grouped together. All the monster stuff goes together. All the key stuff goes together. The gem stuff goes together. The villager stuff goes together. That’s four separate bundles of tasks that, like a pile of sticks, we should be able to wrap up with twine in a tidy little package.

I Have a Tiny Little Package

That’s one of the things Functions do for us: they allow us to group related tasks together into a little package, and we can refer to that package over and over again without having to repeat any lines.

A Function declaration looks very much like a variable or array declaration. Instead of the var keyword, we use the function keyword. In ECMA-based languages like Actionscript 3, Unity javascript and C#, functions are followed by round brackets. Then you open up a statement block between curly brackets, just like in a For Loop or a conditional (If) statement:

function doSomething()
{
   // statements go here
}

Note: If you’re using Unity javascript, best practice is to begin a function name with a capital letter.

So doSomething is our function name. That’s a custom name that we came up with. It makes a lot of sense to use verbs (action words) when naming your functions. We’ll see why in a moment.

Let’s carve out the statements involving the monsters and put them in their own function:

function initMonsters()
{
    // make a monster
    // put the monster on a hill
    // put a power hat on the monster
}

(the “init” here is short for “initialize”, which means “set it up”)

Now, back in the loop, we can substitute those three statements with a Function call. A Function call always uses the name of the function, followed by round brackets, with a semi-colon to end the statement. Take a look:

// Make 50 monsters.
var totalMonsters:int = 50;
var i:int = 0;
for(i=0; i<totalMonsters; i++)
{
    initMonsters(); // We removed these three statements and put them in their own function.
    // Now, we just call the function.
 
    // hide a key
    // create a portrait
    // put the monster's face on the portrait
    // put the portrait inside the castle
    // create a gem
    // bury the gem underground
    // create a villager
    // give the villager a gem clue
}

In common programming parlance, this is called calling a Function.

To understand how a function call works, we need to put ourselves back in the role of our code interpreter, which is a lot like Pac Man.

Pac Man and functions

Pac Man hits the first statement in the loop. It’s a function call. So he jumps out of the loop to wherever the Function is declared, and chews through all of the statements in that Function. When he reaches the bottom of the Function, he bounces back to the loop again, and resumes chewing through code at the very next line.

This works very nicely. Now we can go through and offload all of our chunks of functionality into their own Functions. When we write it all up, i looks something like this:

// Make 50 monsters.
var totalMonsters:int = 50;
var i:int = 0;
for(i=0; i<totalMonsters; i++)
{
    initMonsters();
    initKeys();
    initPortraits();
    initGems();
    initVillagers();
}

Look how much easier to read that loop is now. It’s very clear that we loop 50 times, and each time we make some monsters, some keys, some portraits, some gems, and some villagers. The details for each process are buried in their respective functions. Now, when we look at the initKeys function, we only have to worry about tasks related to initializing those keys.

This bouncing around that the Pac Man-like code interpreter does is the reason why i say that Object Oriented Programming (OOP) is like taking multiple plane flights through time portals.

Pac Man Map

Pac to the Future

There are two more very important things to learn about functions: Arguments and Return Values. These are detailed in two additional articles. Once you read through those, you’ll know almost everything there is to know about Functions, and you’ll be ready to start putting that knowledge into practice by building your own stuff!

For more Flash AS3 Tutorials and a pile of other useful stuff, check out our Flash and Actionscript 911 feature.

10 thoughts on “Understanding Functions

  1. Gag

    please oh please make some more understanding programming tutorial. I find it easier to understand than eating 500 page of actionscript 3 book. thank you :)

    Reply
  2. Gag

    Im a designer learning to code and Im pretty much new to OOP. I hope the [COMING SOON!] part on Flash and Actionscript 911 page will really come to town, thanks :)

    Reply
  3. Igor

    Hi, the site is awesome, lots of detailed info, but I think there is a mistake with the “for” loop examples. They all state the same thing:

    // Make 50 monsters.
    var totalMonsters:int = 50;
    var i:int = 0;
    for(i=0; i

    no change at all through the steps. Maybe you forgot to put the right ones?

    Reply
    1. Ryan Henson Creighton Post author

      Thanks for pointing this out, Igor. The site was broken a while back, so i disabled all of its plugins in order to rehabilitate it. i knocked out the plugin that made the code work in the process. i’ve reinstated it now. (Hopefully you’ve learned a lot more about code in the past couple of years, and you don’t need the post any more!)

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *