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

Slides:



Advertisements
Similar presentations
Objects and Classes Part II
Advertisements

CATHERINE AND ANNIE Python: Part 3. Intro to Loops Do you remember in Alice when you could use a loop to make a character perform an action multiple times?
Instruction Set Design
Programming Languages and Paradigms
Coding Standard: General Rules 1.Always be consistent with existing code. 2.Adopt naming conventions consistent with selected framework. 3.Use the same.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
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.
COEN Expressions and Assignment
Debugging Introduction to Computing Science and Programming I.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
Introduction to Computers and Programming Style Lecture Professor: Evan Korth New York University.
1 Variables (Chapters of Code Complete) Steve Chenoweth CSSE 375, Rose-Hulman Based on Don Bagert’s 2006 Lecture.
Computer Science 1620 Programming & Problem Solving.
Modules, Hierarchy Charts, and Documentation
CS241 PASCAL I - Control Structures1 PASCAL I - Control Structures Philip Fees CS241.
Guide To UNIX Using Linux Third Edition
Algorithm Programming Coding Advices Bar-Ilan University תשס " ו by Moshe Fresko.
Examining the Code [Reading assignment: Chapter 6, pp ]
General Issues in Using Variables
Code-Tuning By Jacob Shattuck. Code size/complexity vs computation resource utilization A classic example: Bubblesort A classic example: Bubblesort const.
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).
XP New Perspectives on Microsoft Office Access 2003 Tutorial 11 1 Microsoft Office Access 2003 Tutorial 11 – Using and Writing Visual Basic for Applications.
1 Understanding Inheritance COSC 156 C++ Programming Lecture 8.
Pointers CS362. Pointers A Pointer is a variable that can hold a memory address Pointers can be used to: Indirectly reference existing variables (sometimes.
GENERAL GUIDELINES FOR CODING. RULE #1 The most important aspect of the code is the readability If your code is incorrect it can be fixed (if it is readable)
National Diploma Unit 4 Introduction to Software Development Data types, variables and constants.
CSCI-383 Object-Oriented Programming & Design Lecture 13.
CS 320 Assignment 1 Rewriting the MISC Osystem class to support loading machine language programs at addresses other than 0 1.
6 Chapter 61 Looping Programming Logic and Design, Second Edition, Comprehensive 6.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
CS101 Computer Programming I Chapter 4 Extra Examples.
CS242.  Reduce Complexity  Introduce an intermediate, understandable abstraction  Avoid code duplication  Support subclassing  Hide sequences  Hide.
Guidelines for a Language- Independent Convention Identify global variables –Use g_prefix –Exp: g_RunningTotal Identify module variables –Use m_prefix.
Programmeerimine Delphi keskkonnas MTAT Programmeerimine Delphi keskkonnas MTAT Jelena Zaitseva
Best Practices for Variables
Using Variables Chapter Outline 2  Variable Initialization  Scope  Persistence  Using Each Variable for Single Purpose  Variable Names.
REFACTORINGREFACTORING. Realities Code evolves substantially during development Requirements changes 1%-4% per month on a project Current methodologies.
First Steps in Modularization. Simple Program Design, Fourth Edition Chapter 8 2 Objectives In this chapter you will be able to: Introduce modularization.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Computing and Statistical Data Analysis Lecture 2 Glen Cowan RHUL Physics Computing and Statistical Data Analysis Variables, types: int, float, double,
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
Chapter 5: Making Decisions. Objectives Plan decision-making logic Make decisions with the if and if…else structures Use multiple statements in if and.
Data Tonga Institute of Higher Education. Variables Programs need to remember values.  Example: A program that keeps track of sales needs to remember.
1 Compiler Construction (CS-636) Muhammad Bilal Bashir UIIT, Rawalpindi.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 2 – August 23, 2001.
Programming Languages Programming languages are a compromise between spoken language and formal math. They allow humans to communicate with computers at.
Week 12 - Monday.  What did we talk about last time?  Defining classes  Class practice  Lab 11.
Algorithms and Pseudocode
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
General Issues in Using Variables
Variables Names SCMP Special Topic: Software Development
Computing and Statistical Data Analysis Lecture 2
GC211Data Structure Lecture2 Sara Alhajjam.
C Programming Tutorial – Part I
Road Map Style Principle of proximity Naming variables if / else.
Lecture 3 of Computer Science II
CSE 143 Introduction to C++ [Appendix B] 4/11/98.
CS 240 – Lecture 11 Pseudocode.
Understanding Inheritance
Lesson 2: Building Blocks of Programming
Designing and Debugging Batch and Interactive COBOL Programs
College of Computer Science and Engineering
Variables Names CSC-3004 Introduction to Software Development
Dr. Bhargavi Dept of CS CHRIST
Loop Strategies Repetition Playbook.
Chapter 09 – Part II Using Variables
Chapter 7 Expressions and Assignment Statements.
Naming & Code Reviews.
Presentation transcript:

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

Steve McConnell’s Guidelines for the Smart Use of Variables

Implicit Declarations  Some compilers don ’ t require you to define variables before their first use.  “ One of the most hazardous features in any language. ”  Much easier to make mistakes.  Some compilers don ’ t require you to define variables before their first use.  “ One of the most hazardous features in any language. ”  Much easier to make mistakes.

Implicit Declarations  What should you do about it?  Turn implicit declarations off.  Declare all variables anyway.  Use naming conventions (num vs. no)  Check variable name listings from compiler.  What should you do about it?  Turn implicit declarations off.  Declare all variables anyway.  Use naming conventions (num vs. no)  Check variable name listings from compiler.

Initializing Variables  Improper data initialization is one of the most fertile sources of error in computer programming.  This may result in some of the following problems when a variable is used:  It has never been assigned a value.  It is outdated.  Only part of the variable is defined.  Improper data initialization is one of the most fertile sources of error in computer programming.  This may result in some of the following problems when a variable is used:  It has never been assigned a value.  It is outdated.  Only part of the variable is defined.

Initializing Variables  Initialize each variable close to where it is first used. Bad Initialization // initialize variables accountIndex = 0 total = 0.0 done = false … // code using accountIndex … // code using total … // code using done Good Initialization accountIndex = 0 // code using accountIndex … total = 0.0 // code using total … done = false // code using done

Initializing Variables  Other guidelines  Use “final” or “const” when possible.  Pay special attention to counters and accumulators (i, j, k, sum)  Initialize a class’s member data in its constructor.  Take advantage of compiler warnings.  Use a memory-access checker to find bad pointers.  Other guidelines  Use “final” or “const” when possible.  Pay special attention to counters and accumulators (i, j, k, sum)  Initialize a class’s member data in its constructor.  Take advantage of compiler warnings.  Use a memory-access checker to find bad pointers.

Scope  Local is usually better than global.  Keep “live time” as short as possible.  Local is usually better than global.  Keep “live time” as short as possible.

Scope  General guidelines for minimizing scope  Initialize variables used in a loop immediately before the loop.  Don’t assign a value to a variable until just before it is used.  Group related statements. (Or give them their own routine.)  Begin by restricting variable visibility as much as possible. Expand scope only when necessary.  General guidelines for minimizing scope  Initialize variables used in a loop immediately before the loop.  Don’t assign a value to a variable until just before it is used.  Group related statements. (Or give them their own routine.)  Begin by restricting variable visibility as much as possible. Expand scope only when necessary.

Binding Time  When is a variable given its value?  When the code is written  color = 0xFF;  When it is compiled  define USE_COLOR = 0xFF;  color = USE_COLOR;  When the program is run  color = getUserColorInput();  When is a variable given its value?  When the code is written  color = 0xFF;  When it is compiled  define USE_COLOR = 0xFF;  color = USE_COLOR;  When the program is run  color = getUserColorInput();

Binding Time  The “earlier” you bind a value to a variable, the less flexible your code is, but the more simple and less error-prone.  Binding later adds more flexibility, but also complexity (and the possibility of more errors).  The “earlier” you bind a value to a variable, the less flexible your code is, but the more simple and less error-prone.  Binding later adds more flexibility, but also complexity (and the possibility of more errors).

Use Variables for One Purpose  It’s sometimes tempting to use one variable in two different places for two different activities. Usually, the variable is named inappropriately for one of its uses or a “temp” variable is used in both cases.  This is not helpful.  It’s sometimes tempting to use one variable in two different places for two different activities. Usually, the variable is named inappropriately for one of its uses or a “temp” variable is used in both cases.  This is not helpful.

Use Variables for One Purpose One Variable for Two Purposes // Compute roots of a quadratic equation. 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; Two Variables for Two Purposes // Compute roots of a quadratic equation. discriminant = Sqrt( b*b - 4*a*c); root[0] = (-b + discriminant) / (2 * a); root[1] = (-b - discriminant) / (2 * a); … // swap the roots oldRoot = root[0]; root[0] = root[1]; root[1] = oldRoot;

Use Variables for One Purpose  Avoid variables with hidden meanings  “pageCount represents the number of pages, unless it equals -1, which means there was an error.”  “customerId represents the customer number, unless its value is greater than 500,000, in which case you subtract 500,000 to get the number of a delinquent account.”  Avoid variables with hidden meanings  “pageCount represents the number of pages, unless it equals -1, which means there was an error.”  “customerId represents the customer number, unless its value is greater than 500,000, in which case you subtract 500,000 to get the number of a delinquent account.”

Use Variables for One Purpose  Make sure that all declared variables are used.  A study by Card, Church, and Agresti found that unreferenced variables were correlated with higher fault rates.  Some compilers and utilities will report unused variables as warnings.  Make sure that all declared variables are used.  A study by Card, Church, and Agresti found that unreferenced variables were correlated with higher fault rates.  Some compilers and utilities will report unused variables as warnings.

Choosing Variable Names Poor Variable Names x = x - xx; xxx = fido + SalesTax( fido ); x = x + LateFee( x1, x ) + xxx; x = x + Intereset( x1, x ); Good Variable Names balance = balance - lastPayment; monthlyTotal = newPurchases + SalesTax( newPurchases ); balance = balance + LateFee( customerID, balance ) + monthlyTotal; balance = balance + Interest( customerID, balance );

Choosing Variable Names  The variable name should fully and accurately describe the entity it represents.  Example:  Purpose of variable: the current date  Good names: currentDate, todaysDate  Bad names: cd, date, current  The variable name should fully and accurately describe the entity it represents.  Example:  Purpose of variable: the current date  Good names: currentDate, todaysDate  Bad names: cd, date, current

Choosing Variable Names  The name should describe the problem, rather than the solution.  (“what” instead of “how”)  Examples:  For a record of employee data:  employeeData rather than inputRecord  For a bit field indicating if printer is ready:  printerReady rather than bitFlag  The name should describe the problem, rather than the solution.  (“what” instead of “how”)  Examples:  For a record of employee data:  employeeData rather than inputRecord  For a bit field indicating if printer is ready:  printerReady rather than bitFlag

Choosing Variable Names  The optimal length for a variable name is between 8 and 20 characters.  Too long:  numberOfPeopleOnTheUsOlympicTeam  numberOfSeatsInTheStadium  Too short:  n, np, ntm  n, ns, nsisd  Just right:  numTeamMembers, teamMemberCount  numSeatsInStadium, seatCount  The optimal length for a variable name is between 8 and 20 characters.  Too long:  numberOfPeopleOnTheUsOlympicTeam  numberOfSeatsInTheStadium  Too short:  n, np, ntm  n, ns, nsisd  Just right:  numTeamMembers, teamMemberCount  numSeatsInStadium, seatCount

Choosing Variable Names  Be consistent  Standardize common qualifiers such as Total, Sum, Max, Str, or Ptr  Consistently put qualifiers at the end of the name (costTotal, frogMax)  You won’t have to guess whether it’s frogMax or maxFrogs  The important part of the variable name comes first. (“What is the variable about”)  Be consistent  Standardize common qualifiers such as Total, Sum, Max, Str, or Ptr  Consistently put qualifiers at the end of the name (costTotal, frogMax)  You won’t have to guess whether it’s frogMax or maxFrogs  The important part of the variable name comes first. (“What is the variable about”)

Naming Specific Types of Data  Loop Indexes  i, j, and k are customary  If a “counter” variable will be used outside the loop, give it a better name.  Loop Indexes  i, j, and k are customary  If a “counter” variable will be used outside the loop, give it a better name. Good Descriptive Loop Variable Name recordCount = 0; while ( moreScores() ) { score[ recordCount ] = GetNextScore(); recordCount++; } // lines using recordCount...

Naming Specific Types of Data  Status Variables  Don’t use “flag” in the name. It doesn’t tell you anything helpful.  Remember: the name should say “what” it’s for, not how it does it.  Status Variables  Don’t use “flag” in the name. It doesn’t tell you anything helpful.  Remember: the name should say “what” it’s for, not how it does it. Bad if ( flag )... if ( printerFlag == 16 )... if (computerFlag == 0 )... Good if ( done )... if ( printerStatus == printerStatus_Ready )... if ( recalcNeeded == false )...

Naming Specific Types of Data  Boolean Variables  Keep “typical” names in mind:  done  error  found  success  Use a name that implies true or false.  Use “positive” names  found instead of notFound  if ( not found ) is easier to understand than if ( not notFound )  Boolean Variables  Keep “typical” names in mind:  done  error  found  success  Use a name that implies true or false.  Use “positive” names  found instead of notFound  if ( not found ) is easier to understand than if ( not notFound )

Naming Specific Types of Data  Enumerated Types  Use the type name as the prefix for each member of the type for clarity.  Enumerated Types  Use the type name as the prefix for each member of the type for clarity. Examples Public Enum Color Color_Red Color_Green Color_Blue End Enum Public Enum Planet Planet_Earth Planet_Mars End Enum

Naming Conventions  Why have conventions?  They let you take more for granted. One global decision rather than many local ones.  They help you transfer knowledge across projects.  They reduce name proliferation. You’re less likely to accidentally use totalPoints when you mean pointTotal.  Why have conventions?  They let you take more for granted. One global decision rather than many local ones.  They help you transfer knowledge across projects.  They reduce name proliferation. You’re less likely to accidentally use totalPoints when you mean pointTotal.

Naming Conventions  Why have conventions? (cont.)  They emphasize relationships among related items. This is especially helpful if your language doesn’t support objects.  Why have conventions? (cont.)  They emphasize relationships among related items. This is especially helpful if your language doesn’t support objects. Settings Data as Object settings.font = ‘helvetica’; settings.fontSize = 14; settings.fontColor = ‘red’; Settings Data without Object settings_font = ‘helvetica’; settings_fontSize = 14; settings_fontColor = ‘red’;

Naming Conventions  When should you have a naming convention?  When multiple programmers are working on a project  When another programmer will be doing maintenance on your project  When your code is reviewed by other programmers in the organization  When should you have a naming convention?  When multiple programmers are working on a project  When another programmer will be doing maintenance on your project  When your code is reviewed by other programmers in the organization

Naming Conventions  When should you have a naming convention? (cont.)  When your program is so large that you must think about it in pieces.  When you might have to come back to it after a few weeks of being away.  When you have a lot of unusual terms that are common on a project and want to have standard terms or abbreviations to use in coding.  When should you have a naming convention? (cont.)  When your program is so large that you must think about it in pieces.  When you might have to come back to it after a few weeks of being away.  When you have a lot of unusual terms that are common on a project and want to have standard terms or abbreviations to use in coding.

Informal Language-Independent Naming Convention Guidelines  Differentiate between variables and routines  variableName vs. RoutineName()  Differentiate between classes and objects  Use a more specific name for the variable. If class is Widget, variable could be employeeWidget.  Identify global variables  For example, g_RunningTotal  Differentiate between variables and routines  variableName vs. RoutineName()  Differentiate between classes and objects  Use a more specific name for the variable. If class is Widget, variable could be employeeWidget.  Identify global variables  For example, g_RunningTotal

Informal Language-Independent Naming Convention Guidelines  Identify class member variables  One method is to use a prefix of m_  Identify type definitions  All caps, or a t_ prefix  Identify named constants  All caps, or a c_ prefix  Identify enumerated types  e_ or E_ prefix  Identify class member variables  One method is to use a prefix of m_  Identify type definitions  All caps, or a t_ prefix  Identify named constants  All caps, or a c_ prefix  Identify enumerated types  e_ or E_ prefix

Informal Language-Independent Naming Convention Guidelines  Identify input-only parameters in languages that don’t enforce them  Use const_ or final_ prefixes on parameters that should not be modified.  Format names for readibility  GYMNASTICSPOINTTOTAL is harder to read than gymnasticsPointTotal or gymnastics_point_total  Identify input-only parameters in languages that don’t enforce them  Use const_ or final_ prefixes on parameters that should not be modified.  Format names for readibility  GYMNASTICSPOINTTOTAL is harder to read than gymnasticsPointTotal or gymnastics_point_total

Conclusion  Be consistent.  Be helpful.  Be consistent.  Be helpful.

Questions?