Chapter 09 – Part II Using Variables

Slides:



Advertisements
Similar presentations
Variables and Powerful Names Nathan Scheck CS525 Software Engineering II Fall II 2007 – Sheldon X. Liang, Ph.D. Nathan Scheck CS525 Software Engineering.
Advertisements

Programming III SPRING 2015 School of Computer and Information Sciences Francisco R. Ortega, Ph.D. McKnight Fellow and GAANN Fellow LECTURE #3 Control.
C++ Basics Variables, Identifiers, Assignments, Input/Output.
Software Engineering Variables. The data literacy test Count 1.0 if you know what the concept means. Count 0.5 if you believe you know what the concept.
Variables and Powerful Naming Ryan Ruzich. Naming Considerations The most important consideration in naming a variable is that the name fully and accurately.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Lecture-5 Though SQL is the natural language of the DBA, it suffers from various inherent disadvantages, when used as a conventional programming language.
10-Jun-15 Introduction to Primitives. 2 Overview Today we will discuss: The eight primitive types, especially int and double Declaring the types of variables.
Road Map Introduction to object oriented programming. Classes
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
CS241 PASCAL I - Control Structures1 PASCAL I - Control Structures Philip Fees CS241.
C++ for Engineers and Scientists Third Edition
General Issues in Using Variables
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).
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Lecture # 5 Methods and Classes. What is a Method 2 A method is a set of code which is referred to by name and can be called (invoked) at any point in.
CPS120: Introduction to Computer Science Variables and Constants Lecture 8 - B.
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Procedures and Functions Computing Module 1. What is modular programming? Most programs written for companies will have thousands of lines of code. Most.
C Derived Languages C is the base upon which many build C++ conventions also influence others *SmallTalk is where most OOP comes Java and Javascript have.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
CPS120: Introduction to Computer Science
Defining and Converting Data Copyright Kip Irvine, 2003 Last Update: 11/4/2003.
1 Type Checking Type checking ensures that the operands and the operator are of compatible types Generalized to include subprograms and assignments Compatible.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
CPS120: Introduction to Computer Science Functions.
Current Assignments Homework 2 is available and is due in three days (June 19th). Project 1 due in 6 days (June 23 rd ) Write a binomial root solver using.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Guidelines for a Language- Independent Convention Identify global variables –Use g_prefix –Exp: g_RunningTotal Identify module variables –Use m_prefix.
Best Practices for Variables
Using Variables Chapter Outline 2  Variable Initialization  Scope  Persistence  Using Each Variable for Single Purpose  Variable Names.
Copyright Curt Hill Variables What are they? Why do we need them?
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
Chapter 4 Literals, Variables and Constants. #Page2 4.1 Literals Any numeric literal starting with 0x specifies that the following is a hexadecimal value.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
Chapter 3: Developing Class Methods Object-Oriented Program Development Using Java: A Class-Centered Approach.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
1 Compiler Construction (CS-636) Muhammad Bilal Bashir UIIT, Rawalpindi.
CPS120: Introduction to Computer Science Variables and Constants.
Programming Languages Programming languages are a compromise between spoken language and formal math. They allow humans to communicate with computers at.
1 Scope Lifetime Functions (the Sequel) Chapter 8.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
Memory Management.
General Issues in Using Variables
Data Types In Text: Chapter 6.
JAVA MULTIPLE CHOICE QUESTION.
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 3 Introduction to Classes, Objects Methods and Strings
Advanced Programming Basics
6 Chapter Functions.
Variables, Identifiers, Assignments, Input/Output
Variables Title slide variables.
Introduction to Primitives
Java Programming Language
Java’s Central Casting
Chap 2. Identifiers, Keywords, and Types
Corresponds with Chapter 5
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Presentation transcript:

Chapter 09 – Part II Using Variables

Outline Variable Initialization Scope Persistence Using Each Variable for Single Purpose Variable Names

