Methods 3. 1. Review. 2. Class-wide vs. local variables. 3. Why C# bans global variables. 4. Nested blocks. 5. Scope of identifiers.

Slides:



Advertisements
Similar presentations
Chapter 8 Scope, Lifetime and More on Functions. Definitions Scope –The region of program code where it is legal to reference (use) an identifier Three.
Advertisements

Chapter 7: User-Defined Functions II
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
Computer Science 1620 Function Scope & Global Variables.
1 Functions and Structured Programming. 2 Structured Programming Structured programming is a problem-solving strategy and a programming methodology. –The.
1 Run time vs. Compile time The compiler must generate code to handle issues that arise at run time Representation of various data types Procedure linkage.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Methods
Cs164 Prof. Bodik, Fall Symbol Tables and Static Checks Lecture 14.
Computer Science 1620 Lifetime & Scope. Variable Lifetime a variable's lifetime is finite Variable creation: memory is allocated to the variable occurs.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
Chapter 6: Functions.
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Call-by-Value vs. Call-by-Reference Call-by-value parameters are used for passing information from the calling function to the called function (input parameters).
Functions g g Data Flow g Scope local global part 4 part 4.
Beginning C++ Through Game Programming, Second Edition by Michael Dawson.
1 Names, Scopes and Bindings Aaron Bloomfield CS 415 Fall
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
CPS120: Introduction to Computer Science Decision Making in Programs.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
User Defined Functions Chapter 7 2 Chapter Topics Void Functions Without Parameters Void Functions With Parameters Reference Parameters Value and Reference.
Built-In and user-Defined functions Software Design Concepts Lecture IV Dr. Sothy Vignarajah.
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
C++ Programming Lecture 11 Functions – Part III By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Copyright © Curt Hill The Compound Statement C-Family Languages and Scope.
1 MORE ON MODULAR DESIGN: MODULE COMMUNICATIONS. 2 WHEN A FUNCTION IS INVOKED, MEMORY IS ALLOCATED LOCALLY FOR THE FORMAL PARAMETERS AND THE VALUE OF.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
CPS120: Introduction to Computer Science Lecture 16 Data Structures, OOP & Advanced Strings.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Slide 1 Chapter 6 Structures and Classes. Slide 2 Learning Objectives  Structures  Structure types  Structures as function arguments  Initializing.
1 Scope Lifetime Functions (the Sequel) Chapter 8.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
COP 2220 Computer Science I Topics –Breaking Problems Down –Functions –User-defined Functions –Calling Functions –Variable Scope Lecture 4.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
CHAPTER 8 Scope, Lifetime, and More on Functions.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
CSCE Introduction to Program Design and Concepts J. Michael Moore Spring 2015 Set 6: Miscellaneous 1 Based on slides created by Bjarne Stroustrup.
1 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
Advanced Programming in C
Eine By: Avinash Reddy 09/29/2016.
Structures and Classes
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Functions II
CS 326 Programming Languages, Concepts and Implementation
Objectives In this chapter, you will:
The Lifetime of a Variable
AKA the birth, life, and death of variables.
7. Inheritance and Polymorphism
Suppose we want to print out the word MISSISSIPPI in big letters.
Functions and Structured Programming
CSC113: Computer Programming (Theory = 03, Lab = 01)
User Defined Functions
Lecture 15 (Notes by P. N. Hilfinger and R. Bodik)
6 Chapter Functions.
Group Status Project Status.
AKA the birth, life, and death of variables.
CPS120: Introduction to Computer Science
The Three Attributes of an Identifier
Corresponds with Chapter 5
Scope Rules.
Presentation transcript:

Methods Review. 2. Class-wide vs. local variables. 3. Why C# bans global variables. 4. Nested blocks. 5. Scope of identifiers.

1. Review. §Recall that creating a function requires both (a) designing the interface = the visible, communication mechanism and §(b) designing the implementation = the “invisible” code hidden inside the function. §A.The interface = the WHAT; includes function name (the task) and the parameters (communication). It specifies what is to be done and what gets sent back and forth.

Review. §Communication requires matching the actual parameters (in the function call) with the formal parameters (in the function heading). §How are parameters matched? §NOT by name—the name can be the same or different. §By: 1) data type; § 2) number; § 3) position.

Review (cont.). §B. The implementation = the HOW; behind the scenes, what machinery (code) actually carries out the task. This includes all the code inside the function’s scope brackets { }. §The implementation may include “local variables”….

2. Class-wide vs. local variables. §Definition. §A local variable is defined inside a block of code, i.e. within scope brackets { }, and is only accessible there. §Memory for local variables is allocated in a region called the stack on a demand basis: it does not exist before the block is entered or after the block is exited.

What are the local variables? Local to what? §class Bundle { §static double Find_Big (double X, double Y) { § double Big; § Big = X; § if (Y > X) § Big = Y; § return Big; § } // end Find_Big §static void Main (string[] arg) § { double Num1, Num2, Answer; § Answer = Find_Big (Num1, Num2); § } // end Main() §} // end Bundle

“Local” is a relative term. §Local to Find_Big: § 1) the formal parameters X and Y. § 2) Big §Local to Main(): § Num1, Num2, Answer §Find_Big CANNOT access Num1, Num2, Answer. Why? §Main() CANNOT access X, Y or Big. Why?

Why local variables? §We typically have variables local to Main(), but we may also put local variables inside our own Methods (or in other blocks of code). §WHY? What are they for?

Uses of local variables. §Local variables are a good solution for indexes and intermediary values that are only needed within a method (or other block). §They are not a good solution if the data values are required after the method / block is exited, because?

