Essay Samples

HOME F.A.Q. REGISTER LOGIN SEARCH  
Essay Topics
Acceptance
Art
Business
Custom Written
Direct Essays
English
Example Essays
Foreign
History
Medical
Mega Essays
Miscellaneous
Movies
Music
Novels
People
Politics
Pre-Written
Religion
Science
Search
Speeches
Sports
Technology
Over 101,000 Essays and Term Papers!!
This is only a preview of the paper
Click here to register and get the full text.
Existing members click here to login

blabla

C++ Code Conventions (a recommendation) 1 - Introduction 1.1 Why Have Code Conventions Code conventions are important to programmers for a number of reasons: · 80% of the lifetime cost of a piece of software goes to maintenance. · Hardly any software is maintained for its whole life by the original author. · Code conventions improve the readability of the software, allowing engineers to understand new code more quickly and thoroughly. · If you ship your source code as a product, you need to make sure it is as well packaged and clean as any other product you create. For the conventions to work, every person writing software must conform to the code conventions. Everyone. 2 - Source Code Organization The name of files can be more than eight characters, with a mix of upper case and lower-case. The name of files should reflect the content of the file as clearly as possible. As a rule of thumb, files containing class definitions and implementations should contain only one class. The name of the file should be the same as the name of the class. Files can contain more than one class when inner classes are used. The definition and implementation of classes should adhere to the basic rule of decoupling interface from implementation. This means that classes should be defined in header file (.h), and implemented in source files (.cpp). 2.1 C++ Header Files Each C++ file contains a single class definition. 2.1.1 Beginning Comments Source (.h, .cpp) files should begin with a c-style comment that lists information related to the file - the class name, author, version, date, copyright notice, etc. Note: for the purpose of the course the class and author names is sufficient. /* * Classname * * Author (name and id) */ 3 - Indentation Four spaces should be used as the unit of indentation. The exact construction of the indentation (spaces vs. tabs) is unspecified. 3.1 Line Length Avoid lines longer than 80 characters, since they’re not handled well by many terminals and tools. 3.2 Wrapping Lines When an expression will not fit on a single line, break it according to these general principles: · Break after a comma. · Break before an operator. · Prefer higher-level breaks to lower-level breaks. · Align the new line with the beginning of the expression at the same level on the previous line. · If the above rules lead to confusing code or to code that’s squished up against the right margin, just indent 8 spaces instead. Here are some examples of breaking method calls: someMethod(longExpression1, longExpression2, longExpression3, longExpression4, longExpression5); var = someMethod1(longExpression1, someMethod2(longExpression2, longExpression3)); Following are two examples of breaking an arithmetic expression. The first is preferred, since the break occurs outside the parenthesized expression, which is at a higher level. longName1 = longName2 * (longName3 + longName4 - longName5) + 4 * longname6; // PREFER longName1 = longName2 * (longName3 + longName4 - longName5) + 4 * longname6; // AVOID Following are two examples of indenting method declarations. The first is the conventional case. The second would shift the second and third lines to the far right if it used conventional indentation, so instead it indents only 8 spaces. //CONVENTIONAL INDENTATION someMethod(int anArg, Object anotherArg, String yetAnotherArg, Object andStillAnother) { ... } //INDENT 8 SPACES TO AVOID VERY DEEP INDENTS int horkingLongMethodName(int anArg, Object anotherArg, String yetAnotherArg, Object andStillAnother) { ... } Line wrapping for if statements should generally use the 8-space rule, since conventional (4 space) indentation makes seeing the body difficult. For example: //DON’T USE THIS INDENTATION if ((condition1 && condition2) || (condition3 && condition4) ||!(condition5 && condition6)) { //BAD WRAPS doSomethingAboutIt(); //MAKE THIS LINE EASY TO MISS } //USE THIS INDENTATION INSTEAD if ((condition1 && condition2) || (condition3 && condition4) ||!(condition5 && condition6)) { doSomethingAboutIt(); } //OR USE THIS if ((condition1 && condition2) || (condition3 && condition4) ||!(condition5 && condition6)) { doSomethingAboutIt(); } Here are three acceptable ways to format ternary expressions: alpha = (aLongBooleanExpression) ? beta : gamma; alpha = (aLongBooleanExpression) ? beta : gamma; alpha = (aLongBooleanExpression) ? beta : gamma; 4 - Comments Comments should be used to give overviews of code and provide additional information that is not readily available in the code itself. Comments should contain only information that is relevant to reading and understanding the program. Discussion of nontrivial or nonobvious design decisions is appropriate, but avoid duplicating information that is present in (and clear from) the code. It is too easy for redundant comments to get out of date. In general, avoid any comments that are likely to get out of date as the code evolves. Note: The frequency of comments sometimes reflects poor quality of code. When you feel compelled to add a comment, consider rewriting the code to make it clearer. Comments should not be enclosed in large boxes drawn with asterisks or other characters. Comments should never include special characters such as form-feed and backspace. 4.1 Implementation Comment Formats Programs can have four styles of implementation comments: block, single-line, trailing and end-of-line. 4.1.1 Block Comments Block comments are used to provide descriptions of files, methods, data structures and algorithms. Block comments may be used at the beginning of each file and before each method. They can also be used in other places, such as within methods. Block comments inside a function or method should be indented to the same level as the code they describe. A block comment should be preceded by a blank line to set it apart from the rest of the code. /* * Here is a block comment. */ See also “Documentation Comments” on page 8. 4.1.2 Single-Line Comments Short comments can appear on a single line indented to the level of the code that follows. If a comment can’t be written in a single line, it should follow the block comment format (see section 5.1.1). A single-line comment should be preceded by a blank line. Here’s an example of a single-line comment in C++ code: if (condition) { /* Handle the condition. */ ... } 4.1.3 Trailing Comments Very short comments can appear on the same line as the code they describe, but should be shifted far enough to separate them from the statements. If more than one short comment appears in a chunk of code, they should all be indented to the same tab setting. Here’s an example of a trailing comment in C++ code: if (a == 2) { return TRUE; /* special case */ } else { return isPrime(a); /* works only for odd a */ } 4.1.4 End-Of-Line Comments The // comment delimiter can comment out a complete line or only a partial line. It shouldn’t be used on consecutive multiple lines for text comments; however, it can be used in consecutive multiple lines for commenting out sections of code. Examples of all three styles follow: if (foo > 1) { // Do a double-flip. ... } else { return false; // Explain why here. } //if (bar > 1) { // // // Do a triple-flip. // ... //} //else { // return false; //} 5 - Declarations 5.1 Number Per Line One declaration per line is recommended since it encourages commenting. In other words, int level; // indentation level int size; // size of table is preferred over int level, size; Do not put different types on the same line. Example: int foo, *fooarray; //WRONG! Note: The examples above use one space between the type and the identifier. Another acceptable alternative is to use tabs, e.g.: int level; // indentation level int size; // size of table Object currentEntry; // currently selected table entry 5.2 Initialization Try to initialize local variables where they’re declared. The only reason not to initialize a variable where it’s declared is if the initial value depends on some computation occurring first. 5.3 Placement Put declarations only at the beginning of blocks. (A block is any code surrounded by curly braces “{” and “}”.) Don’t wait to declare variables until their first use; it can confuse the unwary programmer and hamper code portability within the scope. void myMethod() { int int1 = 0; // beginning of method block if (condition) { int int2 = 0; // beginning of "if" block ... } } The one exception to the rule is indexes of for loops, which in C++ can be declared in the for statement: for (int i = 0; i < maxLoops; i++) { ... } 5.4 Class Declarations The public, protected, and private sections of a class are to be declared in that order (the public section is declared before the protected section which is declared before the private section). By placing the public section first, everything that is of interest to a user is gathered in the beginning of the class definition. The protected section may be of interest to designers when considering inheriting from the class. The private section contains details that should have the least general interest. For example : class String { public: String(); // Default constructor String( const String& s ); // Copy constructor unsigned size() const; // ... protected: int checkIndex( unsigned index ) const; // ... private: unsigned noOfChars; // ... }; 6 - Statements 6.1 Simple Statements Each line should contain at most one statement. Example: argv++; // Correct argc++; // Correct argv++; argc--; // AVOID! 6.2 Compound Statements Compound statements are statements that contain lists of statements enclosed in braces “{ statements }”. See the following sections for examples. · The enclosed statements should be indented one more level than the compound statement. · The opening brace should be at the end of the line that begins the compound statement; the closing brace should begin a line and be indented to the beginning of the compound statement. · Braces are used around all statements, even single statements, when they are part of a control structure, such as a if-else or for statement. This makes it easier to add statements without accidentally introducing bugs due to forgetting to add braces. 6.3 return Statements A return statement with a value should not use parentheses unless they make the return value more obvious in some way. Example: return; return myDisk.size(); return (size ? size : defaultSize); 6.4 if, if-else, if else-if else Statements The if-else class of statements should have the following form: if ( condition) { statements; } if ( condition) { statements; } else { statements; } if ( condition) { statements; } else if ( condition) { statements; } else { statements; } Note: if statements always use braces {}. Avoid the following error-prone form: if ( condition) //AVOID! THIS OMITS THE BRACES {}! statement; 6.5 for Statements A for statement should have the following form: for ( initialization; condition; update) { statements; } An empty for statement (one in which all the work is done in the initialization, condition, and update clauses) should have the following form: for ( initialization; condition; update); When using the comma operator in the initialization or update clause of a for statement, avoid the complexity of using more than three variables. If needed, use separate statements before the for loop (for the initialization clause) or at the end of the loop (for the update clause). 6.6 while Statements A while statement should have the following form: while ( condition) { statements; } An empty while statement should have the following form: while ( condition); 6.7 do-while Statements A do-while statement should have the following form: do { statements; } while ( condition); 6.8 switch Statements A switch statement should have the following form: switch ( condition) { case ABC: statements; /* falls through */ case DEF: statements; break; case XYZ: statements; break; default: statements; break; } Every time a case falls through (doesn’t include a break statement), add a comment where the break statement would normally be. This is shown in the preceding code example with the /* falls through */ comment. Every switch statement should include a default case. The break in the default case is redundant, but it prevents a fall-through error if later another case is added. 6.9 try-catch Statements A try-catch statement should have the following format: try { statements; } catch (ExceptionClass e) { statements; } 7 - White Space 7.1 Blank Lines Blank lines improve readability by setting off sections of code that are logically related. Two blank lines should always be used in the following circumstances: · Between sections of a source file One blank line should always be used in the following circumstances: · Between methods · Between the local variables in a method and its first statement · Before a block (see section 5.1.1) or single-line (see section 5.1.2) comment · Between logical sections inside a method to improve readability 7.2 Blank Spaces Blank spaces should be used in the following circumstances: · A keyword followed by a parenthesis should be separated by a space. Example: while (true) { ... } Note that a blank space should not be used between a method name and its opening parenthesis. This helps to distinguish keywords from method calls. · A blank space should appear after commas in argument lists. · All binary operators except . and -> should be separated from their operands by spaces. Blank spaces should never separate unary operators such as unary minus, increment (“++”), and decrement (“--”) from their operands. Example: a += c + d; a = (a + b) / (c * d); while (d++ = s++) { n++; } prints("size is " + foo + " "); · The expressions in a for statement should be separated by blank spaces. Example: for (expr1; expr2; expr3) 8 - Naming Conventions Naming conventions make programs more understandable by making them easier to read. They can also give information about the function of the identifier—for example, whether it’s a constant, method, or class—which can be helpful in understanding the code. Identifier Type Rules For Naming Examples Classes Class names should be nouns, in mixed casewith the first letter of each internal word capi-talized. Try to keep your class names simpleand descriptive. Use whole words—avoidacronyms and abbreviations (unless theabbre-viation is much more widely used than the long form, such as URL or HTML). class Raster;class ImageSprite; Functions Functions should be verbs, in mixed case withthe first letter lowercase, with the first letter ofeach internal word capitalized. run();runFast();getBackground(); Variables Variables are in mixed case with a lowercasefirst letter. Internal words start with capitalletters. Variable names should not start withunderscore _ or dollar sign $ characters, eventhough both are allowed.Variable names should be short yet meaning-ful. The choice of a variable name should bemnemonic— that is, designed to indicate to thecasual observer the intent of its use. One-character variable names should be avoided except for temporary “throwaway” variables. Common names for temporary variables are i, j, k, m, and n for integers; c, d, and e for characters int i;char c;float myWidth; Constants The names of variables declared constantsshould be all uppercase with words separated by underscores(“_”). const int MIN_WIDTH = 4;const int MAX_WIDTH = 999;const int GET_THE_CPU = 1; 9 - Programming Practices 9.1 Providing Access to Instance and Class Variables Don’t make any instance or class variable public without good reason (there isn’t one). Often, instance variables don’t need to be explicitly set or gotten—often that happens as a side effect of method calls. The use of protected variables in a class is, also, not recommended, since its variables become visible to its derived classes. If you need to give access to private variables use getter/setters functions. Example: If the private section of a class contains a variable of type int named balance use int getBalance() const; void setBalance(int newBalance); 9.2 Referring to Class (static) Variables and Methods Avoid using an object to access a static variable or method. Use a class name instead. For example: classMethod(); //OK AClass.classMethod(); //OK anObject.classMethod(); //AVOID! 9.3 Constants Numerical constants (literals) should not be coded directly, except for -1, 0, and 1, which can appear in a for loop as counter values. 9.4 Variable Assignments Avoid assigning several variables to the same value in a single statement. It is hard to read. Example: fooBar.fChar = barFoo.lchar = 'c'; // AVOID! Do not use the assignment operator in a place where it can be easily confused with the equality operator. Example: if (c++ = d++) { // AVOID! ... } should be written as if ((c++ = d++) != 0) { ... } Do not use embedded assignments in an attempt to improve run-time performance. This is the job of the compiler. Example: d = (a = b + c) + r; // AVOID! should be written as a = b + c; d = a + r; 9.5 Miscellaneous Practices 9.5.1 Parentheses It is generally a good idea to use parentheses liberally in expressions involving mixed operators to avoid operator precedence problems. Even if the operator precedence seems clear to you, it might not be to others—you shouldn’t assume that other programmers know precedence as well as you do. if (a == b && c == d) // AVOID! if ((a == b) && (c == d)) // USE. 9.5.2 Returning Values Try to make the structure of your program match the intent. Example: if ( booleanExpression) { return true; } else { return false; } should instead be written as return booleanExpression; Similarly, if (condition) { return x; } return y; should be written as return (condition ? x : y); 9.5.3 Expressions before ‘?’ in the Conditional Operator If an expression containing a binary operator appears before the ? in the ternary ?: operator, it should be parenthesized. Example: (x >= 0) ? x : -x; 9.5.4 Special Comments Use XXX in a comment to flag something that is bogus but works. Use FIXME to flag something that is bogus and broken. C++ Code Conventions (a recommendation) 1 - Introduction 1.1 Why Have Code Conventions Code conventions are important to programmers for a number of reasons: · 80% of the lifetime cost of a piece of software goes to maintenance. · Hardly any software is maintained for its whole life by the original author. · Code conventions improve the readability of the software, allowing engineers to understand new code more quickly and thoroughly. · If you ship your source code as a product, you need to make sure it is as well packaged and clean as any other product you create. For the conventions to work, every person writing software must conform to the code conventions. Everyone. 2 - Source Code Organization The name of files can be more than eight characters, with a mix of upper case and lower-case. The name of files should reflect the content of the file as clearly as possible. As a rule of thumb, files containing class definitions and implementations should contain only one class. The name of the file should be the same as the name of the class. Files can contain more than one class when inner classes are used. The definition and implementation of classes should adhere to the basic rule of decoupling interface from implementation. This means that classes should be defined in header file (.h), and implemented in source files (.cpp). 2.1 C++ Header Files Each C++ file contains a single class definition. 2.1.1 Beginning Comments Source (.h, .cpp) files should begin with a c-style comment that lists information related to the file - the class name, author, version, date, copyright notice, etc. Note: for the purpose of the course the class and author names is sufficient. /* * Classname * * Author (name and id) */ 3 - Indentation Four spaces should be used as the unit of indentation. The exact construction of the indentation (spaces vs. tabs) is unspecified. 3.1 Line Length Avoid lines longer than 80 characters, since they’re not handled well by many terminals and tools. 3.2 Wrapping Lines When an expression will not fit on a single line, break it according to these general principles: · Break after a comma. · Break before an operator. · Prefer higher-level breaks to lower-level breaks. · Align the new line with the beginning of the expression at the same level on the previous line. · If the above rules lead to confusing code or to code that’s squished up against the right margin, just indent 8 spaces instead. Here are some examples of breaking method calls: someMethod(longExpression1, longExpression2, longExpression3, longExpression4, longExpression5); var = someMethod1(longExpression1, someMethod2(longExpression2, longExpression3)); Following are two examples of breaking an arithmetic expression. The first is preferred, since the break occurs outside the parenthesized expression, which is at a higher level. longName1 = longName2 * (longName3 + longName4 - longName5) + 4 * longname6; // PREFER longName1 = longName2 * (longName3 + longName4 - longName5) + 4 * longname6; // AVOID Following are two examples of indenting method declarations. The first is the conventional case. The second would shift the second and third lines to the far right if it used conventional indentation, so instead it indents only 8 spaces. //CONVENTIONAL INDENTATION someMethod(int anArg, Object anotherArg, String yetAnotherArg, Object andStillAnother) { ... } //INDENT 8 SPACES TO AVOID VERY DEEP INDENTS int horkingLongMethodName(int anArg, Object anotherArg, String yetAnotherArg, Object andStillAnother) { ... } Line wrapping for if statements should generally use the 8-space rule, since conventional (4 space) indentation makes seeing the body difficult. For example: //DON’T USE THIS INDENTATION if ((condition1 && condition2) || (condition3 && condition4) ||!(condition5 && condition6)) { //BAD WRAPS doSomethingAboutIt(); //MAKE THIS LINE EASY TO MISS } //USE THIS INDENTATION INSTEAD if ((condition1 && condition2) || (condition3 && condition4) ||!(condition5 && condition6)) { doSomethingAboutIt(); } //OR USE THIS if ((condition1 && condition2) || (condition3 && condition4) ||!(condition5 && condition6)) { doSomethingAboutIt(); } Here are three acceptable ways to format ternary expressions: alpha = (aLongBooleanExpression) ? beta : gamma; alpha = (aLongBooleanExpression) ? beta : gamma; alpha = (aLongBooleanExpression) ? beta : gamma; 4 - Comments Comments should be used to give overviews of code and provide additional information that is not readily available in the code itself. Comments should contain only information that is relevant to reading and understanding the program. Discussion of nontrivial or nonobvious design decisions is appropriate, but avoid duplicating information that is present in (and clear from) the code. It is too easy for redundant comments to get out of date. In general, avoid any comments that are likely to get out of date as the code evolves. Note: The frequency of comments sometimes reflects poor quality of code. When you feel compelled to add a comment, consider rewriting the code to make it clearer. Comments should not be enclosed in large boxes drawn with asterisks or other characters. Comments should never include special characters such as form-feed and backspace. 4.1 Implementation Comment Formats Programs can have four styles of implementation comments: block, single-line, trailing and end-of-line. 4.1.1 Block Comments Block comments are used to provide descriptions of files, methods, data structures and algorithms. Block comments may be used at the beginning of each file and before each method. They can also be used in other places, such as within methods. Block comments inside a function or method should be indented to the same level as the code they describe. A block comment should be preceded by a blank line to set it apart from the rest of the code. /* * Here is a block comment. */ See also “Documentation Comments” on page 8. 4.1.2 Single-Line Comments Short comments can appear on a single line indented to the level of the code that follows. If a comment can’t be written in a single line, it should follow the block comment format (see section 5.1.1). A single-line comment should be preceded by a blank line. Here’s an example of a single-line comment in C++ code: if (condition) { /* Handle the condition. */ ... } 4.1.3 Trailing Comments Very short comments can appear on the same line as the code they describe, but should be shifted far enough to separate them from the statements. If more than one short comment appears in a chunk of code, they should all be indented to the same tab setting. Here’s an example of a trailing comment in C++ code: if (a == 2) { return TRUE; /* special case */ } else { return isPrime(a); /* works only for odd a */ } 4.1.4 End-Of-Line Comments The // comment delimiter can comment out a complete line or only a partial line. It shouldn’t be used on consecutive multiple lines for text comments; however, it can be used in consecutive multiple lines for commenting out sections of code. Examples of all three styles follow: if (foo > 1) { // Do a double-flip. ... } else { return false; // Explain why here. } //if (bar > 1) { // // // Do a triple-flip. // ... //} //else { // return false; //} 5 - Declarations 5.1 Number Per Line One declaration per line is recommended since it encourages commenting. In other words, int level; // indentation level int size; // size of table is preferred over int level, size; Do not put different types on the same line. Example: int foo, *fooarray; //WRONG! Note: The examples above use one space between the type and the identifier. Another acceptable alternative is to use tabs, e.g.: int level; // indentation level int size; // size of table Object currentEntry; // currently selected table entry 5.2 Initialization Try to initialize local variables where they’re declared. The only reason not to initialize a variable where it’s declared is if the initial value depends on some computation occurring first. 5.3 Placement Put declarations only at the beginning of blocks. (A block is any code surrounded by curly braces “{” and “}”.) Don’t wait to declare variables until their first use; it can confuse the unwary programmer and hamper code portability within the scope. void myMethod() { int int1 = 0; // beginning of method block if (condition) { int int2 = 0; // beginning of "if" block ... } } The one exception to the rule is indexes of for loops, which in C++ can be declared in the for statement: for (int i = 0; i < maxLoops; i++) { ... } 5.4 Class Declarations The public, protected, and private sections of a class are to be declared in that order (the public section is declared before the protected section which is declared before the private section). By placing the public section first, everything that is of interest to a user is gathered in the beginning of the class definition. The protected section may be of interest to designers when considering inheriting from the class. The private section contains details that should have the least general interest. For example : class String { public: String(); // Default constructor String( const String& s ); // Copy constructor unsigned size() const; // ... protected: int checkIndex( unsigned index ) const; // ... private: unsigned noOfChars; // ... }; 6 - Statements 6.1 Simple Statements Each line should contain at most one statement. Example: argv++; // Correct argc++; // Correct argv++; argc--; // AVOID! 6.2 Compound Statements Compound statements are statements that contain lists of statements enclosed in braces “{ statements }”. See the following sections for examples. · The enclosed statements should be indented one more level than the compound statement. · The opening brace should be at the end of the line that begins the compound statement; the closing brace should begin a line and be indented to the beginning of the compound statement. · Braces are used around all statements, even single statements, when they are part of a control structure, such as a if-else or for statement. This makes it easier to add statements without accidentally introducing bugs due to forgetting to add braces. 6.3 return Statements A return statement with a value should not use parentheses unless they make the return value more obvious in some way. Example: return; return myDisk.size(); return (size ? size : defaultSize); 6.4 if, if-else, if else-if else Statements The if-else class of statements should have the following form: if ( condition) { statements; } if ( condition) { statements; } else { statements; } if ( condition) { statements; } else if ( condition) { statements; } else { statements; } Note: if statements always use braces {}. Avoid the following error-prone form: if ( condition) //AVOID! THIS OMITS THE BRACES {}! statement; 6.5 for Statements A for statement should have the following form: for ( initialization; condition; update) { statements; } An empty for statement (one in which all the work is done in the initialization, condition, and update clauses) should have the following form: for ( initialization; condition; update); When using the comma operator in the initialization or update clause of a for statement, avoid the complexity of using more than three variables. If needed, use separate statements before the for loop (for the initialization clause) or at the end of the loop (for the update clause). 6.6 while Statements A while statement should have the following form: while ( condition) { statements; } An empty while statement should have the following form: while ( condition); 6.7 do-while Statements A do-while statement should have the following form: do { statements; } while ( condition); 6.8 switch Statements A switch statement should have the following form: switch ( condition) { case ABC: statements; /* falls through */ case DEF: statements; break; case XYZ: statements; break; default: statements; break; } Every time a case falls through (doesn’t include a break statement), add a comment where the break statement would normally be. This is shown in the preceding code example with the /* falls through */ comment. Every switch statement should include a default case. The break in the default case is redundant, but it prevents a fall-through error if later another case is added. 6.9 try-catch Statements A try-catch statement should have the following format: try { statements; } catch (ExceptionClass e) { statements; } 7 - White Space 7.1 Blank Lines Blank lines improve readability by setting off sections of code that are logically related. Two blank lines should always be used in the following circumstances: · Between sections of a source file One blank line should always be used in the following circumstances: · Between methods · Between the local variables in a method and its first statement · Before a block (see section 5.1.1) or single-line (see section 5.1.2) comment · Between logical sections inside a method to improve readability 7.2 Blank Spaces Blank spaces should be used in the following circumstances: · A keyword followed by a parenthesis should be separated by a space. Example: while (true) { ... } Note that a blank space should not be used between a method name and its opening parenthesis. This helps to distinguish keywords from method calls. · A blank space should appear after commas in argument lists. · All binary operators except . and -> should be separated from their operands by spaces. Blank spaces should never separate unary operators such as unary minus, increment (“++”), and decrement (“--”) from their operands. Example: a += c + d; a = (a + b) / (c * d); while (d++ = s++) { n++; } prints("size is " + foo + " "); · The expressions in a for statement should be separated by blank spaces. Example: for (expr1; expr2; expr3) 8 - Naming Conventions Naming conventions make programs more understandable by making them easier to read. They can also give information about the function of the identifier—for example, whether it’s a constant, method, or class—which can be helpful in understanding the code. Identifier Type Rules For Naming Examples Classes Class names should be nouns, in mixed casewith the first letter of each internal word capi-talized. Try to keep your class names simpleand descriptive. Use whole words—avoidacronyms and abbreviations (unless theabbre-viation is much more widely used than the long form, such as URL or HTML). class Raster;class ImageSprite; Functions Functions should be verbs, in mixed case withthe first letter lowercase, with the first letter ofeach internal word capitalized. run();runFast();getBackground(); Variables Variables are in mixed case with a lowercasefirst letter. Internal words start with capitalletters. Variable names should not start withunderscore _ or dollar sign $ characters, eventhough both are allowed.Variable names should be short yet meaning-ful. The choice of a variable name should bemnemonic— that is, designed to indicate to thecasual observer the intent of its use. One-character variable names should be avoided except for temporary “throwaway” variables. Common names for temporary variables are i, j, k, m, and n for integers; c, d, and e for characters int i;char c;float myWidth; Constants The names of variables declared constantsshould be all uppercase with words separated by underscores(“_”). const int MIN_WIDTH = 4;const int MAX_WIDTH = 999;const int GET_THE_CPU = 1; 9 - Programming Practices 9.1 Providing Access to Instance and Class Variables Don’t make any instance or class variable public without good reason (there isn’t one). Often, instance variables don’t need to be explicitly set or gotten—often that happens as a side effect of method calls. The use of protected variables in a class is, also, not recommended, since its variables become visible to its derived classes. If you need to give access to private variables use getter/setters functions. Example: If the private section of a class contains a variable of type int named balance use int getBalance() const; void setBalance(int newBalance); 9.2 Referring to Class (static) Variables and Methods Avoid using an object to access a static variable or method. Use a class name instead. For example: classMethod(); //OK AClass.classMethod(); //OK anObject.classMethod(); //AVOID! 9.3 Constants Numerical constants (literals) should not be coded directly, except for -1, 0, and 1, which can appear in a for loop as counter values. 9.4 Variable Assignments Avoid assigning several variables to the same value in a single statement. It is hard to read. Example: fooBar.fChar = barFoo.lchar = 'c'; // AVOID! Do not use the assignment operator in a place where it can be easily confused with the equality operator. Example: if (c++ = d++) { // AVOID! ... } should be written as if ((c++ = d++) != 0) { ... } Do not use embedded assignments in an attempt to improve run-time performance. This is the job of the compiler. Example: d = (a = b + c) + r; // AVOID! should be written as a = b + c; d = a + r; 9.5 Miscellaneous Practices 9.5.1 Parentheses It is generally a good idea to use parentheses liberally in expressions involving mixed operators to avoid operator precedence problems. Even if the operator precedence seems clear to you, it might not be to others—you shouldn’t assume that other programmers know precedence as well as you do. if (a == b && c == d) // AVOID! if ((a == b) && (c == d)) // USE. 9.5.2 Returning Values Try to make the structure of your program match the intent. Example: if ( booleanExpression) { return true; } else { return false; } should instead be written as return booleanExpression; Similarly, if (condition) { return x; } return y; should be written as return (condition ? x : y); 9.5.3 Expressions before ‘?’ in the Conditional Operator If an expression containing a binary operator appears before the ? in the ternary ?: operator, it should be parenthesized. Example: (x >= 0) ? x : -x; 9.5.4 Special Comments Use XXX in a comment to flag something that is bogus but works. Use FIXME to flag something that is bogus and broken. C++ Code Conventions (a recommendation) 1 - Introduction 1.1 Why Have Code Conventions Code conventions are important to programmers for a number of reasons: · 80% of the lifetime cost of a piece of software goes to maintenance. · Hardly any software is maintained for its whole life by the original author. · Code conventions improve the readability of the software, allowing engineers to understand new code more quickly and thoroughly. · If you ship your source code as a product, you need to make sure it is as well packaged and clean as any other product you create. For the conventions to work, every person writing software must conform to the code conventions. Everyone. 2 - Source Code Organization The name of files can be more than eight characters, with a mix of upper case and lower-case. The name of files should reflect the content of the file as clearly as possible. As a rule of thumb, files containing class definitions and implementations should contain only one class. The name of the file should be the same as the name of the class. Files can contain more than one class when inner classes are used. The definition and implementation of classes should adhere to the basic rule of decoupling interface from implementation. This means that classes should be defined in header file (.h), and implemented in source files (.cpp). 2.1 C++ Header Files Each C++ file contains a single class definition. 2.1.1 Beginning Comments Source (.h, .cpp) files should begin with a c-style comment that lists information related to the file - the class name, author, version, date, copyright notice, etc. Note: for the purpose of the course the class and author names is sufficient. /* * Classname * * Author (name and id) */ 3 - Indentation Four spaces should be used as the unit of indentation. The exact construction of the indentation (spaces vs. tabs) is unspecified. 3.1 Line Length Avoid lines longer than 80 characters, since they’re not handled well by many terminals and tools. 3.2 Wrapping Lines When an expression will not fit on a single line, break it according to these general principles: · Break after a comma. · Break before an operator. · Prefer higher-level breaks to lower-level breaks. · Align the new line with the beginning of the expression at the same level on the previous line. · If the above rules lead to confusing code or to code that’s squished up against the right margin, just indent 8 spaces instead. Here are some examples of breaking method calls: someMethod(longExpression1, longExpression2, longExpression3, longExpression4, longExpression5); var = someMethod1(longExpression1, someMethod2(longExpression2, longExpression3)); Following are two examples of breaking an arithmetic expression. The first is preferred, since the break occurs outside the parenthesized expression, which is at a higher level. longName1 = longName2 * (longName3 + longName4 - longName5) + 4 * longname6; // PREFER longName1 = longName2 * (longName3 + longName4 - longName5) + 4 * longname6; // AVOID Following are two examples of indenting method declarations. The first is the conventional case. The second would shift the second and third lines to the far right if it used conventional indentation, so instead it indents only 8 spaces. //CONVENTIONAL INDENTATION someMethod(int anArg, Object anotherArg, String yetAnotherArg, Object andStillAnother) { ... } //INDENT 8 SPACES TO AVOID VERY DEEP INDENTS int horkingLongMethodName(int anArg, Object anotherArg, String yetAnotherArg, Object andStillAnother) { ... } Line wrapping for if statements should generally use the 8-space rule, since conventional (4 space) indentation makes seeing the body difficult. For example: //DON’T USE THIS INDENTATION if ((condition1 && condition2) || (condition3 && condition4) ||!(condition5 && condition6)) { //BAD WRAPS doSomethingAboutIt(); //MAKE THIS LINE EASY TO MISS } //USE THIS INDENTATION INSTEAD if ((condition1 && condition2) || (condition3 && condition4) ||!(condition5 && condition6)) { doSomethingAboutIt(); } //OR USE THIS if ((condition1 && condition2) || (condition3 && condition4) ||!(condition5 && condition6)) { doSomethingAboutIt(); } Here are three acceptable ways to format ternary expressions: alpha = (aLongBooleanExpression) ? beta : gamma; alpha = (aLongBooleanExpression) ? beta : gamma; alpha = (aLongBooleanExpression) ? beta : gamma; 4 - Comments Comments should be used to give overviews of code and provide additional information that is not readily available in the code itself. Comments should contain only information that is relevant to reading and understanding the program. Discussion of nontrivial or nonobvious design decisions is appropriate, but avoid duplicating information that is present in (and clear from) the code. It is too easy for redundant comments to get out of date. In general, avoid any comments that are likely to get out of date as the code evolves. Note: The frequency of comments sometimes reflects poor quality of code. When you feel compelled to add a comment, consider rewriting the code to make it clearer. Comments should not be enclosed in large boxes drawn with asterisks or other characters. Comments should never include special characters such as form-feed and backspace. 4.1 Implementation Comment Formats Programs can have four styles of implementation comments: block, single-line, trailing and end-of-line. 4.1.1 Block Comments Block comments are used to provide descriptions of files, methods, data structures and algorithms. Block comments may be used at the beginning of each file and before each method. They can also be used in other places, such as within methods. Block comments inside a function or method should be indented to the same level as the code they describe. A block comment should be preceded by a blank line to set it apart from the rest of the code. /* * Here is a block comment. */ See also “Documentation Comments” on page 8. 4.1.2 Single-Line Comments Short comments can appear on a single line indented to the level of the code that follows. If a comment can’t be written in a single line, it should follow the block comment format (see section 5.1.1). A single-line comment should be preceded by a blank line. Here’s an example of a single-line comment in C++ code: if (condition) { /* Handle the condition. */ ... } 4.1.3 Trailing Comments Very short comments can appear on the same line as the code they describe, but should be shifted far enough to separate them from the statements. If more than one short comment appears in a chunk of code, they should all be indented to the same tab setting. Here’s an example of a trailing comment in C++ code: if (a == 2) { return TRUE; /* special case */ } else { return isPrime(a); /* works only for odd a */ } 4.1.4 End-Of-Line Comments The // comment delimiter can comment out a complete line or only a partial line. It shouldn’t be used on consecutive multiple lines for text comments; however, it can be used in consecutive multiple lines for commenting out sections of code. Examples of all three styles follow: if (foo > 1) { // Do a double-flip. ... } else { return false; // Explain why here. } //if (bar > 1) { // // // Do a triple-flip. // ... //} //else { // return false; //} 5 - Declarations 5.1 Number Per Line One declaration per line is recommended since it encourages commenting. In other words, int level; // indentation level int size; // size of table is preferred over int level, size; Do not put different types on the same line. Example: int foo, *fooarray; //WRONG! Note: The examples above use one space between the type and the identifier. Another acceptable alternative is to use tabs, e.g.: int level; // indentation level int size; // size of table Object currentEntry; // currently selected table entry 5.2 Initialization Try to initialize local variables where they’re declared. The only reason not to initialize a variable where it’s declared is if the initial value depends on some computation occurring first. 5.3 Placement Put declarations only at the beginning of blocks. (A block is any code surrounded by curly braces “{” and “}”.) Don’t wait to declare variables until their first use; it can confuse the unwary programmer and hamper code portability within the scope.


Approximate Word count = 29183
Approximate Pages = 116.7
(250 words per page double spaced)
Over 101,000 Essays and Term Papers!!
Links
How to Blabla bla

Mercer Study blabla

blabla

blabla

blabla

blabla

Support
F.A.Q.
Custom Essays
Payment
Essay Samples
Forgot Password?
Activation Email
More Links
All Papers Are For Research And Reference Purposes Only! You may not turn these papers in as your own! You must cite our web site as your source!
Copyright 2003-2008 essaysamples.net. All rights reserved.