Data Literacy Test literal local variables lookup table member data 33 Data Literacy Test abstract data type array bitmap boolean variable b-tree character variable container class double precision elongated stream enumerated type floating point literal local variables lookup table member data pointer private retroactive synapse referential integrity stack string structured variable tree typedef union value chain variant Total Score 1: familiar 0.5: know what a term means but aren’t sure 33

Loose Interpretation 0-14: beginning programmer 44 Loose Interpretation 0-14: beginning programmer 15-19: intermediate programmer, or An experienced programmer who has forgotten a lot 20-24: expert programmer 25-29: know more about data types than Steve Consider writing your own book 30-32: your are a pompous fraud Elongated stream, retroactive synapse, value chain don’t refer to data types 44

Variable Initialization Problem 55 Variable Initialization Problem A variable may contain an initial value that you do not expect it to contain Never been assigned a value Outdated: assigned a value at some point, but no longer valid Part of the variable assigned a value, part has not 55

Guidelines for Variable Initialization 66 Guidelines for Variable Initialization Initialize each variable as it is declared Inexpensive form of defensive programming Initialize each var close to where it’s first used Some languages (e.g., VB) do not support initializing variables as they are declared Principle of proximity: keep related action together Ideally, declare and define each variable close to where it’s first used int accountIndex = 0; // code using accountIndex … double total = 0.0; // code using total … boolean done = false; // code using done while ( ! done ) { ... } 66

Guidelines for Variable Initialization 77 Guidelines for Variable Initialization Use final or const when possible Pay attention to counters and accumulators Forget to reset before the next time it is used Initialize a class’s member data in constructor Check the need to re-initialization Used by a loop used many times Needs to be reset between calls Use the compiler setting that automatically initialize variables 77

Guidelines for Variable Initialization 88 Guidelines for Variable Initialization Take advantage of compiler’s warning messages Check input parameters for validity Use a memory access checker to check for bad pointers Initialize working memory to a known value at the beginning of your program 88

Scope Scope or visibility 99 Scope Scope or visibility The extent to which the variable is known and can be referenced throughout the program Maximizing scope Convenience, e.g., global variables Easier to write; Harder to understand/debug/modify Minimizing scope Keep variables as local as possible Intellectual manageability, Easier to read Code programs to read or write? 99

Localize References to Variables 10101010 Localize References to Variables The code between references to a variable is a ‘window of vulnerability’ New code might be added, inadvertently altering the variable Someone reading the code might forget the value the variable is supposed to contain Measure how close together the references are span 1010

Variable Span a =0; b=0; c=0; b=a+1; b=b/c; 11111111 Variable Span a =0; b=0; c=0; b=a+1; b=b/c; 1 line between 1st/2nd references to b: span of 1 0 line between 2nd/3rd references to b: span of 0 Average span For b, (1+0)/2=0.5 1111

Live Time Total # of statements over which a variable is live 12121212 Live Time Total # of statements over which a variable is live Life begins/ends at the first/last reference isn't affected by how many times the variable is used between the first and last times it's referenced. 1212

Measuring Live Time recordIndex: 28-2+1 total: 69-3+1 done: 70-4+1 13131313 Measuring Live Time 1 // initialize all variables 2 recordIndex = 0 ; 3 total = 0; 4 done = false; … 26 while (recordIndex<recordCount){ 27 … 28 recordIndex = recordIndex+1; 64 while (!done) { 69 if (total>projectedTotal) { 70 done = true; recordIndex: 28-2+1 total: 69-3+1 done: 70-4+1 Average: 54 1313

