The Elements of Programming Style

Slides:



Advertisements
Similar presentations
Chapter 9 – One-Dimensional Numeric Arrays. Array u Data structure u Grouping of like-type data u Indicated with brackets containing positive integer.
Advertisements

CSE 105 Structured Programming Language Presentation - 2
Programming Languages and Paradigms The C Programming Language.
Communicating in Code: Layout and Style Programming Studio Spring 2012 Note: several examples in this lecture taken from The Practice of Programming by.
Communicating in Code: Layout and Style Programming Studio Spring 2009 Note: several examples in this lecture taken from The Practice of Programming by.
Structure of a C program
XP 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties Tutorial 10.
. Welcome to PLAB. Course Staff Teacher:  Nir Friedman Teaching Assistants:  Yoseph Barash  Liad Blumrosen  Michael Okun.
Chapter 2: Introduction to C++.
Character Input and Output
CSC 125 Introduction to C++ Programming Chapter 2 Introduction to C++
F28PL1 Programming Languages Lecture 7 Programming in C - 2.
1 Computing Software. Programming Style Programs that are not documented internally, while they may do what is requested, can be difficult to understand.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
CS1 Lesson 2 Introduction to C++ CS1 Lesson 2 -- John Cole1.
Programming Style* Objective: For students to appreciate the importance of good programming style and to develop good programming style themselves. –“Well-written.
XP Tutorial 10New Perspectives on Creating Web Pages with HTML, XHTML, and XML 1 Working with JavaScript Creating a Programmable Web Page for North Pole.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Java Coding Standards and Best Practices Coding Standards Introduction: After completing this chapter, you will able to keep your code up to standards.
Advanced Computer Science Lab Coding Style & Documentation.
Copyright © 2012 Pearson Education, Inc. Chapter 2: Introduction to C++
# ACS 168 Structured Programming Using the Computer Chapter 2 Spring 2002 Prepared by Shirley White.
Chapter 05 (Part III) Control Statements: Part II.
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
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.
CPS120 Introduction to Computer Science Exam Review Lecture 18.
Programming Style* Objective: For students to appreciate the importance of good programming style and to develop good programming style themselves. “Well-written.
Chapter 1 slides1 What is C? A high-level language that is extremely useful for engineering computations. A computer language that has endured for almost.
Welcome to Data Structures in C++. Course Staff 2 Teacher : Ofir Pele TA: Teachers of other groups: Roman Yavich.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
2.1 The Part of a C++ Program. The Parts of a C++ Program // sample C++ program #include using namespace std; int main() { cout
Basic Data Types & Memory & Representation
Program style.
The if…else Selection Statement
Chapter 2: Introduction to C++
CS Computer Science IA: Procedural Programming
Selection (also known as Branching) Jumail Bin Taliba by
Characters and Strings
C Programming Tutorial – Part I
Programming Languages and Paradigms
Command Line Arguments
EGR 2261 Unit 4 Control Structures I: Selection
Quiz 11/15/16 – C functions, arrays and strings
Communicating in Code: Layout and Style
BY GAWARE S.R. COMPUTER SCI. DEPARTMENT
C Basics.
Chapter 2: Introduction to C++
Communicating in Code: Layout and Style
Communicating in Code: Layout and Style
2.1 Parts of a C++ Program.
Introduction to Primitive Data types
Introduction to C Topics Compilation Using the gcc Compiler
The Elements of Programming Style
Chapter 2: Introduction to C++.
CS150 Introduction to Computer Science 1
Introduction to C Topics Compilation Using the gcc Compiler
CS150 Introduction to Computer Science 1
Fundamental Programming
C Programming - Lecture 5
Variables in C Topics Naming Variables Declaring Variables
C Language B. DHIVYA 17PCA140 II MCA.
Characters and Strings
C Structures and Commands
CSE 206 Course Review.
Introduction to Primitive Data types
INTRODUCTION TO C.
Chapter 13 Control Structures
Presentation transcript:

The Elements of Programming Style

What distinguishes journeyman from master? Attitude Style Philosophy

Names Use descriptive names for globals. Use short names for locals. Be consistent. Use active names for functions. Be accurate.

Names Use descriptive names for global variables. It is also helpful to include a brief comment with the declaration of each global. int npending = 0; // current length of input queue

Use short names for locals. i, j for loop indices, p, q for pointers, s, t for string Clarity is often achieved through brevity for (theElementIndex=0; theElementIndex<numberOfElements; theElementIndex++) elementArray[theElementIndex] = theElementIndex; for (i =0; i<nElem; i++) arr[i] = i;

Use active names for functions. int getHour(); bool isEven(int n);

Be consistent. class UserQueue { int noOfItemsInQ, frontOfTheQueue, queueCapacity; public int noOfUsersInQueue(){…} … …. } int nitems, front, capacity; public int nusers(){…} int nusers, front, capacity; public int getNuers(){…}

