instant management c++ coding style - louis newstrom

Upload: gamindu-udayanga

Post on 05-Jul-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    1/77

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    2/77

    Copyright © 2016 by Louis Newstrom

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

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    3/77

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    4/77

    The Instant Management SeriesImagine 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 avoidthem. They would have checklists so nothing was forgotten. They would know when each

    task would be done, and what resources it would use.Don’t 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.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    5/77

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    6/77

    Table of ContentsWhat 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

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    7/77

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    8/77

    What Coding Styles AreA 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 affectthe 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 happeningwould be considered good practice. On the other hand, indenting the body of a loop withfour spaces (as opposed to some other number of spaces) would have no effect on theprogram. (The compiler would literally produce that same program.) So indentationchoices would be considered coding style.

    In many companies, good practice rules are mixed in with the coding styles. Thisbook does not do that. This book only addresses coding styles, and does not address goodpractice.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    9/77

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    10/77

    Why Have Coding Style GuidelinesSince 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 importancethan 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 thecode easier to read, easier to understand, and easier to maintain, becomes very important.That’s 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 toread.

    As the code base gets larger and larger, it becomes important to be able to find thecode that needs to be changed. Some styles, like always putting functions inalphabetical order, are aimed at making the code easier to navigate, so that specificparts of it can be found when needed.

    C++ requires certain structures to be properly nested. Some styles, like aligningopening braces ( { ) and closing braces ( } ), are aimed at making errors easier to avoid.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    11/77

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    12/77

    Block StylesBlock 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 softwareengineer misunderstands reading where a code block begins and ends, they will

    misunderstand what the code does.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    13/77

    Style: block layoutThe 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 partof a control structure (such as if ). This can be demonstrated by creating a code blockwithout a control statement. Also, placing an opening brace on the same line as a controlstructure confuses the indentation. For example, a continuation line of a long if statementis 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 thesame level as the surrounding code. This makes matching opening and closing braces easyto find.

    The code within the code block should be indented one level (four spaces) morethan the surrounding code.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    14/77

    Style: block neededIf 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 newline of code (inserted between the control statement and the target statement) accidentallychanging the scope of the control statement.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    15/77

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    16/77

    C++ StylesC++ 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 ofdoing things.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    17/77

    Style: C++ castC 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 beused instead. These casts specifically tell the compiler (and future readers) what you aretrying to accomplish.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    18/77

    Style: C++ source nameSource 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 usedbecause they do not stand for anything.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    19/77

    Style: C++ structC++ 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 classdefaults to private scope.) struct should only be used where a C (not C++) compilerwould understand it. This means the if there are any member functions or any private orprotected member variables, then class should be used.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    20/77

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    21/77

    Class StylesClass 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 theclasses and objects easy to understand probably has the biggest impact on making future

    maintenance easier.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    22/77

    Style: class layoutWithin a class definition, declarations should be in the following order:

    using statementstypedef s and enum sconstantsconstructorsdestructormember functionsmember variables

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

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    23/77

    Style: class operatorOperators 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.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    24/77

    Style: class variableClass 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 specialprefix or suffix). This is a hold over from when object oriented design was new and classvariables were considered something special. In an object oriented language, classvariables are the most common type of variable, so there is no need to mark it as if it wereunusual.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    25/77

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    26/77

    Comment StylesComment 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 informationaccurately.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    27/77

    Style: comment DEBUGThe 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.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    28/77

    Style: comment end-of-lineA 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 linesnear each other, may have their double slash ( // ) vertically aligned.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    29/77

    Style: comment grammarComments 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 andpunctuation used in prose.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    30/77

    Style: comment headerA 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 ( // ).

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    31/77

    Style: comment in-lineA 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.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    32/77

    Style: comment lineA comment on its own line should be indented along with the code it is part of. It

    should begin with a double slash ( // ).

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    33/77

    Style: comment TODOThe 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.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    34/77

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    35/77

    Function StylesFunction Styles are all of the coding decisions related to functions. These include

    member functions which are often called methods.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    36/77

    Style: function declarationThe 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 isroom. (If some of the arguments need comments, they can be on their own lines with end-of-line comments.) The opening and closing braces of the code block should be on theirown lines. The code within the function should be indented one level (four spaces) morethan the function signature.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    37/77

    Style: function parameter constInput parameters should be const references. Output parameters (and parameters

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

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    38/77

    Style: function parameter defaultDefault parameters should only be defined if there is a well-known default value

    acknowledged in the real-world.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    39/77

    Style: function parameter orderFunction 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 alwayshas the parameters in a specific order.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    40/77

    Style: function parameter referenceFunction parameters should be references unless they are built in types or for some

    reason needs to be a pointer.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    41/77

    Style: function parameter unusedUnused function parameters should have commented out variable names.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    42/77

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    43/77

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

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    44/77

    Style: header contentHeader files should contain declarations but not definitions. This means that classes

    should list the members, but not include code for them. Function prototypes should beincluded, but not the function bodies.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    45/77

    Style: header guardC++ 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 theheader file, with non-alphabetic characters replaced with an underscore. This will almostalways ensure a unique macro name. For example:

    #define project_alpha_MyClass_hpp#ifdef project_alpha_MyClass_hpp...#endif

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    46/77

    Style: header layoutWithin a header file, #include s should be in the following order:

    C library headersC++ library headersother library headersproject library headersclass definitionsfunction prototypes

    This allows custom libraries to refer to definitions in C++ libraries and allows custom andC++ libraries to refer to C and system libraries. Within each section, libraries should be inalphabetical order. Be aware that a poorly written header (which demands the previousinclusion of another header) may force #include s to be in another order.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    47/77

    Style: header nameHeader 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 beincluded more than once) should end in .inc which stands for “include”.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    48/77

    Style: header needs #includeHeader 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 headerfile.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    49/77

    Style: header paths#include s 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 ( / ).

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    50/77

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    51/77

    Layout StylesLayout Styles are all of the coding decisions related to white space. These include

    spaces, tabs, line breaks, and any other invisible characters.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    52/77

    Style: layout functionThere will be no spaces between a function name and the following left parenthesis.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    53/77

    Style: layout indentIndentation 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.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    54/77

    Style: layout line breaksUsually, 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 avisual groupings, such as one line within a two dimensional array.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    55/77

    Style: layout non-functionA single space will be used between a control statement and the following left

    parenthesis.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    56/77

    Style: layout operatorMembership operators ( . , -> , .* , ->* , [] ) will have no spaces around the operator.

    Other binary operators (and the tertiary operators) will have one space between theoperator and the operands. Unary operators will have no spaces between the operator andthe operands.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    57/77

    Style: layout pointer declarationWhen 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, butthe placement of the spaces affects how a software engineer might read the code. Forexample, 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

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    58/77

    Style: layout reference declarationWhen 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, butthe placement of the spaces affects how a software engineer might read the code. Forexample, 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

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    59/77

    Style: layout semi-colonThere should be no spaces before a semi-colon.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    60/77

    Style: layout tabTab characters should never be used. They are visually indistinguishable from

    spaces. For indentation, four spaces should be used instead of a tab character. Forcharacter strings, \t should be used to create a tab character.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    61/77

    Style: layout trailing backslashA 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 aquote ( " ) on the first line and beginning with a quote ( " ) on the following line.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    62/77

    Style: layout trailing spaceA space should never be the last character on a line.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    63/77

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    64/77

    Name StylesName Styles are all of the coding decisions related to the choice of user defined

    identifiers. These include names of files, macros, types, or variables.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    65/77

    Style: name acronymAcronyms 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 capitalizedaccording to the style (whether it is a namespace, type, or variable) and all subsequentletters will be lowercase.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    66/77

    Style: name functionFunctions (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 usedas pointers, a function can be used as a variable, and since objects can have functorsdefined for them, an object can be used as a function. Trying to name them differentlybreaks encapsulation and forces the end user to know the implementation in order to knowhow to capitalize the name.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    67/77

    Style: name leading underscoreC++ 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 anunderscore.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    68/77

    Style: name namespaceNamespaces will be named with only lowercase letter. For example, my_namespace .

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    69/77

    Style: name variableVariables (including member variables) will be named beginning with a lowercase

    letter and every subsequent word beginning with a capital letter. For example,myVariable .

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    70/77

    Style: name typeTypes (including class es, enum s, struct s, and typedef s) will be named beginning

    with a capital letter and every subsequent word beginning with a capital letter. Forexample MyType .

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    71/77

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    72/77

    Variable StylesVariable Styles are all of the coding decisions related to variables. These include

    member variables which are often called attributes.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    73/77

    Style: variable initVariables should be initialized immediately if possible. This reduces the possibility

    that the variable is used before it is assigned a value.

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    74/77

    Style: variable scopeA 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, variablesshould be declared

    in a control statement (like for )in a code blockin a functionin a function parameter listin an object (non- static member variable)in a class ( static member variable)in a namespaceas a global variable

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    75/77

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    76/77

    Appendix - check list of styles to look forBlock 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

  • 8/16/2019 Instant Management C++ Coding Style - Louis Newstrom

    77/77

    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