GENERAL GUIDELINES FOR CODING RULE 1 The most

  • Slides: 20
Download presentation
GENERAL GUIDELINES FOR CODING

GENERAL GUIDELINES FOR CODING

RULE #1 • The most important aspect of the code is the readability •

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) • If your code is slow it can be profiled and optimized • If it makes inefficient use of resources, algorithms can be improved

RULE #1 • The most important aspect of the code is the readability (continued)

RULE #1 • The most important aspect of the code is the readability (continued) • If you write readable code, your coworkers will like working with you more than if you write unreadable code • If code is unreadable it will be thrown away! • “It works” is the weakest possible defense of bad coding. Poorly written code may work for the moment, but when modifications are needed it will be a liability.

COROLLARY 1. 1 : DON’T WRITE FOR EFFICIENCY • Do not write your code

COROLLARY 1. 1 : DON’T WRITE FOR EFFICIENCY • Do not write your code for “efficiency. ” If your algorithms are efficient there will be little effect from inefficiencies in the code. Efficiency must be subordinate to readability unless you can prove that it can’t be. • Most code does not have a significant affect on performance • Inner-loops generally determine performance • Most code is not resident in inner loops • Compilers don’t usually bother optimizing code outside of inner loops • Performance problems should not be fixed unless they occur • Programmers are usually bad at guessing which parts of their programs are the bottlenecks. You must diagnose performance problems with performance tools (profilers)

DON’T OPTIMIZE OUTSIDE OF INNER LOOPS • One million lines of code here •

DON’T OPTIMIZE OUTSIDE OF INNER LOOPS • One million lines of code here • For(int i=0; i<1000; i++) • For(int j=0; j<1000; j++) { <statement 1> <statement 2> <statement 3> <statement 4> } • Programs live in loops • Typically, 90+% of the CPU time is spent in a few “inner loops” • I/O Speeds are often the bottleneck • Disk reads/writes are 100, 000 to 1, 000 slower than memory reads/writes

EXAMPLES • x = x << 3; • I actually saw a programmer do

EXAMPLES • x = x << 3; • I actually saw a programmer do this with the explanation that it is more “efficient” than multiplication by 8. The code was not inside an inner loop. • I actually saw a different programmer spend most of a morning trying to figure out why this was being done • Even if the code is inside an inner loop, it is doubtful that this will make any significant difference in performance. • If x is a signed int, this code can change the sign of a positive number to a negative – a very hard bug to find • We all like to be clever, but this kind of thing is just nonsense.

BEING “CLEVER” IS NOT CLEVER • • • Three exclusive-or’s equal a swap But

BEING “CLEVER” IS NOT CLEVER • • • Three exclusive-or’s equal a swap But don’t write (the fastest) : x = x ^ y; y = x ^ y; x = x ^ y; Better is (the second fastest): temp = x; x = y; y = temp; Best is: (the third fastest): • swap(x, y); // Easy to read and already debugged

COROLLARY 1. 2 : CHOOSE IDENTIFIER NAMES CAREFULLY • The names programmers chose for

COROLLARY 1. 2 : CHOOSE IDENTIFIER NAMES CAREFULLY • The names programmers chose for variables, functions, interfaces, classes, and other identifiers has a profound impact on program readability • Take the time necessary to think of a good name for a new identifier. If you fail in your first attempt, use a refactoring tool to rename it. • The choice of good identifier names reduces the need for comments. • Make sure that your names are precise and accurate.

EXAMPLE OF BAD NAMES • Avoid the use of one letter names • a,

EXAMPLE OF BAD NAMES • Avoid the use of one letter names • a, b, c should not usually be used. • Exceptions include names of loop indices, but even then, other names can add clarity • for(int row=0; row<n. Rows; rows++) • for(int column=0; column<n. Columns; ++column) • house 1, house 2, house 3 • Never make names distinct by adding a number to the end • It will be very easy to introduce an error by writing house 2 when you mean house 3. Such errors can be very hard to find. • If numbers really do provide meaning consider using an array instead.

EXAMPLES OF BAD NAMES (CONTINUED) • fred, wilma, and barney • Never use people’s

EXAMPLES OF BAD NAMES (CONTINUED) • fred, wilma, and barney • Never use people’s names as identifiers. This is also something I have actually seen professional programmers do. They thought it was funny. It’s just bad programming. • int items. Processed = -1; • Make sure that your variable name is not inaccurate. Clearly we haven’t processed -1 items. If we are going to name this variable items. Processed then it should always contain the number of items. Processed. • A more subtle example: float weight. In. Pounds; // Read weight in kilograms cin >> weight. In. Pounds; weight. In. Pounds = weight. In. Pounds * POUNDS_PER_KILOGRAM;

