C++ Coding Standards: Rules, Guidelines, and Best Practices / Edition 1

Paperback (Print)
Used and New from Other Sellers
Used and New from Other Sellers
from $19.93
Usually ships in 1-2 business days
(Save 60%)
Other sellers (Paperback)
  • All (13) from $19.93   
  • New (7) from $35.26   
  • Used (6) from $19.93   

Overview

Consistent, high-quality coding standards improve software quality, reduce time-to-market, promote teamwork, eliminate time wasted on inconsequential matters, and simplify maintenance. Now, two of the world's most respected C++ experts distill the rich collective experience of the global C++ community into a set of coding standards that every developer and development team can understand and use as a basis for their own coding standards.

The authors cover virtually every facet of C++ programming: design and coding style, functions, operators, class design, inheritance, construction/destruction, copying, assignment, namespaces, modules, templates, genericity, exceptions, STL containers and algorithms, and more. Each standard is described concisely, with practical examples. From type definition to error handling, this book presents C++ best practices, including some that have only recently been identified and standardized-techniques you may not know even if you've used C++ for years. Along the way, you'll find answers to questions like

  • What's worth standardizing--and what isn't?
  • What are the best ways to code for scalability?
  • What are the elements of a rational error handling policy?
  • How (and why) do you avoid unnecessary initialization, cyclic, and definitional dependencies?
  • When (and how) should you use static and dynamic polymorphism together?
  • How do you practice "safe" overriding?
  • When should you provide a no-fail swap?
  • Why and how should you prevent exceptions from propagating across module boundaries?
  • Why shouldn't you write namespace declarations or directives in a header file?
  • Why should you use STL vector and string instead of arrays?
  • How do you choose the right STL search or sort algorithm?
  • What rules should you follow to ensure type-safe code?

Whether you're working alone or with others, C++ Coding Standards will help you write cleaner code--and write it faster, with fewer hassles and less frustration.

Read More Show Less

Product Details

  • ISBN-13: 9780321113580
  • Publisher: Addison-Wesley
  • Publication date: 10/29/2004
  • Series: C++ In-Depth Series
  • Edition description: New Edition
  • Edition number: 1
  • Pages: 224
  • Sales rank: 412,575
  • Product dimensions: 7.37 (w) x 9.20 (h) x 0.53 (d)

Meet the Author

Herb Sutter is the author of three highly acclaimed books, Exceptional C++ Style, Exceptional C++, and More Exceptional C++ (Addison-Wesley). He chairs the ISO C++ standards committee, and is contributing editor and columnist for C/C++ Users Journal. As a software architect for Microsoft, Sutter leads the design of C++ language extensions for .NET programming.

Andrei Alexandrescu is the author of the award-winning book Modern C++ Design (Addison-Wesley, 2001) and is a columnist for C/C++ Users Journal.

Read More Show Less

Read an Excerpt

Get into a rut early: Do the same process the same way. Accumulate idioms. Standardize. The only difference(!) between Shakespeare and you was the size of his idiom list-not the size of his vocabulary.

—Alan Perlis emphasis ours

The best thing about standards is that there are so many to choose from.

—Variously attributed

We want to provide this book as a basis for your team's coding standards for two principal reasons:

A coding standard should reflect the community's best tried-and-true experience: It should contain proven idioms based on experience and solid understanding of the language. In particular, a coding standard should be based firmly on the extensive and rich software development literature, bringing together rules, guidelines, and best practices that would otherwise be left scattered throughout many sources.

Nature abhors a vacuum: If you don't consciously set out reasonable rules, usually someone else will try to push their own set of pet rules instead. A coding standard made that way usually has all of the least desirable properties of a coding standard; for example, many such standards try to enforce a minimalistic C style use of C++.

Many bad coding standards have been set by people who don't understand the language well, don't understand software development well, or try to legislate too much. A bad coding standard quickly loses credibility and at best even its valid guidelines are liable to be ignored by disenchanted programmers who dislike or disagree with its poorer guidelines. That's "at best"—at worst, a bad standard might actually be enforced.

How to Use This Book