Measuring Live Time - cont 14141414 Measuring Live Time - cont … 25 recordIndex = 0 ; 26 while (recordIndex<recordCount){ 27 … 28 recordIndex = recordIndex+1; 62 total = 0 ; 63 done = false; 64 while (!done) { 69 if (total>projectedTotal) { 70 done = true; recordIndex: 28-25+1 total: 69-62+1 done: 70-63+1 Average: 7 1414

Keep Variables ‘Live’ for a Short Time 15151515 Keep Variables ‘Live’ for a Short Time Keep live time as short as possible: advantages Reduce the window of vulnerability Concentrate on a smaller section of code Reduce the chance of initialization errors Make the code more readable Easier for refactoring or splitting a large routine into smaller routines 1515

What Do You Think? 16161616 1616 void SummarizeData(…){ … GetOldData( oldData, &numOldData); GetnewData(newData, &numNewData); totalOldData = sum(oldData, numOldData); totalNewData = sum(newData, numNewData); PrintOldDataSummary(oldData, totalOldData, numOldData); PrintNewDataSummary(newData, totalNewData, numNewData); SaveOldDataSummary(totalOldData, numOldData); SaveNewDataSummary(totalNewData, numNewData); } 1616

Guidelines for Minimizing Scope 17171717 Guidelines for Minimizing Scope 1717

Guidelines for Minimizing Scope 18181818 Guidelines for Minimizing Scope Group related statements, and, if necessary, break related statements into separate routines Don't assign a value to a variable until just before the value is used 1818

Guidelines for Minimizing Scope 19191919 Guidelines for Minimizing Scope Initialize variables used in a loop immediately before the loop rather than back at the beginning of the routine containing the loop When modify the loop, remember to make corresponding modifications to the initialization Favor the smallest possible scope Local to a specific loop, local to a routine, private to a class, then protected, then package, Global only as last resort 1919

Persistence Some variables persist 20202020 Persistence Some variables persist For the life of a block of code or routine Variables inside a for loop As long as you allow them to Objects created with new persist until garbage collected For the life of a program Global variables Forever Variables include values in database Problem - If you assume that a variable has a longer persistence than it really does 2020

Avoiding Persistence Problem 21212121 Avoiding Persistence Problem Use debug code or assertions to check critical variables for reasonable values Set variables to unreasonable values when you are through with them Set a pointer to null after you delete it Write code that assumes data isn’t persistent Develop the habit of declaring and initializing all data right before it’s used Be suspicious if data is used without a nearby initialization. 2121

What Do You Think? // compute roots of a quadratic equation 22222222 What Do You Think? // compute roots of a quadratic equation // this code assumes that (b*b-4*a*c) is positive temp = sqrt (b*b-4*a*c); root[0] = (-b + temp) / (2*a); root[1] = (-b - temp) / (2*a); … //swap the roots temp = root[0]; root[0] = root[1]; root[1] = temp; 2222

Using Each Variable for Single Purpose 23232323 Using Each Variable for Single Purpose Using the same variable for different purposes makes it seem as though they are related when they’re not! Use discriminant for the first temp Use oldRoot for the second temp 2323

Using Each Variable for Single Purpose 24242424 Using Each Variable for Single Purpose Avoid variables with hidden meanings - different values mean different things customerID: a customer number unless its value>=500,000, in which case subtracting 500,000 results in the number of a delinquent account Make sure all declared variables are used 2424

What Do You Think? x = x –xx; xxx = fido + SalesTax(fido); 25252525 What Do You Think? x = x –xx; xxx = fido + SalesTax(fido); x = x +LateFee(x1, x) + xxx; x = x + Interest(x1, x); 2525

Kinds of Names to Avoid Avoiding misleading names or abbreviations 26262626 Kinds of Names to Avoid Avoiding misleading names or abbreviations Avoid names with similar meanings recordNum/numRecords Avoid names that sound similar wrap/rap Avoid numerals in names Avoid misspelled words in names Don’t differentiate names solely by capitalization Avoid multiple natural languages check/cheque 2626

Kinds of Names to Avoid - cont 27272727 Kinds of Names to Avoid - cont Avoid the names of standard types, variables, and routines If if=then then then = else; else else = if; // PL/1 Avoid names containing hard-to-read chars (1, l, I), (0, O), (2, Z), (S, 5), ... Don’t use names that are totally unrelated to what the variables represent 2727

Reading The Power of Variable Names ‘Code Complete’ Chapter 11. 28282828 Reading The Power of Variable Names ‘Code Complete’ Chapter 11. 2828