Class-wide variables. §If data needs to survive after a method call, or it makes sense for several methods to share data, C# allows class-wide variables. §These are data members. All methods in the class can access these variables directly without passing them as parameters. §They are “common knowledge,” to everyone in the class.

Class-wide variables. §class Bundle { § double Big; // Big is a class-wide variable. §static void Find_Big (double X, double Y) { § Big = X; § if (Y > X) § Big = Y; §} // end Find_Big §static void Main (string[] arg) §{ double Num1, Num2; § Find_Big (Num1, Num2); § Console.Write (“The answer is ” + Big); // legal! §} // end Main() §} // end Bundle

Note the differences: §Both Find_Big and Main() can access the class- wide variable Big directly, without passing it as a parameter. §Does that mean anyone can access Big? §No. Only class members can see Big. §Can a local variable have the same name as a class-wide variable? §Yes, but it is not a good idea. More later.

3. Why C# bans global variables. §Some languages allow global variables, e.g. C and C++. §Global variables are defined outside of any class at “file scope.” §They can therefore be accessed by methods in any class. §Using global variables, on can avoid parameter passing altogether. §Here is an example in C++:

A Global variable in C++ §#include §int Global_Num; // a global variable. §int main () { Global_Num = 5; // accesses global variable §} §void Another_Function () { § Global_Num = 7; // does it again §}

Global variables. §Notice that if a variable is defined globally, it can be accessed anywhere, *without* passing it as a parameter. §But then why pass parameters? §If we don’t, too much danger of data corruption. WHY?

What’s wrong with global variables? §Global variables lead to poor interface design. §They make it unclear to another programmer what is supposed to pass in and out of a function. Listing parameters forces us to think precisely about the communication between functions.

Why bother with parameters? §Using parameters is like “going through the proper channels. §It avoids doing an end-run / going around the side. §If we don’t do this, we allow “side effects.”

What are side-effects §Definition: §A side effect is any communication between 2 modules (functions) that is not specified by the interface.

Side effects (cont.). §Analogies: §1.Restaurant analogy. See diagram. Suppose the cook brings out food with no input from the customer, or the customer goes straight into the kitchen for food! §2.Theology: claiming Jesus is one of many ways to access the Father, yet there is only *one* mediator between God and man (1 Tim. 2: 5).

Solution of C# §C# is a more constrained language than C++. §In addition to rigorous type-checking, checking for initialization of variables and code-path checking, the designers of C# chose to remove temptation: §C# bans global variables.

4. Nested blocks. §Consider Russian dolls: §a miniature doll fits inside a slightly larger duplicate which fits inside another, until we reach the outermost doll. The smaller dolls are nested inside the larger dolls.

Nesting (cont.). §Likewise, in a computer program, one block can be nested inside another. §static void Main () { //outer block §while (Count != 10) { // singly nested block § if (Num > 7) { // doubly nested block § § } // doubly nested block §} // singly nested block § } // end outer block.

Nesting (cont.). §For example, one can have: § a nested if (an if inside an if), §a nested loop (a loop inside a loop) §and ifs inside loops or loops inside ifs. §Definition: nesting occurs when one block is defined inside another block.

Nesting and local variables. §C# allows you to define local variables within *any* block, not just in methods. §However, although C# allows local and class-wide variables to have the same name, unlike C++, you cannot use the same name for 2 local variables.

Nested blocks (cont.). §static void main ( ) { float Total = 0; // local to main int Count = 0; // local to main while (Count < 10) { int Num; // LEGAL cout << “Enter a number.” cin >> Num; Total + = Num; Count++; } // end while } // end main

Nested blocks (cont.). §static void main ( ) { float Total = 0; // local to main int Count = 0; // local to main int Num; // local to main while (Count < 10) { int Num; // ILLEGAL cout << “Enter a number.” cin >> Num; Total + = Num; Count++; } // end while } // end main

What if we do use the same name for a class-wide and a local variable? §Then, we are bad people. It is horrible programming practice. However, if we do… §…the compiler will reference the most recently defined. This is the rule of local precedence. §Compare: who do you mean by “Jack” given so many people with that name?

Example: §class Bundle { § double Big; // Big is a class-wide variable. §static void Find_Big (double X, double Y) { § double Big; // local Big blocks access to § // classwide Big § Big = X; // refers to local Big § if (Y > X) § Big = Y; // ditto §} // end Find_Big §}

5. Scope of identifiers. §The scope of an identifier is the region in which it is accessible. §Method names: this is simple, since they are class-wide. §They are accessible anywhere in the class. §(With OOP, we will see that methods can also be marked public, private or protected to regulate access by program clients of the class.)

Scope of identifiers (cont.). §For variable names, it is more complex. There are 3 cases to consider: §A) local variables §B) formal parameters (declared inside the function heading) §C) class-wide variables.

Scope of identifiers (cont.). §A) LOCAL VARIABLES. §not accessible outside the block that defines them. §B)FORMAL PARAMETERS. Are treated just like local variables. Accessible anywhere in the method that defines them except in a nested block that redefines them.

Scope of identifiers (cont.). §C)CLASS-WIDE variables. §Accessible anywhere in the class except in a nested block that redefines them. §One can see an emerging pattern. Although many texts give a long arcane list of scope rules, they all reduce to one. §One rule to rule them all, and in the darkness bind them!

Scope of identifiers (cont.). §The 1 scope rule: §An identifier can be accessed anywhere inside (not outside) the block that defines it, but not in a nested block that redefines it.