Difference between revisions of "Overview"

From CompSciWiki
Jump to: navigation, search
(Inserted codeblock templates all previous changes were cleaning up piplines)
m (typo)
 
(4 intermediate revisions by 3 users not shown)
Line 3: Line 3:
 
|Body=
 
|Body=
 
|Chapter_TOC=[[User-Defined_Methods|User-Defined Methods]]
 
|Chapter_TOC=[[User-Defined_Methods|User-Defined Methods]]
|Introduction=Up until now, all of the code you have written has been placed in the ''main'' method. As programs get larger, code written entirely in the ''main'' method becomes unmaintainable and unreadable. This chapter will explain how to define separate code sections which perform specific tasks. These code sections may then be used any number of times. These separate code sections are called '''user-defined methods'''.
 
|Overview=User-defined methods allow you to reuse code more easily and keep your programs readable.
 
}}
 
  
 +
==Introduction==
 +
All of the code you have written up until now has been placed in the ''main'' method. As your programs get larger, code written entirely in the ''main'' method becomes difficult to maintain and understand. This chapter will explain how to define separate code sections called '''user-defined methods''', which perform specific tasks. These code sections may then be used repeatedly, any number of times.
  
  
 
=What is a User-Defined Method?=
 
=What is a User-Defined Method?=
  
A '''user-defined method''' is a section of code which is declared once in a program, then used by other code sections. Instead of writing an entire program in the main method, you can separate program functionality into separate user-defined methods. Doing so has two main benefits:
+
A '''user-defined method''' is a section of code which is declared and written somewhere in your class, then called from anywhere else in your program. Instead of writing an entire program in the main method, you can separate program functionality into separate logically separated user-defined methods. Doing so has two main benefits:
  
# ''Readability'' - When a complex code segment is placed in a user-defined method and called by the main method, a programmer who reads the main method will only need to understand ''what'' the user-defined method does, and not ''how'' it is implemented.
+
# '''Readability''' - User-defined methods will allow a programmer reading code to understand, at a glance, the main purpose of the program. The programmer will quickly be able to comprehend ''what'' the user-defined method does, without needing to worry about ''how'' it is implemented.
# ''Re-usability'' - When a program consists of only a main method, the only way to reuse sections of code is to copy and paste code sections. On the other hand, if a program separates its logic into a number of user-defined methods, the programmer can call these methods from other programs.
+
# '''Re-usability''' - When a program consists of only a main method, code can only be reused by copying and pasting sections. On the other hand, if a program is logically split up into a number of user-defined methods, the programmer can call these methods from other programs, or easily fit them into pre-existing code.
  
 
A method does three things:
 
A method does three things:
  
 
# Accepts input values, called '''parameters'''.
 
# Accepts input values, called '''parameters'''.
# Performs a task which may use the parameters.
+
# Performs a single task, which may use the parameters.
 
# Gives a '''return value''', or output value, to the code which called the method.
 
# Gives a '''return value''', or output value, to the code which called the method.
  
The following is an example of a user-defined method. Don't worry if you don't understand this - we will explain methods in more detail throughout the chapter.
+
 
 +
The following is an example of a user-defined method:
  
 
{{CodeBlock
 
{{CodeBlock
Line 34: Line 34:
 
}}
 
}}
  
The above is the '''definition''' of a method called ''getAverage''. The method does three things:
+
Above is a method called ''getAverage''. The method does three things:
  
 
# Accepts three '''parameters''' (firstNum, secondNum, thirdNum)
 
# Accepts three '''parameters''' (firstNum, secondNum, thirdNum)
 
# Calculates the average of these three numbers
 
# Calculates the average of these three numbers
 
# '''Returns''' the average as the method result.
 
# '''Returns''' the average as the method result.
 +
  
 
=An Analogy=
 
=An Analogy=
Billy is setting up his apartment for a party on Friday. He goes through his checklist of things to do:
+
Steve is setting up his apartment for a party on Friday. He goes through his checklist of things to do:
  
 
*Move the furniture
 
*Move the furniture
Line 49: Line 50:
 
*Clean the bathroom
 
