Learn How To Use Methods So You Don’t Have To Squeeze All Your Code Into One Place
Imagine there’s a new restaurant in town that offers unlimited choices. They claim it’s the ultimate choose your own meal. It just opened last week down the road next to the supermarket.
They promise to fix anything you want and if they don’t have the ingredients, then they’ll get what you want from the supermarket and cook it just like you want.
This sounds amazing, so you decide to try it out.
When you get to your table, your server explains how the ordering works. There’s no menu. After all, how could the restaurant offer unlimited choices with a menu? They’d need an infinite number of pages in the menu to list everything.
You begin thinking that maybe this really is new. I mean, who ever heard of not having a menu because they wouldn’t be able to fit everything?
You’re not very hungry and having trouble thinking what you want so you just ask for the first thing that comes to mind. A salad and cup of hot tea should be good.
“Uh, there’s just one problem,” the server says. “You can’t order things by name like that.”
Now you understand how the restaurant works. There’s no names even for common items except for raw ingredients. There’s no ordering a slice of cheese pizza. No ordering a bowl of potato soup. Not even a cup of tea with a salad. You have to provide detailed instructions instead.
You change your order to “Shred some lettuce, put it in a bowl along with some croutons, then thinly slice some parmesan cheese and add it to the bowl, then mix everything together with some caesar salad dressing.”
And for your drink, you tell the server to heat some water to almost boiling and pour it into a cup meant for hot liquids and put a tea bag on the side.
Your food and drink arrive perfect. But the restaurant closed down after being open for just a month. It seems that the ordering system was not very friendly. And while you were able to write clear instructions, most people struggled to remember all the steps needed to make even a chicken sandwich.
Programming is all about writing instructions. If you had to always write those instructions for everything, though, then it’d be just as bad as the unlimited choice restaurant. We like to name things at a higher level than just raw ingredients.
Methods let you wrap up a set of instructions into a bundle that you can call by name whenever you want those instructions to run. Just like how you would ask for a chicken sandwich by name.
There’s a lot to learn about methods so this class is divided into three parts. We’ll start out with some simple methods and take it from the beginning.
First, there are methods that just do something. You call them by name and they run their code.
- You’ll learn more about the structure of a method.
- return value
- method name
- Your method can have no parameters if they’re not needed.
- Have a type and name.
- The name can be left out if the parameter is not needed by the method.
- Parameters will be explained more in part two.
A lot of variables will be used by methods and live in a memory area called the stack. This is different from global variables that exist in memory set aside for your application when it begins.
- You’ll see the difference between these so you’ll know when to use each type.
An earlier class explained methods as types. This class builds on that by giving you more in-depth and practical knowledge.
- You’ll learn when you should create methods.
- To reuse code so it can be run again.
- To name code so it has more meaning.
- And when should you use parameters?
- To change what data a method works with.
- To slightly change the behavior of a method.
- Parameters will be explained in the second class.
You’ll develop a better sense of scope which will help you understand when things are available to you to use..
- A method body starts a new scope that ends when the method body ends.
Then there are methods that return a value.
- You can ignore the return value when calling a method.
- All code paths must return a type compatible with the method return type.
- Don’t return a reference to a local variable.
- The return value optimization is your friend.
- A method can only return one type. But that type can be a struct which can contain many members.
- You can also return classes which will be explained later.
- Another choice is to pass references to what you want the method to change as arguments. These can behave like return values.
The second class begins here and will show you how to work with method parameters so you can let your methods accept information to work with and change their behavior.
- You declare a type and name for each parameter. Then when calling the method, you provide argument values to match each method parameter.
- You can also call other methods and use their return values to pass as method arguments.
- There is no defined order for the compiler to use when resolving method arguments. You’ll learn how to avoid this common mistake.
Default argument values are provided at the place where a method is called. The method itself always gets all its parameters and doesn’t know which were explicitly set and which were set by default.
- All default parameters must come at the end of the other parameters.
Using references in method parameters will let you pass large objects to a method quickly and to be able to modify variables outside of the method.
- Declare your references const if the method doesn’t need to change them.
- Prefer to use references for anything larger than basic types.
Modifying global variables from within a method.
- Avoid using global variables. If a method needs to change something, then it’s better to pass a reference to the thing that needs to be changed as an argument when calling the method.
- If you need a variable to exist and maintain its value between method calls, then you can use a static local variable.
The third class starts here and will show you how to declare multiple methods with the same name but different parameters. This can simplify your design.
How, you might wonder, does having multiple methods with the same name make things simpler? After all, if you call out the name of your friend in a crowded room and three people stop to look at you, is this simpler? Or if you order a “sandwich” from a menu that lists several items all called “sandwich”, isn’t that just asking for confusion?
In these cases, yes. Having many different things with the same name is more confusing than not. But you’ll learn in this class how that thinking is backwards for programming and how going against our natural tendencies is actually better.
Then, you’ll get more experience declaring a method before it’s implemented.
- This lets you call the method even if the compiler has not yet seen the implementation.
- An implementation by itself is also a declaration.
- The declaration can be in an include file and the implementation can be in a separate cpp file.
- You don’t have to call or make use of every method that was declared. But if you do call a method, then the program will need to include the implementation for that method.
- You can’t call a method that hasn’t been declared or implemented.
There can normally be only a single method implementation for each method in a program. The inline keyword can get around this restriction. But be careful.