Be accurate. bool isOdd(int num){ return (num%2 == 0); } bool isEven(int num){ bool checkOctal(char c){ … … bool isOctal(char c){

Many naming conventions and local customs: CONSTANTS Globals pch, nodep for pointers strTo and strFrom to mean string be written to and read from npending or numPending or num_pending is a matter of taste

#define ONE 1 #define TEN 10 #define TWENTY 20 #define INPUT_MODE 1 #define INPUT_BUFSIZE 10 #define OUTPUT_BUFSIZE 20

Expressions and statements Say what you mean, simply and directly. Use the natural form for expression. Parenthesize to resolve ambiguity. Break up complex expressions. Replace repetitive expressions by calls to a common function. Be careful with side effects. Use the “telephone test” for readability.

Say what you mean, simply and directly. int v[10][10]; for (int i = 1; i<=10; i++) for (int j = 1; j<=10; j++) v[i-1][j-1] = (i/j)*(j/i);

Use natural form for expression if (!(block_id < actblks) || !(block_id >= unblocks)) if ((block_id >= actblks) || (block_id < unblocks))

Parenthesize to resolve ambiguity. *this.hour (*this).hour or *(this.hour)?

Break up complex expression *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;

Be careful with side effects scanf(“%d %d”, &yr, &profit[yr]); scanf(“%d”, &yr); scanf(“%d”, &profit[yr]);

Consistency and idioms Use a consistent indentation and brace style. Use idioms for consistency. Use else-if for multi-way decision.

Use idiom for consistency while (i <= n-1) array[i++] = 1.0; for (i=0;i<n;) for (i=n;--i>=0;) array[i] = 1.0; for (i=0;i<n;i++)

Use idiom for consistency do { c = getchar(); putchar(c); } while (c!=EOF); while ((c=getchar())!=EOF)

Use idiom for consistency int i, *iArray, nmemb; iArray = malloc(nmemb*sizeof(int)); for (i = 0; i<=nmemb; i++) iArray[i]=i; for (i = 0; i<nmemb; i++)

Use else-if for multi-way decisions if (argc == 3) if ((fin=fopen(argv[1],”r”)) !=NULL) if ((fout = fopen(argv[2],”w”)) != NULL) { while ((c = getc(fin)) !=EOF) putc(c,fout); fclose(fin); fclose(fout); } else printf(“Can’t open output file %s\n”, argv[2]); else printf(“Can’t open input file %s\n”, argv[1]); printf(“Usage: cp input file output file\n”);

Use else-if for multi-way decisions if (argc != 3) printf(“Usage: cp input file output file\n”); else if ((fin=fopen(argv[1],”r”)) ==NULL) printf(“Can’t open input file %s\n”, argv[1]); else if ((fout = fopen(argv[2],”w”)) == NULL) printf(“Can’t open output file %s\n”, argv[2]); else { while ((c = getc(fin)) !=EOF) putc(c,fout); fclose(fin); fclose(fout); }

Avoid function macros while ((a=getchar() !=EOF) && isupper(a)) #define isupper(c) ((c)>=‘A’ && (c) <=‘Z’) while (isupper(a = getchar())) while ((a=getchar() !=EOF) && isupper(a))

Parenthesize the macro body and arguments #define square(x) (x)+(x) 1/square(y) will be expanded to 1/(y)+(y) #define square(x) ((x)*(x)) 1/((y)+(y))

Magic Numbers Give names to magic numbers Use character constants, not integers Use language to calculate the size of an object

Give names to magic numbers Magic numbers are the constants, array sizes, character positions, conversion factors and other literal numeric values that appear in program int array[10][20]; const int MAXROW=10; const int MAXCOL=20; int array[MAXROW][MAXCOL];

Use character constants, not integers if (c >=65 && c <= 90) if (c >=‘A’ && c <= ‘Z’) if (isupper(c))

Use language to calculate the size of an object Use sizeof(int) instead of 2 or 4 int size; char *buf; buf = new char[n]; size = sizeof(buf)/sizeof(char); for (int i=0; i<size; i++)

Documentation The only reliable document is the code. A comment is of <=0 value if it is wrong. Make sure comments and code agree. Don’t just echo the code with comments – make every comment count. Don’t comment on bad code – rewrite it. Comment functions and global data. Don’t over-comment.

If ( (country == SING) || (country == BRNI) || (country == POL) || (country == ITALY) ) { /* * if the country is Singapore, Brunei or Poland * then the current time is the answer time * rather than the off hook time. * Reset answer time and set day of week. */

/* * default */ default: break; /* return SUCCESS */ return SUCCESS;

References The elements of programming style by Kernighan and Plauger The practice of programming by Kernighan and Pike The pragmatic programmer by Hunt and Thomas