Communicating in Code: Layout and Style

Slides:



Advertisements
Similar presentations
Communicating in Code: Layout and Style Programming Studio Spring 2012 Note: several examples in this lecture taken from The Practice of Programming by.
Advertisements

Software Engineering Table-driven methods General control issues.
Communicating in Code: Layout and Style Programming Studio Spring 2009 Note: several examples in this lecture taken from The Practice of Programming by.
Introduction to C Programming
Coding Standards A Presentation by Jordan Belone.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 2: Your First Program.
15-Jun-15 Beginning Style. 2 Be consistent! Most times, you will enter an ongoing project, with established style rules Follow them even if you don’t.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
26-Jun-15 Beginning Style. 2 Be consistent! Most times, you will enter an ongoing project, with established style rules Follow them even if you don’t.
1 Midterm Review COMP 102. Tips l Eat a light meal before the exam l NO electronic devices (including calculators, dictionaries, phones, pagers, etc.)
Chapter 2: Introduction to C++.
Introduction to C Programming
IS 1181 IS 118 Introduction to Development Tools VB Chapter 03.
Computer Science 1620 Lifetime & Scope. Variable Lifetime a variable's lifetime is finite Variable creation: memory is allocated to the variable occurs.
Fruitful functions. Return values The built-in functions we have used, such as abs, pow, int, max, and range, have produced results. Calling each of these.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
Spring 2005, Gülcihan Özdemir Dağ Lecture 3, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 3 Outline 3.1 Introduction.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
How to think through your program [ principles of good program design ] Rachel Denison MATLAB for Cognitive Neuroscience ICN, 13 December 2007.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
1 Lecture 5: Selection Structures. Outline 2  Control Structures  Conditions  Relational Operators  Logical Operators  if statements  Two-Alternatives.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
CPS120: Introduction to Computer Science
Copyright © 2012 Pearson Education, Inc. Chapter 2: Introduction to C++
CPS120: Introduction to Computer Science Decision Making in Programs.
Lecture 2: Introduction to C Programming. OBJECTIVES In this lecture you will learn:  To use simple input and output statements.  The fundamental data.
1 FUNCTIONS - I Chapter 5 Functions help us write more complex programs.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Today: –Review declaration, implementation, simple class structure. –Add an exception class and show.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Controlling Program Flow with Decision Structures.
ATS Programming Short Course I INTRODUCTORY CONCEPTS Tuesday, Feb 10th, 2009 Introduction to Programming.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Copyright © Curt Hill The C++ IF Statement More important details More fun Part 3.
The for Statement A most versatile loop
2.1 The Part of a C++ Program. The Parts of a C++ Program // sample C++ program #include using namespace std; int main() { cout
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
JavaScript: Conditionals contd.
User-Written Functions
More on the Selection Structure
Computing and Statistical Data Analysis Lecture 2
Predefined Functions Revisited
Bill Tucker Austin Community College COSC 1315
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
More important details More fun Part 3
EGR 2261 Unit 4 Control Structures I: Selection
Communicating in Code: Layout and Style
Chapter 2.1 Control Structures (Selection)
Chapter 5 Function Basics
CSC113: Computer Programming (Theory = 03, Lab = 01)
Communicating in Code: Commenting
Control Structures – Selection
Communicating in Code: Layout and Style
Chapter 4: Control Structures I (Selection)
Chapter 1: Computer Systems
TIPS: How to Be Successful
Computing Fundamentals
Topics Introduction to Functions Defining and Calling a Void Function
Beginning Style 27-Feb-19.
Chapter 2: Introduction to C++.
Topics Introduction to Functions Defining and Calling a Function
An Overview of C.
Variables in C Topics Naming Variables Declaring Variables
Controlling Program Flow
Class code for pythonroom.com cchsp2cs
Creating readable code
Presentation transcript:

Communicating in Code: Layout and Style Programming Studio, Fall 2017 Tanzir Ahmed Note: several examples in this lecture taken from The Practice of Programming by Kernighan and Pike

Layout and Style Like naming, the goal is to communicate Again like naming, sometimes conventions are in place Adhering to the convention in place will usually lead to more readable code than using your own “better” convention Goal of layout and style is to increase clarity.

