<< Back

Methods

Our code has gotten pretty long now! It's time we reorganize it a bit! You've now used some methods and had them described to you, but to really understand them you need to write your own, and conveniently they're the prefect tool to clean up the code we have so far. Just as a refresher, a method is some code saved somewhere else that you can 'call' or 'execute' when needed.

First, lets clean up the code that says which ways you can go. At the end of the file, we're going to add some new code:

This is the start of your method definition. The void means that you don't want the method to return a value, and just want it to go do something. Many people argue that methods should only act on the data passed into then and return a result based on them, because it is easier to tell what is going on in a program that way. Those people are not wrong, but especially right now that isn't so important. After the void is the method name, followed by the argument list (or parameter list), surrounded by parentheses. Currently, we have no arguments, but we're going to need some: our four 'can go' variables.

The parameters are seperated by commas, and specify a type and a name. The name is what will be used to refer to those variables within the method, regardless of their names outside the method. The types, though, are important. Previously, whenever we've defined a variable, we have used var. This keyword says that you want the variable type to be determined by what you're putting into it. Usually, this is exactly what you want, but methods cannot (and should not!) do this. The types of the method parameters make sure only values that are the right type can be passed in. We want booleans, which are values that can only be true or false, so we use the bool keyword.

Now we're going to grab everything from line 53 to 88 and move it into the method.

Now, back where we removed the code from, we need to call it!

If you run the program now it should behave exactly the same as it did before. The main goal of this was to show you that you can put some of your code somewhere else, and give that code a name, so that you can read that name and know what it does without having to read all of that code.

Next lesson, we'll discuss defining classes, which allow you to structure an object freely and combine some data and methods together, outside of the main logic of your program. We'll even do it in another file!