Lesson Objectives
At the end of this lesson, you will know…
- What functions, procedures, and methods are
- How functions can call other functions
What are functions, procedures, and methods?
These are just the names we use to call about a small piece of the program that does a particular task.
That task may be to perform a mathematical calculation on some numbers, or read some data from a file, or place an order on a website. They can perform huge tasks or small ones. However, if the task/function is large, we usually break it down into smaller tasks/functions. This makes them easier to read.
Personally, I try to keep my functions no longer than 15 – 20 lines of code – at the max. Sometimes, it makes sense to have larger ones. But it’s easier to figure out what a function is doing if you can see all of it on one screen, without constantly scrolling up and down.
Nowadays, most people use these names interchangeably. In the past, programmers would often use “function” for a piece of the program that did something and returned a value. Whereas a “method” did something, but didn’t return any value.
If you look at the World.cs class we created, it has eight methods – if you don’t count the constructor method.
Methods with no return values
The first four are the ones that start with “Populate”. Let’s take a look at the “PopulateItems” method.
private static void PopulateItems() { Items.Add(new Weapon(ITEM_ID_RUSTY_SWORD, "Rusty sword", "Rusty swords", 0, 5)); Items.Add(new Item(ITEM_ID_RAT_TAIL, "Rat tail", "Rat tails")); Items.Add(new Item(ITEM_ID_PIECE_OF_FUR, "Piece of fur", "Pieces of fur")); Items.Add(new Item(ITEM_ID_SNAKE_FANG, "Snake fang", "Snake fangs")); Items.Add(new Item(ITEM_ID_SNAKESKIN, "Snakeskin", "Snakeskins")); Items.Add(new Weapon(ITEM_ID_CLUB, "Club", "Clubs", 3, 10)); Items.Add(new HealingPotion(ITEM_ID_HEALING_POTION, "Healing potion", "Healing potions", 5)); Items.Add(new Item(ITEM_ID_SPIDER_FANG, "Spider fang", "Spider fangs")); Items.Add(new Item(ITEM_ID_SPIDER_SILK, "Spider silk", "Spider silks")); Items.Add(new Item(ITEM_ID_ADVENTURER_PASS, "Adventurer pass", "Adventurer passes")); }
First, we have the scope “private”.
“Private” means that this method can only be run by other code inside this class. If it was “public”, then it could be run from other classes. But we don’t need to allow that for this method, since it’s only ever run once, from this class’ constructor.
Next, we have “static”.
Normally, when you want to run a method, you do it on an object. For example, on a monster object, you might have a ReceiveDamage method that gets the amount of damage that was done to the monster, and subtracts that from its CurrentHitPoints. The method is doing something to, or with, the object.
If you want to run a method without instantiating an object from the class, then the method needs to be static. Since this method is in a static class, which can never be instantiated, we need to include static here.
Then, there is “void”.
“Void” means that this method is not going to return a value. It’s just going to do some work. In this case, the work is to populate the Items list with the items in our game world.
Finally, we have the method name “PopulateItems”.
Give your methods names that are easy to understand. Then, when you, or another programmer, want to make changes to the program in the future, it will be easier to figure out what the method is supposed to be doing.
It’s also common to name methods in a verb-noun format. What are you doing, and what are you doing it to?
Methods that return a value
Now, let’s take a look at a method that returns something, the “ItemByID” method.
public static Item ItemByID(int id) { foreach(Item item in Items) { if(item.ID == id) { return item; } } return null; }
This time, the scope of the method is “public”.
We’re going to need to “call” (a common way to say “run” or “execute” for a method) this method from other parts of the game. So, it needs to be public.
We still need “static”, since this class is never an object.
Now, instead of “void”, we have “Item”.
That’s because this method is going to return a value, and the datatype of that value is going to be “Item”. So, the user knows that when they call this method, they should get an Item back.
This method also accepts parameters. Just like we had in the constructors of our other classes. We’ll talk later about exactly what is happening inside the method. But, for now, you can probably guess that the method accepts an ID number and returns the item with the matching ID number.
Methods that call other methods
Looking at the code in the constructor of this class, we see that all it has in it is the name of the Populate methods in the class. That’s because all this method does is run those other methods.
static World() { PopulateItems(); PopulateMonsters(); PopulateQuests(); PopulateLocations(); }
When the constructor is called, it runs the PopulateItems method, then the PopulateMonsters, PopulateQuests, and PopulateLocations methods.
When you run your program, the computer is basically performing one line of the program at a time – at least, until you get into multi-threaded programming. So picture the computer working like this:
- It starts to run the World constructor
- It see the line “PopulateItems();” and goes to the PopulateItems method
- It goes through each line in the PopulateItems method, adding items to the list
- When it reaches the end of the PopulateItems method, it returns back to where it was last in the World constructor
- The next line is “PopulateMonsters();”, so the computer goes to the PopulateMonsters method and performs each line in there
- At the end of the PopulateMonsters method, it returns to the World method and performs the next line “PopulateQuests();”
- Etc.
So, a line of code in one method can call another method, which can contain a line of code that calls another method, which contains a line of code that calls another method, and so on…
In large programs, these method calls can get 20 layers deep, or deeper. That can make it difficult to find bugs, since you aren’t really sure what happened in each layer. So, remember to keep your programs simple. Don’t add another layer, just because you can.
Summary
Now you understand the basics of functions, procedures, and methods.
These are important, because you need to create them to start doing things in the program. We’ll have some that handle user input, some that do let the player move around, and some that handle our game’s battles. These will be the brains of our program.
Source code for this lesson
No source code for this lesson
Next lesson: Lesson 13.2 – Creating functions to handle user input
Previous lesson: Lesson 12.1 – Add the remaining UI controls
All lessons: Learn C# by Building a Simple RPG Index
I’m thoroughly enjoying your guide and your explanation style is excellent!
Little typo here: “When you run your program, the computer is basically performing *on* line of the program at a time”
I’m looking forward to finishing and expanding it.
Thanks! I got that typo fixed.
Hi!
Been reading through all of your lessons up until this one, even though I’m already experienced in OOP and I have basic knowledge of C#, mainly ASP.NET MVC5 I am learning a lot of both new things and refreshing my memory of old things forgotten. A friend of mine and I are making an RPG together on the side of Uni studies and this is really helping me get a grasp of all the things that have slipped. Thanks, lessons and tutorials like this one are rare and far inbetween.
Truly enjoyable to read and follow.
You’re welcome. I’m glad it helps. 🙂
so cool lessons thank you!!!!!!!!!!!
You’re welcome!
The question I ended up with after this lesson is about “Static”.
I understand the Class will never be used to “create” an object if it is Static.
But in this lesson I took it that Static, on functions/methods, means no object is used with the function after reading:
‘Normally, when you want to run a method, you do it on an object.’ … ‘The method is doing something to, or with, the object.’
(I just accepted that, for now, even though PopulateItems() is working with objects.)
But then you said ‘We still need “static”, since this class is never an object.’
So… if the Class is static all methods/function, and looks like variables too, will be static? (Yes?)
But what if the Class is not static; Can/would you have static functions still? (Yes?)
You are correct.
If a class is not static, its functions and class-level variables can be either static or non-static.
If a class is static, its functions and class-level variables must also be static. You can use non-static variables inside your static functions, like “total” and “average” in this function:
public static class Calculator
{
public static double ComputeAverage(double firstNumber, double secondNumber)
{
double total = firstNumber + secondNumber;
double average = total / 2;
return average;
}
}
One example of using a static method, in a non-static class, could be if you want to use the “Singleton” design pattern – a coding technique where you make sure your program will only ever have one instance/object of a particular class.
Here is a small sample of how you would use the Singleton design pattern to make sure your whole program uses a single (shared) Logger object: https://gist.github.com/ScottLilly/fa590a163ae22ab141f3
I think this page is linked to the wrong next step. Then, 13.2, which I found back at the table of contents, the link at the bottom of that page goes to 14.1, though the ending text says that the next step is writing the functions. I think I may have missed something but I thought I would check.
Thank you so much for this guide! I’ve thoroughly enjoyed C# more than any programming language I have tried to learn.
Oops! I found it later, there were just some lessons in between. Sorry about that!
No problem. I’m glad you are enjoying the lessons. 🙂
As i understand that this is not really necessary to add the method “static World()” because anyway the program will trigger all the methods inside of it. Am i right ?
Like we added that only that people who read that could say what methods are we using in the program.
We need to have the “static World()” function, for this program.
The way this works is:
1. Part of the program uses a function or property in World.cs.
2. The program knows that World.cs is static, and this is the first time it is using anything in the World class – so it looks for the “static World()” function.
3. Because the “static World()” function exists, the function is run before using the function or property the program originally tried to use.
4. Running the “static World()” function populates the static variables for the locations, monsters, etc.
5. When the “static World()” function is done running, the program tries to use the original function or property – which needed the static variables to be populated.
If we removed the “static World()” function, we would need to have another way to populate the static variables before they were used by the rest of the program.
Great course.
Thank you for your share.
You’re welcome!
Scott I’m honestly so impressed by this tutorial. I’ve been learning C# and applying it in Unity to try to make simple games. I have been educating myself by looking up guides here and there and following along with various tutorials and I must say I haven’t found anyone that explains things quite as well as you. I can only assume that you’re occupationally a teacher of some sort. You certainly have a gift for it!
I’ve read that you have a more advanced version of a very similar course to this. So far, I’m following along quite clearly and I’m looking forward to finishing with this course and moving on to your next course!
Is there other ways that I can follow along with your teachings? Do you have many other lessons available?
Thanks Callan!
By profession, I’m a custom software developer for large companies (energy, insurance, pharmaceutical, etc.).
The only other guides I have (besides the WPF version of this game) are a series on C# design patterns. These teach common techniques used to write code for common situations. I might create other courses. Right now I’m trying to figure out what direction to take my business, and that’s one possible alternative.