Monday, May 21, 2012

Functions: Running when you call the name


Let's talk about Functions (AKA: methods, paragraphs, functions, subroutines, defs, etc, etc, etc). I've been tutoring for about four years, and during those four years I've been in and out of a lot of different languages (COBOL, JCL, DYL280, Javascript, PHP, Perl, Java, C, C++, and even Android's version of Java) and I think almost every language has a different name for this. We're talking about create a block of code that runs when you call it's name....kinda like a dog, if you think about it.

Remember way back in grade school when your teacher was trying to teach you about adding, subtracting, and multiplying numbers? (Dividing came much later) She would have a box at the front of the room, grab some poor kid and give him a little chalk board (or white board if you're younger than me) and whisper in his ear that he should add one two whatever she gives him. She has the class write down numbers on paper and then hands them into the kid, and he shows the number he was handed plus one (if he's smart). After ten or fifteen minutes the gifted students figure out the kid is adding one to every number and the in class activity is done. Recess break, yay!

A function in programming is like that. We have a block of code that we put something into, it does a bunch of stuff, and kicks something back out. Except now we're not working with snotty little kids and chalk boards, we're working with computers: the universal machine. We aren't limited to just numbers, we can build functions to take anything. Anything you could imagine.

Let's say you're writing some javascript to print off some student ID numbers with their names and grades. You start in

Great. You got one student to print correctly. Congratulations! Now let's type the same code for the other 3,600 students on your campus. See you in five years. Don't go insane typing the same block of code over and over and over again.

This is where functions come in. We want to generalize this idea so that instead of operating specifically for "ComputeryGuy" and those grades, we can use this same code for different students over and over and over again.


At first, this may look like more work. It may look like you're making more effort to get the same result. But what if we wanted to print off a second student? All we have to do is call the writeStudent function again and send it different information. Makes your life easier!

No comments:

Post a Comment