1 / 20

General Guidelines for Coding

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

wei
Download Presentation

General Guidelines for Coding

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. General Guidelines for Coding

  2. 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

  3. 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.

  4. 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)

  5. Don’t Optimize Outside of inner loops • One million lines of code here • For(inti=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,000 slower than memory reads/writes

  6. 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.

  7. 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

  8. 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.

  9. 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<nRows;rows++) • for(int column=0;column<nColumns;++column) • house1, house2, house3 • Never make names distinct by adding a number to the end • It will be very easy to introduce an error by writing house2 when you mean house3. Such errors can be very hard to find. • If numbers really do provide meaning consider using an array instead.

  10. 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. • intitemsProcessed = -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 itemsProcessed then it should always contain the number of itemsProcessed. • A more subtle example: float weightInPounds; // Read weight in kilograms cin >> weightInPounds; weightInPounds = weightInPounds * POUNDS_PER_KILOGRAM;

  11. 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 op1, float op2) - Bad float divide(float firstOp, float secondOp) – Better Float divide(float dividend, float divisor) – Even better

  12. Examples of Bad Variable Names(continued) • Avoid the use of acronyms – especially those that are not widely used • // What is CDS? intusersInCDS; intcampusDataSystemNUsers; // better

  13. 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? boolcheckOddOrEven(int number) // There is no question about the returned value here boolisEven(int number)

  14. 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.

  15. Rule #4: Structured Programs should have a single exit point boolisOdd(intnum) { if (num % 2 == 0) return true; else return false; } boolisOdd(intnum) { 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.

  16. 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. constint 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

  17. 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

  18. 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 AirConditioner • Class names should usually be nouns • Function and variable names begin with lowercase letters and user uppercase to begin new words (Camel Case). • Examples • intcomputeMean(); • intheightOfGraph;

  19. Standards Used in this Class (and frequently Encountered In Industry) • End data members with underscores • Example • class Car • { • private: • intnDoors_; • float topSpeedInMPH_; • }

  20. Standards Used in this Class (and frequently Encountered In Industry) • Use all uppercase for constants • Examples • constint DAYS_PER_ITERATION = 14; • constint 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

More Related