EXAMPLES OF BAD VARIABLE NAMES (CONTINUED) • Make it difficult to confuse one variable

EXAMPLES OF BAD VARIABLE NAMES (CONTINUED) • Make it difficult to confuse one variable for another • Variable names should differ in more than a single letter int star; int stars[MAX_STARS]; int Star; • Variable names should “look diffrent” float divide(float op 1, float op 2) - Bad float divide(float first. Op, float second. Op) – Better Float divide(float dividend, float divisor) – Even better

EXAMPLES OF BAD VARIABLE NAMES (CONTINUED) • Avoid the use of acronyms – especially

EXAMPLES OF BAD VARIABLE NAMES (CONTINUED) • Avoid the use of acronyms – especially those that are not widely used • // What is CDS? int users. In. CDS; int campus. Data. System. NUsers; // better

FUNCTION NAMES SHOULD GIVE A CLEAR INDICATION OF WHAT THEY DO • Boolean functions

FUNCTION NAMES SHOULD GIVE A CLEAR INDICATION OF WHAT THEY DO • Boolean functions should make an assertion that can be answered with true or false // If the number is odd is false returned? bool check. Odd. Or. Even(int number) // There is no question about the returned value here bool is. Even(int number)

RULE #2: KEEP THINGS SMALL • Strive to write functions that are just a

RULE #2: KEEP THINGS SMALL • Strive to write functions that are just a few lines in length. If your functions are getting long, refactor them. • Try not to have too many methods on your classes • Keeping things small will make things easier to: • • Understand Debug Test Reuse • Use a small number of parameters in your functions • Some argue no more than two or three.

RULE #4: STRUCTURED PROGRAMS SHOULD HAVE A SINGLE EXIT POINT bool is. Odd(int num)

RULE #4: STRUCTURED PROGRAMS SHOULD HAVE A SINGLE EXIT POINT bool is. Odd(int num) { if (num % 2 == 0) return true; else return false; } bool is. Odd(int num) { return (num % 2) == 0; } • Multiple returns are really just a different implementation of the goto statement. So are “break” and “continue. ” All should be avoided.

RULE #5 : USE DEFINED CONSTANTS RATHER THAN NUMERIC LITERALS • Using name constants

RULE #5 : USE DEFINED CONSTANTS RATHER THAN NUMERIC LITERALS • Using name constants has two principal advantages • The name provides more information than a number and make the program more readable. day = LAST_DAY_IN_MARCH; // more info than day = 31; • You can change the value of the constant in one place and you change all the places the constant is used. const int DAYS_LATE_BEFORE_PENALTY = 5; // The DAYS_LATE_BEFORE_PENALTY changes to 6 we don’t // have to look through the program for all the place 5 //occurs

USE A CODING STANDARD • Many languages have de facto standards that are used

USE A CODING STANDARD • Many languages have de facto standards that are used throughout the industry • Example C++ • • • Class names start with an uppercase character Variable names start with a lowercase character Constants contain all uppercase characters Member function names start with a lowercase Data members often use a convention • Example: A data member storing a balance might be called m_balance or balance_, • Global variables might have the name of the source module appended or prepended to the name • Many languages also have formal standards that can be adopted • E. g. , http: //www. literateprogramming. com/ellemtel. pdf

STANDARDS USED IN THIS CLASS (AND FREQUENTLY ENCOUNTERED IN INDUSTRY) • Class names begin

STANDARDS USED IN THIS CLASS (AND FREQUENTLY ENCOUNTERED IN INDUSTRY) • Class names begin with uppercase letters and thereafter use lowercase letters unless a new word is introduced (Pascal case) • Examples • class Car • class Air. Conditioner • Class names should usually be nouns • Function and variable names begin with lowercase letters and user uppercase to begin new words (Camel Case). • Examples • int compute. Mean(); • int height. Of. Graph;

STANDARDS USED IN THIS CLASS (AND FREQUENTLY ENCOUNTERED IN INDUSTRY) • End data members

STANDARDS USED IN THIS CLASS (AND FREQUENTLY ENCOUNTERED IN INDUSTRY) • End data members with underscores • Example • class Car • { • private: • int n. Doors_; • float top. Speed. In. MPH_; • }

STANDARDS USED IN THIS CLASS (AND FREQUENTLY ENCOUNTERED IN INDUSTRY) • Use all uppercase

STANDARDS USED IN THIS CLASS (AND FREQUENTLY ENCOUNTERED IN INDUSTRY) • Use all uppercase for constants • Examples • const int DAYS_PER_ITERATION = 14; • const int DAYS_PER_WEEK = 7; • Prefer constants to numeric literals in all cases except • Sometimes 1, 0, and -1 • Cases where it doesn’t make any sense. • Advantages • Program is more readable • Program is more easily modified