*Clean the bathroom
  
So he moves his furniture so that there's plenty of room in his small apartment. He hooks up his stereo with giant subwoofers so that the neighbors will complain about the racket at 2:00 in the morning.
+
Steve begins by moving his furniture so that there will be plenty of room for his guests in his small apartment. He hooks up his stereo with giant subwoofers to ensure that the neighbours will complain about the racket at 2:00 in the morning.
  
Next, he needs to pick up some chips. But he doesn't feel like going out shopping, and besides, he doesn't even know the best brand to get.
+
Next, Steve needs to pick up some chips, but he doesn't feel like going out shopping. He isn't even sure which would be the best brand to purchase.
  
"I should get my brother Jimmy to go pick up the chips," Billy decides.
+
"I should get my brother Greg to go pick up the chips," Steve decides.
  
"Jimmy!" Billy shouts. "Could you get the chips for tonight? Preferably two bags of spicy tortillas?"
+
So Steve called his brother. "Greg! Could you get the chips for tonight? Preferably two bags of spicy tortillas?."
  
Jimmy, being the great brother that he is, heads out to the nearest convenience store and picks up a few bags of jalapeno-cheddar tortillas. He heads home and hands the bags over to Billy. "I tried some of these chips last week," Jimmy says. "They're really awesome."
+
Greg, being the great brother he is, heads out to the nearest convenience store and picks up two bags of jalapeno-cheddar tortillas. Meanwhile, Steve has been working all day, and believes he has earned a break until Greg gets back.
  
Billy now continues to prepare for the party. He phones the cable company and orders the pay-per-view fight, then heads off to clean the bathroom.
+
Upon returning home, Greg gives the chips to Steve. "I tried some of these chips last week," Greg says. "They're really great". Steve dumps the chips into bowls and places them on the table.
 +
 
 +
Steve now continues to prepare for the party. He phones the cable company and orders the pay-per-view fight, and then heads off to clean the bathroom.
  
 
==How the Story Relates to User-Defined Methods==
 
==How the Story Relates to User-Defined Methods==
Billy's list of things to do are similar to computer instructions. His plan is to go through each step in the order he determined earlier, which is similar to how a Java program runs. First he moved the furniture, then he set up the stereo.
+
Steve's list of things to do are similar to computer instructions. His plan is to go through each step in the order he determined earlier, which is similar to how a Java program runs. First he moved the furniture, and then he set up the stereo.
  
