Sunteți pe pagina 1din 77

Copyright

2016 by Louis Newstrom


All rights reserved. This book or any portion thereof may not be reproduced or used in any
manner whatsoever without the express written permission of the author except for the use
of brief quotations in a book review.

The Instant Management Series


Imagine if there was an company that was, well, really organized. They would have
written procedures for tasks. They would have warnings about problems and how to avoid
them. They would have checklists so nothing was forgotten. They would know when each
task would be done, and what resources it would use.
Dont you wish that you were that organized? You can be. You are holding in your
hands, a set of procedures. What if you simply decided that these were your procedures?
You are now that organized. Is really is that easy.

Table of Contents
What Coding Styles Are
Why Have Coding Style Guideline
Block Styles
C++ Styles
Class Styles
Comment Styles
Function Styles
Header Styles
Layout Styles
Name Styles
Variable Styles
Appendix - check list of styles to look for

What Coding Styles Are


A coding style is a coding decision that does not affect the functionality of the
program. This is contrasted with good practice, which is a coding decision that does affect
the functionality of the program. For example, it would be considered an error if a
software program tried to divide by zero and terminated. Preventing that from happening
would be considered good practice. On the other hand, indenting the body of a loop with
four spaces (as opposed to some other number of spaces) would have no effect on the
program. (The compiler would literally produce that same program.) So indentation
choices would be considered coding style.
In many companies, good practice rules are mixed in with the coding styles. This
book does not do that. This book only addresses coding styles, and does not address good
practice.

Why Have Coding Style Guidelines


Since coding style has no affect on the behavior of the program, it takes a back seat
to good practice. Making sure that the code works, is of much more immediate importance
than what it looks like. But what the code looks like is still important.
The code may be written once, but it may be maintained for years. So making the
code easier to read, easier to understand, and easier to maintain, becomes very important.
Thats what coding styles are all about.
C++ places a lot of importance on tiny punctuation marks like commas. Some styles,
like always putting a space after a comma, are aimed at making the code easier to
read.
As the code base gets larger and larger, it becomes important to be able to find the
code that needs to be changed. Some styles, like always putting functions in
alphabetical order, are aimed at making the code easier to navigate, so that specific
parts of it can be found when needed.
C++ requires certain structures to be properly nested. Some styles, like aligning
opening braces ({) and closing braces (}), are aimed at making errors easier to avoid.

Block Styles
Block Styles are all of the coding decisions related to code blocks. Code blocks are
lines of code surrounded by an opening brace ({) and a closing brace (}). If a software
engineer misunderstands reading where a code block begins and ends, they will
misunderstand what the code does.

Style: block layout


The opening brace ({) of the code block should be on its own line, indented to the
same level as the surrounding code. The opening brace starts a code block, and is not part
of a control structure (such as if). This can be demonstrated by creating a code block
without a control statement. Also, placing an opening brace on the same line as a control
structure confuses the indentation. For example, a continuation line of a long if statement
is indented at the same level as the code inside the code block.
The closing brace (}) of the code block should be on its own line, indented to the
same level as the surrounding code. This makes matching opening and closing braces easy
to find.
The code within the code block should be indented one level (four spaces) more
than the surrounding code.

Style: block needed


If the target of a control statement is one statement, and is not placed on the same
line as the control statement, then a code block must be used. This guards against a new
line of code (inserted between the control statement and the target statement) accidentally
changing the scope of the control statement.

C++ Styles
C++ Styles are all of the coding decisions related to techniques that exist in C++ but
not C. In most (if not all) cases, the C++ way of doing things is better than the C way of
doing things.

Style: C++ cast


C style casts (a type within parentheses, like (int)) should not be used. One of the
C++ casts (const_cast, dynamic_cast, reinterpret_cast, or static_cast) should be
used instead. These casts specifically tell the compiler (and future readers) what you are
trying to accomplish.

Style: C++ source name


Source files should end in .cpp which stands for C plus plus. .c should not be
used because that indicates a C (not C++) program. .C, .cc and .cxx should not be used
because they do not stand for anything.

Style: C++ struct


C++ expanded the meaning of struct to be almost the same as class almost
interchangeably. (The only difference is that struct defaults to public scope while class
defaults to private scope.) struct should only be used where a C (not C++) compiler
would understand it. This means the if there are any member functions or any private or
protected member variables, then class should be used.

Class Styles
Class Styles are all of the coding decisions related to classes and objects. Object
oriented design is often the main reason that C++ is being used on a project, so making the
classes and objects easy to understand probably has the biggest impact on making future
maintenance easier.

Style: class layout