Fundamental Theorem of Formatting Good visual layout shows the logical structure of the program. Studies show that organization is as important to understanding as the “details”

White Space Used to indicate logical grouping Spacing between characters Indentation Blank lines

Line Breaks Use blank lines to separate different sections of code Separate concepts should be reflected by separate blocks of code Should usually comment start of each “block” Put blank lines between functions/methods.

Indentation Can clarify structure, especially in odd cases Studies show that 2-4 space indentation works best. More indentation might “appear” better, but is not Now, usually editors provide automatically But, variations for some statements: switch/case if/elseif Brace conventions differ, but be consistent

Example Brace Conventions while (something) { blahblahblah } while (something) { blahblahblah } while (something) { blahblahblah } while (something) { blahblahblah }

Parentheses Parentheses can resolve ambiguity Particularly important since order of operations can be problematic Better to use more parentheses than you think you need Coupled with white space, can more quickly highlight the grouping/ordering of operations leap_year = y % 4 == 0 && y % 100 != 0 || y % 400 == 0;

Parentheses Parentheses can resolve ambiguity Particularly important since order of operations can be problematic Better to use more parentheses than you think you need Coupled with white space, can more quickly highlight the grouping/ordering of operations leap_year = y % 4 == 0 && y % 100 != 0 || y % 400 == 0; leap_year = ((y%4 == 0) && (y%100 != 0)) || (y%400 == 0);

Optional Braces Like parentheses, use more(??) braces than you need One-statement operation often becomes more, later if (a > b) max = a;

Optional Braces Like parentheses, use more braces than you need One-statement operation often becomes more, later if (a > b) max = a; cout << “Set a new maximum.” << endl;

Optional Braces Like parentheses, use more braces than you need One-statement operation often becomes more, later if (a > b) { max = a; }

Braces Like parentheses, use more braces than you need. One-statement operation often becomes more, later. if (a > b) { max = a; cout << “Set a new maximum.” << endl; }

Avoiding Complex Expressions Goal is not to write most concise and clever code Break up expressions to make them clearer The “?” operator can be especially problematic *x += (*xp=(2*k < (n-m) ? c[k+1] : d[k--])); if (2*k < n-m) *xp = c[k+1]; else *xp = d[k--]; *x += *xp;

Avoiding Complex Expressions Goal is not to write most concise and clever code Break up expressions to make them clearer The “?” operator can be especially problematic *x += (*xp=(2*k < (n-m) ? c[k+1] : d[k--])); if (2*k < n-m) { *xp = c[k+1]; } else { *xp = d[k--]; } *x += *xp;

Use “Natural Form” for Expressions State conditional tests positively if (!(z>=0) && !(z<a)) if ((z<0) && (z>=a)) This can vary if the way it’s expressed better matches the underlying algorithm

Use “idomatic” forms There are “common” ways of expressing certain things. e.g. Use a for loop appropriately – loop control in the for statement, and other operations outside for (i=0;i<n;i++) a[i] = 0.0; for (i=0;i<n;a[i++]=0.0); for (i=0;i<n;) { i++ }