But when it came time to buy the chips, he didn't want to complete the step himself. Instead, got his brother to do it. In Java, having some other part of a program complete a series of instructions for you is known as '''calling a method'''. This chapter will explain how to write your own user-defined methods and how to call them.
+
But when it came time to buy the chips, he didn't want to complete the step himself. Instead, he got his brother to do it. In Java, having some other part of a program complete a series of instructions for you is known as '''calling a method'''. This chapter will explain how to write your own user-defined methods and how to call them.
  
 
==Method Terms Related to Analogy==
 
==Method Terms Related to Analogy==
 
*'''Defining the method'''
 
*'''Defining the method'''
**Jimmy is capable of doing many things, one of which is "Buying chips."
+
**Greg is capable of doing many things, one of which is "Buying chips."
 
**In Java, you may define a number of methods within any class you write.
 
**In Java, you may define a number of methods within any class you write.
  
 
*'''Accepting parameters'''
 
*'''Accepting parameters'''
**Jimmy needed to know what kind of chips to buy and how many bags to buy. Whenever somebody asks him to buy chips, that person will have to give Jimmy those two pieces of information.
+
**Greg needed to know what kind of chips to buy, and how many bags he should purchase. Whenever somebody asks Greg to buy chips, that person will have to give him those two pieces of information.
 
**In Java, a method definition states the parameters which the method requires to execute.
 
**In Java, a method definition states the parameters which the method requires to execute.
  
 
*'''Passing arguments''' to a method
 
*'''Passing arguments''' to a method
**Billy tells Jimmy that he needs three bags of spicy tortillas. "Three bags" and "spicy tortillas" are the arguments.
+
**Steve tells Greg that he needs two bags of spicy tortillas. "Two bags" and "spicy tortillas" are the arguments.
 
**In Java, when a user-defined method is called, the caller method must pass a value for each parameter to the called method. Each passed value is known as an argument.
 
**In Java, when a user-defined method is called, the caller method must pass a value for each parameter to the called method. Each passed value is known as an argument.
  
 
*'''Calling a method'''
 
*'''Calling a method'''
**Once Billy is finished setting up the stereo, he asks Jimmy to buy chips and specifies the amount and type of chips.
+
**Once Steve is finished setting up the stereo, he asks Greg to buy chips, and specifies both the amount and type of chips.
 
**In Java, a method may be called at any point in your code. The method call consists of the name of the class where the method is defined, the method name, and a list of arguments. Your program waits for the method to complete execution, then the program continues on.
 
**In Java, a method may be called at any point in your code. The method call consists of the name of the class where the method is defined, the method name, and a list of arguments. Your program waits for the method to complete execution, then the program continues on.
 
**'''NOTE''': If the called method is defined in the same class as the calling method, you do not need to specify the class name in the method call.
 
**'''NOTE''': If the called method is defined in the same class as the calling method, you do not need to specify the class name in the method call.
  
 
*'''Performing some actions'''
 
*'''Performing some actions'''
**Jimmy gets into his car, drives to the convenience store, picks up the chips, pays for the chips, and drives back home.
+
**Greg gets into his car, drives to the convenience store, buys the chips, and then drives back home.
**In Java, the body of a user-defined method definition contains code which executes once the method is called.
+
**In Java, the body of a user-defined method definition contains code which executes in order once the method is called.
  
 
*'''Returning a result'''
 
*'''Returning a result'''
**Jimmy comes home with three bags of jalapeno-cheddar tortillas and hands them to Billy.
+
**Greg comes home with two bags of chips and hands them to Steve who has been taking a break since Greg left. Once Steve gets the chips from Greg, he stores them in bowls on the table.
**In Java, once a called method is finished execution, it may return a value to the caller. The caller usually assigns this value to a variable that is used later. The caller continues execution of its own code once the method call is complete.
+
**In Java, once a called method is finished execution, it may return a value to the caller. The caller usually assigns this value to a variable that is used later, and then continues execution of its own code once the method call is complete.
  
=An Example - The Main Method=
+
 
 +
=The Main Method=
 
Up until now, you have placed all code inside the ''main'' method like so:
 
Up until now, you have placed all code inside the ''main'' method like so:
  
Line 104: Line 108:
  
 
The ''main'' method is a special type of user-defined method. When you tell Java to run your program, Java will look for a method called ''main'' within your class and run the method if found. As proof, try running a program without a ''main'' method and note the result.
 
The ''main'' method is a special type of user-defined method. When you tell Java to run your program, Java will look for a method called ''main'' within your class and run the method if found. As proof, try running a program without a ''main'' method and note the result.
 +
}}

Latest revision as of 02:32, 8 December 2011

COMP 1010 Home > User-Defined Methods

Introduction

All of the code you have written up until now has been placed in the main method. As your programs get larger, code written entirely in the main method becomes difficult to maintain and understand. This chapter will explain how to define separate code sections called user-defined methods, which perform specific tasks. These code sections may then be used repeatedly, any number of times.


What is a User-Defined Method?

A user-defined method is a section of code which is declared and written somewhere in your class, then called from anywhere else in your program. Instead of writing an entire program in the main method, you can separate program functionality into separate logically separated user-defined methods. Doing so has two main benefits:

  1. Readability - User-defined methods will allow a programmer reading code to understand, at a glance, the main purpose of the program. The programmer will quickly be able to comprehend what the user-defined method does, without needing to worry about how it is implemented.
  2. Re-usability - When a program consists of only a main method, code can only be reused by copying and pasting sections. On the other hand, if a program is logically split up into a number of user-defined methods, the programmer can call these methods from other programs, or easily fit them into pre-existing code.

A method does three things:

  1. Accepts input values, called parameters.
  2. Performs a single task, which may use the parameters.
  3. Gives a return value, or output value, to the code which called the method.


The following is an example of a user-defined method:

 public static int getAverage(int firstNum, int secondNum, int thirdNum)
    {
        int average;
        average = (firstNum + secondNum + thirdNum) / 3;
        return average;
    } 

Above is a method called getAverage. The method does three things:

  1. Accepts three parameters (firstNum, secondNum, thirdNum)
  2. Calculates the average of these three numbers
  3. Returns the average as the method result.


An Analogy

Steve is setting up his apartment for a party on Friday. He goes through his checklist of things to do:

  • Move the furniture
  • Set up the stereo
  • Buy some chips
  • Pay for the pay-per-view fight
  • Clean the bathroom

Steve begins by moving his furniture so that there will be plenty of room for his guests in his small apartment. He hooks up his stereo with giant subwoofers to ensure that the neighbours will complain about the racket at 2:00 in the morning.

Next, Steve needs to pick up some chips, but he doesn't feel like going out shopping. He isn't even sure which would be the best brand to purchase.

"I should get my brother Greg to go pick up the chips," Steve decides.

So Steve called his brother. "Greg! Could you get the chips for tonight? Preferably two bags of spicy tortillas?."

Greg, being the great brother he is, heads out to the nearest convenience store and picks up two bags of jalapeno-cheddar tortillas. Meanwhile, Steve has been working all day, and believes he has earned a break until Greg gets back.

Upon returning home, Greg gives the chips to Steve. "I tried some of these chips last week," Greg says. "They're really great". Steve dumps the chips into bowls and places them on the table.

Steve now continues to prepare for the party. He phones the cable company and orders the pay-per-view fight, and then heads off to clean the bathroom.

How the Story Relates to User-Defined Methods

Steve's list of things to do are similar to computer instructions. His plan is to go through each step in the order he determined earlier, which is similar to how a Java program runs. First he moved the furniture, and then he set up the stereo.

But when it came time to buy the chips, he didn't want to complete the step himself. Instead, he got his brother to do it. In Java, having some other part of a program complete a series of instructions for you is known as calling a method. This chapter will explain how to write your own user-defined methods and how to call them.

Method Terms Related to Analogy

  • Defining the method
    • Greg is capable of doing many things, one of which is "Buying chips."
    • In Java, you may define a number of methods within any class you write.
  • Accepting parameters
    • Greg needed to know what kind of chips to buy, and how many bags he should purchase. Whenever somebody asks Greg to buy chips, that person will have to give him those two pieces of information.
    • In Java, a method definition states the parameters which the method requires to execute.
  • Passing arguments to a method
    • Steve tells Greg that he needs two bags of spicy tortillas. "Two bags" and "spicy tortillas" are the arguments.
    • In Java, when a user-defined method is called, the caller method must pass a value for each parameter to the called method. Each passed value is known as an argument.
  • Calling a method
    • Once Steve is finished setting up the stereo, he asks Greg to buy chips, and specifies both the amount and type of chips.
    • In Java, a method may be called at any point in your code. The method call consists of the name of the class where the method is defined, the method name, and a list of arguments. Your program waits for the method to complete execution, then the program continues on.
    • NOTE: If the called method is defined in the same class as the calling method, you do not need to specify the class name in the method call.
  • Performing some actions
    • Greg gets into his car, drives to the convenience store, buys the chips, and then drives back home.
    • In Java, the body of a user-defined method definition contains code which executes in order once the method is called.
  • Returning a result
    • Greg comes home with two bags of chips and hands them to Steve who has been taking a break since Greg left. Once Steve gets the chips from Greg, he stores them in bowls on the table.
    • In Java, once a called method is finished execution, it may return a value to the caller. The caller usually assigns this value to a variable that is used later, and then continues execution of its own code once the method call is complete.


The Main Method

Up until now, you have placed all code inside the main method like so:

 public static void main(String[] args)
    {
        // Code is written here
    } 

The main method is a special type of user-defined method. When you tell Java to run your program, Java will look for a method called main within your class and run the method if found. As proof, try running a program without a main method and note the result.