Within a class definition, declarations should be in the following order:
using statements
typedefs and enums

constants
constructors
destructor
member functions
member variables
Types, constants and functions are placed closer to the top because everyone using the
class needs to read them. Member functions and variables are placed closer to the end
because only a software engineer maintaining this class needs to read them.

Style: class operator


Operators should only be overloaded when there is a well-known definition for
those operators. Do not invent a new language made up of new operators.

Style: class variable


Class variables should follow the same name style as any other variable. In other
words, do not try to mark class variables with a special convention (such as a special
prefix or suffix). This is a hold over from when object oriented design was new and class
variables were considered something special. In an object oriented language, class
variables are the most common type of variable, so there is no need to mark it as if it were
unusual.

Comment Styles
Comment Styles are all of the coding decisions related to comments. Comments
explain what the code is doing. It is very important that they convey that information
accurately.

Style: comment DEBUG


The key word DEBUG should be used in a comment to mark temporary code. This
makes it easy to search for temporary code and remove it later.

Style: comment end-of-line


A comment at the end of a line should be separated from the code by at least two
spaces. It should begin with a double slash (//). Multiple end-of-line comments, on lines
near each other, may have their double slash (//) vertically aligned.

Style: comment grammar


Comments may be short phrases or even single words that make the code clearer. If
whole sentences are used, then the entire comment should have proper grammar and
punctuation used in prose.

Style: comment header


A header comment should be placed at the top of every file explaining what that file
contains. The first and last line of the comment header should be a row of slashes (/).
Intermediate lines, including blank lines, should begin with a double slash (//).

Style: comment in-line


A comment in the middle of the line begins with /* and ends with */. The comment
should be separated from the preceding and following code by at least one space.

Style: comment line


A comment on its own line should be indented along with the code it is part of. It
should begin with a double slash (//).

Style: comment TODO


The key word TODO should be used in a comment to mark places where more code
needs to be written. This makes it easy to search for unfinished code and add to it later.

Function Styles
Function Styles are all of the coding decisions related to functions. These include
member functions which are often called methods.

Style: function declaration


The return type, the function name, and the first parameter should be on the same
line if there is room. Additional arguments should be on the same line as long as there is
room. (If some of the arguments need comments, they can be on their own lines with endof-line comments.) The opening and closing braces of the code block should be on their
own lines. The code within the function should be indented one level (four spaces) more
than the function signature.

Style: function parameter const


Input parameters should be const references. Output parameters (and parameters
that are both input and output parameters) should be non-const references.

Style: function parameter default


Default parameters should only be defined if there is a well-known default value
acknowledged in the real-world.

Style: function parameter order


Function parameters should be declared in the following order:
input parameters (including input/output parameters)
output parameters
An exception can be made if the parameters are from a well-known equation that always
has the parameters in a specific order.

Style: function parameter reference


Function parameters should be references unless they are built in types or for some
reason needs to be a pointer.

Style: function parameter unused


Unused function parameters should have commented out variable names.

Header Styles
Header Styles are all of the coding decisions related to header files.

Style: header content


Header files should contain declarations but not definitions. This means that classes
should list the members, but not include code for them. Function prototypes should be
included, but not the function bodies.

Style: header guard


C++ header files should use a guard to prevent it from being included more than
once. This is done by placing a #define and #ifdef at the beginning of the file and an
#endif at the end of the file. The defined macro should be the complete path name of the
header file, with non-alphabetic characters replaced with an underscore. This will almost
always ensure a unique macro name. For example:
#define project_alpha_MyClass_hpp
#ifdef project_alpha_MyClass_hpp
...
#endif

Style: header layout


Within a header file, #includes should be in the following order:
C library headers
C++ library headers
other library headers
project library headers
class definitions
function prototypes
This allows custom libraries to refer to definitions in C++ libraries and allows custom and
C++ libraries to refer to C and system libraries. Within each section, libraries should be in
alphabetical order. Be aware that a poorly written header (which demands the previous
inclusion of another header) may force #includes to be in another order.

Style: header name


Header files (meant to be included once) should end in .hpp which stands for
header plus plus. Specific header files, which can be compiled by a C (not C++)
compiler should end in .h which C uses for header files. Include files (meant to be
included more than once) should end in .inc which stands for include.

Style: header needs #include


Header files should #include any header files necessary to allow it to compile. The
header files should not depend on its users having already included another specific header
file.

Style: header paths


#includes should use relative paths beginning at the same level as the file they are
in. This means that the paths should not being with a slash (/).

Layout Styles
Layout Styles are all of the coding decisions related to white space. These include
spaces, tabs, line breaks, and any other invisible characters.

Style: layout function


There will be no spaces between a function name and the following left parenthesis.

Style: layout indent


Indentation will be in multiples of four spaces. Lines of code that continue the
previous line of code will be indented one level (four spaces) beyond the first line.

Style: layout line breaks


Usually, there should be one statement per line. Sections of code, that perform a
specific task, should be separated by blank lines. Line breaks can be omitted to create a
visual groupings, such as one line within a two dimensional array.

Style: layout non-function


A single space will be used between a control statement and the following left
parenthesis.

Style: layout operator


Membership operators (., ->, .*, ->*, []) will have no spaces around the operator.
Other binary operators (and the tertiary operators) will have one space between the
operator and the operands. Unary operators will have no spaces between the operator and
the operands.

Style: layout pointer declaration


When a pointer type or variable is being declared, there must be at least one space
between the type and the asterisk. The compiler does not care where the spaces are, but
the placement of the spaces affects how a software engineer might read the code. For
example, the following lines both declare one pointer and one int:
int* a, b; // bad - looks like the type is int*
int *a, b; // good - clear that the type is int

Style: layout reference declaration


When a reference type or variable is being declared, there must be at least one space
between the type and the ampersand. The compiler does not care where the spaces are, but
the placement of the spaces affects how a software engineer might read the code. For
example, the following lines both declare one reference and one int:
int& a, b; // bad - looks like the type is int&
int &a, b; // good - clear that the type is int

Style: layout semi-colon


There should be no spaces before a semi-colon.

Style: layout tab


Tab characters should never be used. They are visually indistinguishable from
spaces. For indentation, four spaces should be used instead of a tab character. For
character strings, \t should be used to create a tab character.

Style: layout trailing backslash


A trailing backslash (\) will not be used to continue a line. No identifier or reserved
should be split by a line break. A long character string can be broken up by ending with a
quote (") on the first line and beginning with a quote (") on the following line.

Style: layout trailing space


A space should never be the last character on a line.

Name Styles
Name Styles are all of the coding decisions related to the choice of user defined
identifiers. These include names of files, macros, types, or variables.

Style: name acronym


Acronyms within names will be treated as single words. This means that they are
not written in all capitals, as in normal English. The first letter should be capitalized
according to the style (whether it is a namespace, type, or variable) and all subsequent
letters will be lowercase.

Style: name function


Functions (including member functions) will be named beginning with a lowercase
letter and every subsequent word beginning with a capital letter. For example,
myFunction. This is the same style used for variables. Since function names can be used
as pointers, a function can be used as a variable, and since objects can have functors
defined for them, an object can be used as a function. Trying to name them differently
breaks encapsulation and forces the end user to know the implementation in order to know
how to capitalize the name.

Style: name leading underscore


C++ allows an identifier to begin with a leading underscore, but such usage is
reserved for compilers. For that reason, no user defined identifier can begin with an
underscore.

Style: name namespace


Namespaces will be named with only lowercase letter. For example, my_namespace.

Style: name variable


Variables (including member variables) will be named beginning with a lowercase
letter and every subsequent word beginning with a capital letter. For example,
myVariable.

Style: name type


Types (including classes, enums, structs, and typedefs) will be named beginning
with a capital letter and every subsequent word beginning with a capital letter. For
example MyType.

Variable Styles
Variable Styles are all of the coding decisions related to variables. These include
member variables which are often called attributes.

Style: variable init


Variables should be initialized immediately if possible. This reduces the possibility
that the variable is used before it is assigned a value.

Style: variable scope


A variable should be declared at the smallest scope possible, unless that would be
inside a loop and incur extra overhead. This means that in order of preference, variables
should be declared
in a control statement (like for)
in a code block
in a function
in a function parameter list
in an object (non-static member variable)
in a class (static member variable)
in a namespace
as a global variable

Appendix - check list of styles to look for


Block Styles
block layout
block needed

C++ Styles
C++ cast
C++ source name
C++ struct

Class Styles
class layout
class operator
class variable

Comment Styles
comment DEBUG
comment end-of-line
comment grammar
comment header
comment in-line
comment line
comment TODO

Function Styles
function declaration
function parameter const
function parameter default
function parameter order
function parameter reference
function parameter unused

Header Styles
header content
header guard
header layout
header name
header needs #include

header paths

Layout Styles
layout function
layout indent
layout line breaks
layout non-function
layout operator
layout pointer declaration
layout reference declaration
layout semi-colon
layout tab
layout trailing backslash
layout trailing space

Name Styles
name acronym
name function
name leading underscore
name namespace
name variable
name type

Variable Styles
variable init
variable scope

S-ar putea să vă placă și