Idiomatic forms Use if-elseif-else form whenever possible Alternatives are more difficult to understand if (cond1) { dothis1(); } else { if (cond2) { dothis2(); if (cond3) { dothis3(); dothis4(); } if (cond1) { dothis1(); } else if (cond2) { dothis2(); } else if (cond3) { dothis3(); } else { dothis4(); }

If statements Read so that you look for the “true” case rather than a “stack” of else cases if (a > 3) { if (b < 12) { while (!EOF(f)) { dothis(); } } else { cerr << “Error 2” << endl; cerr << “Error 1” << endl; if (a <= 3) { cerr << “Error 1” << endl; } else if (b >= 12) { cerr << “Error 2” << endl; } else { while (!EOF(f)) { dothis(); }

Avoid Magic Numbers The constant values that we use in our programs Rule of thumb: any number other than 0 or 1 is probably a “magic number” Can lead to tremendous debugging problems when these numbers are changed One change is out-of-sync with others Instead, define constants, or variables, to give names to those numbers. int a = 1 – a; // alternating between 1 and 0 int a = rand ()%100 + 1; //random num. in range [1,100] No need to have variables replacing “1”

Avoid Magic Numbers Rule of thumb: any number other than 0 or 1 is probably a “magic number” Can lead to tremendous debugging problems when these numbers are changed Instead, define constants, or variables, to give names to those numbers. Even better const int WINHEIGHT = 400; windowPosY = WINHEIGHT-y windowPosY = 400-y; OK OR int WINHEIGHT = 400; windowPosY = WINHEIGHT-y #define WINHEIGHT 400 … windowPosY = WINHEIGHT-y

Layout for Control Structures Put control in one line when possible Single indentation level for what it affects xxxxxx xxxxx Group each part of a complicated condition on its own line Same idea as before, break-down whenever necessary

Layout of Individual Statements White space can improve readability Spaces after commas Write it in the same way you write English EvaluateEmployee(Name.First,EmployeeID,Date.Start,Da te.End); EvaluateEmployee (Name.First, EmployeeID, Date.Start, Date.End); Spaces between parts of conditions if (((a<b)||(c>d))&&((a+b)<(c-d))&&((c-d)>2)) If ((a<b) || (c>d)) && ((a+b)<(c-d)) && ((c-d)>2))

Layout of Individual Statements White space can improve readability Spaces after commas EvaluateEmployee(Name.First,EmployeeID,Date.Start,Date.End); EvaluateEmployee (Name.First, EmployeeID, Date.Start, Date.End); Spaces between parts of conditions if (((a<b)||(c>d))&&((a+b)<(c-d))&&((c-d)>2)) if (((a<b) || (c>d)) && ((a+b)<(c-d)) && ((c-d)>2)) if (((a<b) || (c>d)) && ((a+b) < (c-d)) && ((c-d) > 2) )

Layout of Individual Statements Line up related definitions or assignments StudentName = ProcessInputName(); StudentID = ProcessInputID(); StudentHometown = ProcessInputName(); There is a big problem with this, though!

Layout of Individual Statements Line up related definitions or assignments Don’t use more than one statement per line. Likewise, define only one variable per line. Exception: when defining sets of variables or writing statements with same purpose x = ray.computehits(); nhits = x.size(); // unrelated x = ray.computehits(); //better nhits = x.size(); ------------------------------------------------------ int i; float[3] newpoint; //dissimilar data types int i; float[3] newpoint; ------------------------------------------------------- point vertex1, vertex2, vertex3; // variables with similar purposes a[i]=b[i]=c[i]=0.0;

Layout of Individual Statements Line up related definitions or assignments Don’t use more than one statement per line. Avoid side-effects (such as including the ++ operator when doing something else). Try to write in separate statements. x[i++] = 0; x[i] = 0; i++;

When a Line is Too Long Make it clear that the previous line is not ending (e.g. end with an operator) Keep related parts of the line together (don’t break single thought across line) Use indentation to highlight that there’s a continuation Make it easy to find the end of the continued line

When a line is too long Clear continuation Indentation retirementFunds=AmtAfterTax(Compound(checkingBalance,checkingRate, yearsleft)+Compound(savingsBalance,savingsRat,yearsleft)+Compound( mutualFundBalance,fundRate,yearsleft),taxRate)+Compound(rothiraBalance ,fundRate,yearsleft); retirementFunds = AmtAfterTax ( Compound (checkingBalance, checkingRate, yearsleft) + Compound (savingsBalance, savingsRat, yearsleft) + Compound (mutualFundBalance, fundRate, yearsleft), taxRate) + Compound(rothiraBalance, fundRate, yearsleft); Clear continuation Indentation

Layout of Routines Use standard indentation approach for arguments Use blank lines to separate parts of routines or blocks of common actions Slightly different idea/purpose Just like an essay where Paragraphs are used to separate ideas Use comments (will return to it later) to identify major breaks in conceptual flow Completely different idea

Layout of Files Clearly separate (multiple line breaks) different routines in the same file Don’t want to accidentally “merge” or “break” individual routines Also helps easy navigation Sequence functions inside files in a logical manner Functions in a .cpp files are written in the same order as in the .h files Or, in alphabetical order Or, Constructor, accessor, destructor, other – in this order Again, whatever you choose, be consistent