Programming: Functions

    Programming: Functions

      It's 5:00AM and you have to be at the airport twenty minutes ago. (Aren't hypotheticals fun?) Being the forward thinker that you are, you of course stayed up three hours past your bedtime playing Laundry Wars: The Battle for Soap. But that isn't the point. The point is that it's early and you're tired and late. And, just for fun, it's pouring rain outside, so you'll soon be cold and wet too.

      In order to get to the airport on time, you need to focus on the important things. You don't want to think about every single thing that needs to be done to turn coffee beans into a cup of coffee; you just want that perk to wake you up and get you to your flight. Luckily, you have a coffee maker to walk through all the steps you want to ignore. Give it the right inputs (water, ground beans, a dash of baking soda), and you can let it do the work of making your coffee.

      Just like your coffee maker, a function abstracts the steps of a routine (or algorithm) so that you don't need to worry about each step every time. As long as you give it the right inputs, it'll give you exactly what you need.

      Not only does using a function save you time, it also makes your code more durable and less prone to bugs. Because you don't need to think about every step in making coffee, you're less likely to forget one. Since it's all automated, you don't need to worry about getting all the steps right except for the first time you write it. On top of that, if you ever need to change the steps, all you need to do is go into that single function and rewrite the steps. As long as you don't need to change what goes in or what comes out, all the times you call the function can stay the same.

      Example

      Let's talk about something really simple: exchanging the values of two variables. Our variables are:

      integer a
      integer b

      Both integers. If we write a function for them:

      FUNCTION switch_vars(integer a, integer b):	
              add_vars = a + b
      	b = add_vars – b
      	a = add_vars – a
      	RETURN a, b

      If we want to write this out to test it, just to make sure, we can set the vals:

      a = 7
      b = 8
       
      add_vars = a + b = 15
      b = add_vars – b = 15 – 8
      	         = 7
      a = add_vars – a = 15 – 7
      	         = 8
      a = 8
      b = 7

      All right, our algorithm works. If we tried to write that out every time, we'd probably get it wrong, too, meaning that it's perfect for a function. Now all we need to do is call it anywhere in our code, and we'll switch the variables.

      It makes life easy.