Think. Do follow good guidelines conscientiously; but don't follow them blindly. In this book's Items, note the Exceptions clarifying the less common situations where the guidance may not apply. No set of guidelines, however good (and we think these ones are), should try to be a substitute for thinking.

Each development team is responsible for setting its own standards, and for setting them responsibly. That includes your team. If you are a team lead, involve your team members in setting the team's standards; people are more likely to follow standards they view as their own than they are to follow a bunch of rules they feel are being thrust upon them.

This book is designed to be used as a basis for, and to be included by reference in, your team's coding standards. It is not intended to be the Last Word in coding standards, because your team will have additional guidelines appropriate to your particular group or task, and you should feel free to add those to these Items. But we hope that this book will save you some of the work of (re)developing your own, by documenting and referencing widely-accepted and authoritative practices that apply nearly universally (with Exceptions as noted), and so help increase the quality and consistency of the coding standards you use.

Have your team read these guidelines with their rationales (i.e., the whole book, and selected Items' References to other books and papers as needed), and decide if there are any that your team simply can't live with (e.g., because of some situation unique to your project). Then commit to the rest. Once adopted, the team's coding standards should not be violated except after consulting with the whole team.

Finally, periodically review your guidelines as a team to include practical experience and feedback from real use.

Coding Standards and You

Good coding standards can offer many interrelated advantages:

  • Improved code quality: Encouraging developers to do the right things in a consistent way directly works to improve software quality and maintainability.
  • Improved development speed: Developers don't need to always make decisions starting from first principles.
  • Better teamwork: They help reduce needless debates on inconsequential issues and make it easier for teammates to read and maintain each other's code.
  • Uniformity in the right dimension: This frees developers to be creative in directions that matter.

Under stress and time pressure, people do what they've been trained to do. They fall back on habit. That's why ER units in hospitals employ experienced, trained personnel; even knowledgeable beginners would panic.

As software developers, we routinely face enormous pressure to deliver tomorrow's software yesterday. Under schedule pressure, we do what we are trained to do and are used to doing. Sloppy programmers who in normal times don't know good practices of software engineering (or aren't used to applying them) will write even sloppier and buggier code when pressure is on. Conversely, programmers who form good habits and practice them regularly will keep themselves organized and deliver quality code, fast.

The coding standards introduced by this book are a collection of guidelines for writing high-quality C++ code. They are the distilled conclusions of a rich collective experience of the C++ community. Much of this body of knowledge has only been available in bits and pieces spread throughout books, or as word-of-mouth wisdom. This book's intent is to collect that knowledge into a collection of rules that is terse, justified, and easy to understand and follow.

Of course, one can write bad code even with the best coding standards. The same is true of any language, process, or methodology. A good set of coding standards fosters good habits and discipline that transcend mere rules. That foundation, once acquired, opens the door to higher levels. There's no shortcut; you have to develop vocabulary and grammar before writing poetry. We just hope to make that easier.

We address this book to C++ programmers of all levels:

If you are an apprentice programmer, we hope you will find the rules and their rationale helpful in understanding what styles and idioms C++ supports most naturally. We provide a concise rationale and discussion for each rule and guideline to encourage you to rely on understanding, not just rote memorization.

For the intermediate or advanced programmer, we have worked hard to provide a detailed list of precise references for each rule. This way, you can do further research into the rule's roots in C++'s type system, grammar, and object model. At any rate, it is very likely that you work in a team on a complex project. Here is where coding standards really pay off-you can use them to bring the team to a common level and provide a basis for code reviews.

About This Book

We have set out the following design goals for this book:

Short is better than long: Huge coding standards tend to be ignored; short ones get read and used. Long Items tend to be skimmed; short ones get read and used.

Each Item must be noncontroversial: This book exists to document widely agreed upon standards, not to invent them. If a guideline is not appropriate in all cases, it will be presented that way (e.g., "Consider X..." instead of "Do X...") and we will note commonly accepted exceptions.

Each Item must be authoritative: The guidelines in this book are backed up by references to existing published works. This book is intended to also provide an index into the C++ literature.

Each Item must need saying: We chose not to define new guidelines for things that you'll do anyway, that are already enforced or detected by the compiler, or that are already covered under other Items.

Example: "Don't return a pointer/reference to an automatic variable" is a good guideline, but we chose not to include it in this book because all of the compilers we tried already emit a warning for this, and so the issue is already covered under the broader Item 1, "Compile cleanly at high warning levels."

Example: "Use an editor (or compiler, or debugger)" is a good guideline, but of course you'll use those tools anyway without being told; instead, we spend two of our first four Items on "Use an automated build system" and "Use a version control system."

Example: "Don't abuse goto" is a great Item, but in our experience programmers universally know this, and it doesn't need saying any more.

Each Item is laid out as follows:

  • Item title: The simplest meaningful sound bite we could come up with as a mnemonic for the rule.
  • Summary: The most essential points, briefly stated.
  • Discussion: An extended explanation of the guideline. This often includes brief rationale, but remember that the bulk of the rationale is intentionally left in the References.
  • Examples (if applicable): Examples that demonstrate a rule or make it memorable.
  • Exceptions (if applicable): Any (and usually rare) cases when a rule doesn't apply. But beware the trap of being too quick to think: "Oh, I'm special; this doesn't apply in my situation"-that rationalization is common, and commonly wrong.
  • References: See these parts of the C++ literature for the full details and analysis.

In each section, we chose to nominate a "most valuable Item." Often, it's the first Item in a section, because we tried to put important Items up front in each part; but other times an important Item couldn't be put up front, for flow or readability reasons, and we felt the need to call it out for special attention in this way.

Read More Show Less

Table of Contents

Preface.

1. Organizational and Policy Issues.

Don't sweat the small stuff. (Or: Know what not to standardize.).

Compile cleanly at high warning levels.

Use an automated build system.

Use a version control system.

Invest in code reviews.

2. Design Style.

Give one entity one cohesive responsibility.

Correctness, simplicity, and clarity come first.

Know when and how to code for scalability.

Don't optimize prematurely.

Don't pessimize prematurely.

Minimize global and shared data.

Hide information.

Know when and how to code for concurrency.

Ensure resources are owned by objects. Use explicit RAII and smart pointers.

3. Coding Style.

Prefer compile- and link-time errors to run-time errors.

Use const proactively.

Avoid macros.

Avoid magic numbers.

Declare variables as locally as possible.

Always initialize variables.

Avoid long functions. Avoid deep nesting.

Avoid initialization dependencies across compilation units.

Minimize definitional dependencies. Avoid cyclic dependencies.

Make header files self-sufficient.

Always write internal #include guards. Never write external #include guards.

4. Functions and Operators.

Take parameters appropriately by value, (smart) pointer, or reference.

Preserve natural semantics for overloaded operators.

Prefer the canonical forms of arithmetic and assignment operators.

Prefer the canonical form of ++ and --. Prefer calling the prefix forms.

Consider overloading to avoid implicit type conversions.

Avoid overloading &&, , or , (comma).

Don't write code that depends on the order of evaluation of functionarguments.

5. Class Design and Inheritance.

Be clear what kind of class you're writing.

Prefer minimal classes to monolithic classes.

Prefer composition to inheritance.

Avoid inheriting from classes that were not designed to be base classes.

Prefer providing abstract interfaces.

Public inheritance is substitutability.

Inherit, not to reuse, but to be reused.

Practice safe overriding.

Consider making virtual functions nonpublic, and public functions nonvirtual.

Avoid providing implicit conversions.

Make data members private, except in behaviorless aggregates (C-stylestructs).

Don't give away your internals.

Pimpl judiciously.

Prefer writing nonmember nonfriend functions.

Always provide new and delete together.

If you provide any class-specific new, provide all of the standard forms (plain, in-place, and nothrow).

6. Construction, Destruction, and Copying.

Define and initialize member variables in the same order.

Prefer initialization to assignment in constructors.

Avoid calling virtual functions in constructors and destructors.

Make base class destructors public and virtual, or protected and nonvirtual.

Destructors, deallocation, and swap never fail.

Copy and destroy consistently.

Explicitly enable or disable copying.

Avoid slicing. Consider Clone instead of copying in base classes.

Prefer the canonical form of assignment.

Whenever it makes sense, provide a no-fail swap (and provide it correctly).

7. Namespaces and Modules.

Keep a type and its nonmember function interface in the same namespace.

Keep types and functions in separate namespaces unless they're specifically intended to work together.

Don't write namespace usings in a header file or before an #include.

Avoid allocating and deallocating memory in different modules.

Don't define entities with linkage in a header file.

Don't allow exceptions to propagate across module boundaries.

Use sufficiently portable types in a module's interface.

8. Templates and Genericity.

Blend static and dynamic polymorphism judiciously.

Customize intentionally and explicitly.

Don't specialize function templates.

Don't write unintentionally nongeneric code.

9. Error Handling and Exceptions.

Assert liberally to document internal assumptions and invariants.

Establish a rational error handling policy, and follow it strictly.

Distinguish between errors and non-errors.

Design and write error-safe code.

Prefer to use exceptions to report errors.

Throw by value, catch by reference.

Report, handle, and translate errors appropriately.

Avoid exception specifications.

10. STL: Containers.

Use vector by default. Otherwise, choose an appropriate container.

Use vector and string instead of arrays.

Use vector (and string::c_str) to exchange data with non-C++ APIs.

Store only values and smart pointers in containers.

Prefer push_back to other ways of expanding a sequence.

Prefer range operations to single-element operations.

Use the accepted idioms to really shrink capacity and really erase elements.

11. STL: Algorithms.

Use a checked STL implementation.

Prefer algorithm calls to handwritten loops.

Use the right STL search algorithm.

Use the right STL sort algorithm.

Make predicates pure functions.

Prefer function objects over functions as algorithm and comparer arguments.

Write function objects correctly.

12. Type Safety.

Avoid type switching; prefer polymorphism.

Rely on types, not on representations.

Avoid using reinterpret_cast.

Avoid using static_cast on pointers.

Avoid casting away const.

Don't use C-style casts.

Don't memcpy or memcmp non-PODs.

Don't use unions to reinterpret representation.

Don't use varargs (ellipsis).

Don't use invalid objects. Don't use unsafe functions.

Don't treat arrays polymorphically.

Bibliography.

Summary of Summaries.

Index.

Read More Show Less

Preface

Get into a rut early: Do the same process the same way. Accumulate idioms. Standardize. The only difference(!) between Shakespeare and you was the size of his idiom list-not the size of his vocabulary.

--Alan Perlis emphasis ours

The best thing about standards is that there are so many to choose from.

--Variously attributed

We want to provide this book as a basis for your team's coding standards for two principal reasons:

A coding standard should reflect the community's best tried-and-true experience: It should contain proven idioms based on experience and solid understanding of the language. In particular, a coding standard should be based firmly on the extensive and rich software development literature, bringing together rules, guidelines, and best practices that would otherwise be left scattered throughout many sources.

Nature abhors a vacuum: If you don't consciously set out reasonable rules, usually someone else will try to push their own set of pet rules instead. A coding standard made that way usually has all of the least desirable properties of a coding standard; for example, many such standards try to enforce a minimalistic C style use of C++.

Many bad coding standards have been set by people who don't understand the language well, don't understand software development well, or try to legislate too much. A bad coding standard quickly loses credibility and at best even its valid guidelines are liable to be ignored by disenchanted programmers who dislike or disagree with its poorer guidelines. That's "at best"--at worst, a bad standard might actually be enforced.

How to Use This Book

Think. Do follow good guidelines conscientiously; but don't follow them blindly. In this book's Items, note the Exceptions clarifying the less common situations where the guidance may not apply. No set of guidelines, however good (and we think these ones are), should try to be a substitute for thinking.

Each development team is responsible for setting its own standards, and for setting them responsibly. That includes your team. If you are a team lead, involve your team members in setting the team's standards; people are more likely to follow standards they view as their own than they are to follow a bunch of rules they feel are being thrust upon them.

This book is designed to be used as a basis for, and to be included by reference in, your team's coding standards. It is not intended to be the Last Word in coding standards, because your team will have additional guidelines appropriate to your particular group or task, and you should feel free to add those to these Items. But we hope that this book will save you some of the work of (re)developing your own, by documenting and referencing widely-accepted and authoritative practices that apply nearly universally (with Exceptions as noted), and so help increase the quality and consistency of the coding standards you use.

Have your team read these guidelines with their rationales (i.e., the whole book, and selected Items' References to other books and papers as needed), and decide if there are any that your team simply can't live with (e.g., because of some situation unique to your project). Then commit to the rest. Once adopted, the team's coding standards should not be violated except after consulting with the whole team.

Finally, periodically review your guidelines as a team to include practical experience and feedback from real use.

Coding Standards and You

Good coding standards can offer many interrelated advantages:

  • Improved code quality: Encouraging developers to do the right things in a consistent way directly works to improve software quality and maintainability.
  • Improved development speed: Developers don't need to always make decisions starting from first principles.
  • Better teamwork: They help reduce needless debates on inconsequential issues and make it easier for teammates to read and maintain each other's code.
  • Uniformity in the right dimension: This frees developers to be creative in directions that matter.

Under stress and time pressure, people do what they've been trained to do. They fall back on habit. That's why ER units in hospitals employ experienced, trained personnel; even knowledgeable beginners would panic.

As software developers, we routinely face enormous pressure to deliver tomorrow's software yesterday. Under schedule pressure, we do what we are trained to do and are used to doing. Sloppy programmers who in normal times don't know good practices of software engineering (or aren't used to applying them) will write even sloppier and buggier code when pressure is on. Conversely, programmers who form good habits and practice them regularly will keep themselves organized and deliver quality code, fast.

The coding standards introduced by this book are a collection of guidelines for writing high-quality C++ code. They are the distilled conclusions of a rich collective experience of the C++ community. Much of this body of knowledge has only been available in bits and pieces spread throughout books, or as word-of-mouth wisdom. This book's intent is to collect that knowledge into a collection of rules that is terse, justified, and easy to understand and follow.

Of course, one can write bad code even with the best coding standards. The same is true of any language, process, or methodology. A good set of coding standards fosters good habits and discipline that transcend mere rules. That foundation, once acquired, opens the door to higher levels. There's no shortcut; you have to develop vocabulary and grammar before writing poetry. We just hope to make that easier.

We address this book to C++ programmers of all levels:

If you are an apprentice programmer, we hope you will find the rules and their rationale helpful in understanding what styles and idioms C++ supports most naturally. We provide a concise rationale and discussion for each rule and guideline to encourage you to rely on understanding, not just rote memorization.

For the intermediate or advanced programmer, we have worked hard to provide a detailed list of precise references for each rule. This way, you can do further research into the rule's roots in C++'s type system, grammar, and object model. At any rate, it is very likely that you work in a team on a complex project. Here is where coding standards really pay off-you can use them to bring the team to a common level and provide a basis for code reviews.

About This Book

We have set out the following design goals for this book:

Short is better than long: Huge coding standards tend to be ignored; short ones get read and used. Long Items tend to be skimmed; short ones get read and used.

Each Item must be noncontroversial: This book exists to document widely agreed upon standards, not to invent them. If a guideline is not appropriate in all cases, it will be presented that way (e.g., "Consider X..." instead of "Do X...") and we will note commonly accepted exceptions.

Each Item must be authoritative: The guidelines in this book are backed up by references to existing published works. This book is intended to also provide an index into the C++ literature.

Each Item must need saying: We chose not to define new guidelines for things that you'll do anyway, that are already enforced or detected by the compiler, or that are already covered under other Items.

Example: "Don't return a pointer/reference to an automatic variable" is a good guideline, but we chose not to include it in this book because all of the compilers we tried already emit a warning for this, and so the issue is already covered under the broader Item 1, "Compile cleanly at high warning levels."

Example: "Use an editor (or compiler, or debugger)" is a good guideline, but of course you'll use those tools anyway without being told; instead, we spend two of our first four Items on "Use an automated build system" and "Use a version control system."

Example: "Don't abuse goto" is a great Item, but in our experience programmers universally know this, and it doesn't need saying any more.

Each Item is laid out as follows:

  • Item title: The simplest meaningful sound bite we could come up with as a mnemonic for the rule.
  • Summary: The most essential points, briefly stated.
  • Discussion: An extended explanation of the guideline. This often includes brief rationale, but remember that the bulk of the rationale is intentionally left in the References.
  • Examples (if applicable): Examples that demonstrate a rule or make it memorable.
  • Exceptions (if applicable): Any (and usually rare) cases when a rule doesn't apply. But beware the trap of being too quick to think: "Oh, I'm special; this doesn't apply in my situation"-that rationalization is common, and commonly wrong.
  • References: See these parts of the C++ literature for the full details and analysis.

In each section, we chose to nominate a "most valuable Item." Often, it's the first Item in a section, because we tried to put important Items up front in each part; but other times an important Item couldn't be put up front, for flow or readability reasons, and we felt the need to call it out for special attention in this way.

Read More Show Less

Customer Reviews

Be the first to write a review
( 0 )
Rating Distribution

5 Star

(0)

4 Star

(0)

3 Star

(0)

2 Star

(0)

1 Star

(0)

Your Rating:

Your Name: Create a Pen Name or

Barnes & Noble.com Review Rules

Our reader reviews allow you to share your comments on titles you liked, or didn't, with others. By submitting an online review, you are representing to Barnes & Noble.com that all information contained in your review is original and accurate in all respects, and that the submission of such content by you and the posting of such content by Barnes & Noble.com does not and will not violate the rights of any third party. Please follow the rules below to help ensure that your review can be posted.

Reviews by Our Customers Under the Age of 13

We highly value and respect everyone's opinion concerning the titles we offer. However, we cannot allow persons under the age of 13 to have accounts at BN.com or to post customer reviews. Please see our Terms of Use for more details.

What to exclude from your review:

Please do not write about reviews, commentary, or information posted on the product page. If you see any errors in the information on the product page, please send us an email.

Reviews should not contain any of the following:

  • - HTML tags, profanity, obscenities, vulgarities, or comments that defame anyone
  • - Time-sensitive information such as tour dates, signings, lectures, etc.
  • - Single-word reviews. Other people will read your review to discover why you liked or didn't like the title. Be descriptive.
  • - Comments focusing on the author or that may ruin the ending for others
  • - Phone numbers, addresses, URLs
  • - Pricing and availability information or alternative ordering information
  • - Advertisements or commercial solicitation

Reminder:

  • - By submitting a review, you grant to Barnes & Noble.com and its sublicensees the royalty-free, perpetual, irrevocable right and license to use the review in accordance with the Barnes & Noble.com Terms of Use.
  • - Barnes & Noble.com reserves the right not to post any review -- particularly those that do not follow the terms and conditions of these Rules. Barnes & Noble.com also reserves the right to remove any review at any time without notice.
  • - See Terms of Use for other conditions and disclaimers.
Search for Products You'd Like to Recommend

Recommend other products that relate to your review. Just search for them below and share!

Create a Pen Name

Your Pen Name is your unique identity on BN.com. It will appear on the reviews you write and other website activities. Your Pen Name cannot be edited, changed or deleted once submitted.

 
Your Pen Name can be any combination of alphanumeric characters (plus - and _), and must be at least two characters long.

Continue Anonymously
Sort by: Showing 1 Customer Reviews
  • Anonymous

    Posted November 18, 2004

    some padding

    The subtitle about '101 rules...' evokes comparison with O'Reilly's series of '100 Hacks on...'. But coincidential or not, the authors do provide many useful rules if you are a serious C++ programmer who is looking to make your code more robust and easier to debug. However, there is some padding done by the authors, to reach this fabled 101 total. They added some elementary rules that are often well-described in many C++ or C texts. Like rule 17 - 'Avoid magic numbers'. In other words, define constants to hold these values. Or rule 18, about declaring variables as locally as possible. You do know these already, I hope. Later in the book, they actually get to more worthwhile discussions. Like rule 52, about copying and destroying consistently. Or rule 72, about using exceptions instead of error codes to report errors. Overall, most of the book can be useful to you. Though I think the authors would have done well to junk some trite rules.

    0 out of 1 people found this review helpful.

    Was this review helpful? Yes  No   Report this review
Sort by: Showing 1 Customer Reviews

If you find inappropriate content, please report it to Barnes & Noble
Why is this product inappropriate?
Comments (optional)