~3v1n0/unity/dash-files-open

« back to all changes in this revision

Viewing changes to guides/cppguide.xml

  • Committer: Tim Penhey
  • Date: 2011-07-19 00:32:10 UTC
  • mto: This revision was merged to the branch mainline in revision 1311.
  • Revision ID: tim.penhey@canonical.com-20110719003210-kxux222k7l9e0ty2
Add the style guide into the tree.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
<?xml version="1.0"?>
 
2
<?xml-stylesheet type="text/xsl" href="styleguide.xsl"?>
 
3
<GUIDE title="Google C++ Style Guide">
 
4
 
 
5
<p align="right">
 
6
 
 
7
Revision 3.188
 
8
</p>
 
9
 
 
10
 
 
11
 
 
12
<address>
 
13
Benjy Weinberger<br/>
 
14
Craig Silverstein<br/>
 
15
Gregory Eitzmann<br/>
 
16
Mark Mentovai<br/>
 
17
Tashana Landray
 
18
</address>
 
19
 
 
20
<OVERVIEW>
 
21
<CATEGORY title="Important Note">
 
22
  <STYLEPOINT title="Displaying Hidden Details in this Guide">
 
23
     <SUMMARY>
 
24
       This style guide contains many details that are initially
 
25
       hidden from view.  They are marked by the triangle icon, which you
 
26
       see here on your left.  Click it now.
 
27
       You should see "Hooray" appear below.
 
28
     </SUMMARY>
 
29
     <BODY>
 
30
       <p>
 
31
        Hooray!  Now you know you can expand points to get more
 
32
        details.  Alternatively, there's an "expand all" at the
 
33
        top of this document.
 
34
       </p>
 
35
     </BODY>
 
36
  </STYLEPOINT>
 
37
</CATEGORY>
 
38
<CATEGORY title="Background">
 
39
  <p>
 
40
    C++ is the main development language
 
41
    
 
42
    used by many of Google's open-source
 
43
    projects.
 
44
    As every C++ programmer knows, the language has many powerful features,
 
45
    but this power brings with it complexity, which in turn can make code
 
46
    more bug-prone and harder to read and maintain.
 
47
  </p>
 
48
  <p>
 
49
    The goal of this guide is to manage this complexity by describing
 
50
    in detail the dos and don'ts of writing C++
 
51
    code. These rules exist to
 
52
    keep
 
53
    
 
54
    the
 
55
    code base manageable while still allowing coders to use C++ language
 
56
    features productively.
 
57
  </p>
 
58
  <p>
 
59
    <em>Style</em>, also known as readability, is what we call the
 
60
    conventions that govern our C++ code. The term Style is a bit of a
 
61
    misnomer, since these conventions cover far more than just source
 
62
    file formatting.
 
63
  </p>
 
64
  <p>
 
65
    One way in which we keep the code base manageable is by enforcing
 
66
    <em>consistency</em>.
 
67
    
 
68
    It is very important that any
 
69
    
 
70
    programmer
 
71
    be able to look at another's code and quickly understand it.
 
72
    Maintaining a uniform style and following conventions means that we can
 
73
    more easily use "pattern-matching" to infer what various symbols are
 
74
    and what invariants are true about them. Creating common, required
 
75
    idioms and patterns makes code much easier to understand.  In some
 
76
    cases there might be good arguments for changing certain style
 
77
    rules, but we nonetheless keep things as they are in order to
 
78
    preserve consistency.
 
79
  </p>
 
80
  <p>
 
81
    Another issue this guide addresses is that of C++ feature bloat.
 
82
    C++ is a huge language with many advanced features. In some cases
 
83
    we constrain, or even ban, use of certain features. We do this to
 
84
    keep code simple and to avoid the various common errors and
 
85
    problems that these features can cause.  This guide lists these
 
86
    features and explains why their use is restricted.
 
87
  </p>
 
88
  <p>
 
89
    
 
90
    Open-source projects developed by Google
 
91
    conform to the requirements in this guide.
 
92
  </p>
 
93
  
 
94
  <p>
 
95
    Note that this guide is not a C++ tutorial: we assume that the
 
96
    reader is familiar with the language.
 
97
    
 
98
  </p>
 
99
  
 
100
</CATEGORY>
 
101
</OVERVIEW>
 
102
 
 
103
<CATEGORY title="Header Files">
 
104
  <p>
 
105
    In general, every <code>.cc</code> file should have an associated
 
106
    <code>.h</code> file. There are some common exceptions, such as
 
107
    
 
108
    unittests
 
109
    and small <code>.cc</code> files containing just a <code>main()</code>
 
110
    function.
 
111
  </p>
 
112
  <p>
 
113
    Correct use of header files can make a huge difference to the
 
114
    readability, size and performance of your code.
 
115
  </p>
 
116
  <p>
 
117
    The following rules will guide you through the various pitfalls of
 
118
    using header files.
 
119
  </p>
 
120
 
 
121
  <STYLEPOINT title="The #define Guard">
 
122
    <SUMMARY>
 
123
      All header files should have <code>#define</code> guards to
 
124
      prevent multiple inclusion.  The format of the symbol name
 
125
      should be
 
126
      <code><i>&lt;PROJECT&gt;</i>_<i>&lt;PATH&gt;</i>_<i>&lt;FILE&gt;</i>_H_</code>.
 
127
    </SUMMARY>
 
128
    <BODY>
 
129
      
 
130
      <p>
 
131
        To guarantee uniqueness, they should be based on the full path
 
132
        in a project's source tree.  For example, the file
 
133
        <code>foo/src/bar/baz.h</code> in project <code>foo</code> should
 
134
        have the following guard:
 
135
      </p>
 
136
      <CODE_SNIPPET>
 
137
         #ifndef FOO_BAR_BAZ_H_
 
138
         #define FOO_BAR_BAZ_H_
 
139
 
 
140
         ...
 
141
 
 
142
         #endif  // FOO_BAR_BAZ_H_
 
143
      </CODE_SNIPPET>
 
144
      
 
145
    </BODY>
 
146
  </STYLEPOINT>
 
147
 
 
148
  <STYLEPOINT title="Header File Dependencies">
 
149
    <SUMMARY>
 
150
        Don't use an <code>#include</code> when a forward declaration
 
151
        would suffice.
 
152
    </SUMMARY>
 
153
    <BODY>
 
154
      <p>
 
155
        When you include a header file you introduce a dependency that
 
156
        will cause your code to be recompiled whenever the header file
 
157
        changes. If your header file includes other header files, any
 
158
        change to those files will cause any code that includes your
 
159
        header to be recompiled.  Therefore, we prefer to minimize
 
160
        includes, particularly includes of header files in other
 
161
        header files.
 
162
      </p>
 
163
      <p>
 
164
        You can significantly reduce the number of header files you
 
165
        need to include in your own header files by using forward
 
166
        declarations.  For example, if your header file uses the
 
167
        <code>File</code> class in ways that do not require access to
 
168
        the declaration of the <code>File</code> class, your header
 
169
        file can just forward declare <code>class File;</code> instead
 
170
        of having to <code>#include "file/base/file.h"</code>.
 
171
      </p>
 
172
      <p>
 
173
        How can we use a class <code>Foo</code> in a header file
 
174
        without access to its definition?
 
175
      </p>
 
176
      <ul>
 
177
        <li> We can declare data members of type <code>Foo*</code> or
 
178
             <code>Foo&amp;</code>.
 
179
             </li>
 
180
        <li> We can declare (but not define) functions with arguments,
 
181
             and/or return values, of type <code>Foo</code>.  (One
 
182
             exception is if an argument <code>Foo</code>
 
183
             or <code>const Foo&amp;</code> has a
 
184
             non-<code>explicit</code>, one-argument constructor,
 
185
             
 
186
             in which case we need the full definition to support
 
187
             automatic type conversion.)
 
188
             </li>
 
189
        <li> We can declare static data members of type
 
190
             <code>Foo</code>.  This is because static data members
 
191
             are defined outside the class definition.
 
192
             </li>
 
193
      </ul>
 
194
      <p>
 
195
        On the other hand, you must include the header file for
 
196
        <code>Foo</code> if your class subclasses <code>Foo</code> or
 
197
        has a data member of type <code>Foo</code>.
 
198
      </p>
 
199
      <p>
 
200
        Sometimes it makes sense to have pointer (or better,
 
201
        <code>scoped_ptr</code>)
 
202
        members instead of object members. However, this complicates code
 
203
        readability and imposes a performance penalty, so avoid doing
 
204
        this transformation if the only purpose is to minimize includes
 
205
        in header files.
 
206
      </p>
 
207
      <p>
 
208
        Of course, <code>.cc</code> files typically do require the
 
209
        definitions of the classes they use, and usually have to
 
210
        include several header files.
 
211
      </p>
 
212
      
 
213
      <SUBSECTION title="Note:">
 
214
        If you use a symbol <code>Foo</code> in your source file, you
 
215
        should bring in a definition for <code>Foo</code> yourself,
 
216
        either via an #include or via a forward declaration.  Do not
 
217
        depend on the symbol being brought in transitively via headers
 
218
        not directly included.  One exception is if <code>Foo</code>
 
219
        is used in <code>myfile.cc</code>, it's ok to #include (or
 
220
        forward-declare) <code>Foo</code> in <code>myfile.h</code>,
 
221
        instead of <code>myfile.cc</code>.
 
222
      </SUBSECTION>
 
223
    </BODY>
 
224
  </STYLEPOINT>
 
225
 
 
226
  <STYLEPOINT title="Inline Functions">
 
227
    <SUMMARY>
 
228
      Define functions inline only when they are small, say, 10 lines
 
229
      or less.
 
230
    </SUMMARY>
 
231
    <BODY>
 
232
      <DEFINITION>
 
233
        You can declare functions in a way that allows the compiler to
 
234
        expand them inline rather than calling them through the usual
 
235
        function call mechanism.
 
236
      </DEFINITION>
 
237
      <PROS>
 
238
        Inlining a function can generate more efficient object code,
 
239
        as long as the inlined function is small. Feel free to inline
 
240
        accessors and mutators, and other short, performance-critical
 
241
        functions.
 
242
      </PROS>
 
243
      <CONS>
 
244
        Overuse of inlining can actually make programs slower.
 
245
        Depending on a function's size, inlining it can cause the code
 
246
        size to increase or decrease.  Inlining a very small accessor
 
247
        function will usually decrease code size while inlining a very
 
248
        large function can dramatically increase code size.  On modern
 
249
        processors smaller code usually runs faster due to better use
 
250
        of the instruction cache.
 
251
      </CONS>
 
252
      <DECISION>
 
253
        <p>
 
254
          A decent rule of thumb is to not inline a function if it is
 
255
          more than 10 lines long. Beware of destructors, which are
 
256
          often longer than they appear because of implicit member-
 
257
          and base-destructor calls!
 
258
        </p>
 
259
        <p>
 
260
          Another useful rule of thumb: it's typically not cost
 
261
          effective to inline functions with loops or switch
 
262
          statements (unless, in the common case, the loop or switch
 
263
          statement is never executed).
 
264
        </p>
 
265
        <p>
 
266
          It is important to know that functions are not always
 
267
          inlined even if they are declared as such; for example,
 
268
          virtual and recursive functions are not normally inlined.
 
269
          Usually recursive functions should not be inline.  The main
 
270
          reason for making a virtual function inline is to place its
 
271
          definition in the class, either for convenience or to
 
272
          document its behavior, e.g., for accessors and mutators.
 
273
        </p>
 
274
      </DECISION>
 
275
    </BODY>
 
276
  </STYLEPOINT>
 
277
 
 
278
  <STYLEPOINT title="The -inl.h Files">
 
279
    <SUMMARY>
 
280
      You may use file names with a <code>-inl.h</code> suffix to define
 
281
      complex inline functions when needed.
 
282
    </SUMMARY>
 
283
    <BODY>
 
284
      <p>
 
285
        The definition of an inline function needs to be in a header
 
286
        file, so that the compiler has the definition available for
 
287
        inlining at the call sites.  However, implementation code
 
288
        properly belongs in <code>.cc</code> files, and we do not like
 
289
        to have much actual code in <code>.h</code> files unless there
 
290
        is a readability or performance advantage.
 
291
      </p>
 
292
      <p>
 
293
        If an inline function definition is short, with very little,
 
294
        if any, logic in it, you should put the code in your
 
295
        <code>.h</code> file.  For example, accessors and mutators
 
296
        should certainly be inside a class definition.  More complex
 
297
        inline functions may also be put in a <code>.h</code> file for
 
298
        the convenience of the implementer and callers, though if this
 
299
        makes the <code>.h</code> file too unwieldy you can instead
 
300
        put that code in a separate <code>-inl.h</code> file.
 
301
        This separates the implementation from the class definition,
 
302
        while still allowing the implementation to be included where
 
303
        necessary.
 
304
      </p>
 
305
      <p>
 
306
        Another use of <code>-inl.h</code> files is for definitions of
 
307
        function templates.  This can be used to keep your template
 
308
        definitions easy to read.
 
309
      </p>
 
310
      <p>
 
311
        Do not forget that a <code>-inl.h</code> file requires a
 
312
        <a href="#The__define_Guard"><code>#define</code> guard</a> just
 
313
        like any other header file.
 
314
      </p>
 
315
      
 
316
    </BODY>
 
317
  </STYLEPOINT>
 
318
 
 
319
  <STYLEPOINT title="Function Parameter Ordering">
 
320
    <SUMMARY>
 
321
      When defining a function, parameter order is: inputs,
 
322
      then outputs.
 
323
    </SUMMARY>
 
324
    <BODY>
 
325
      <p>
 
326
        Parameters to C/C++ functions are either input to the
 
327
        function, output from the function, or both. Input parameters
 
328
        are usually values or <code>const</code> references, while output
 
329
        and input/output parameters will be non-<code>const</code>
 
330
        pointers. When ordering function parameters, put all input-only
 
331
        parameters before any output parameters.  In particular, do not add
 
332
        new parameters to the end of the function just because they are
 
333
        new; place new input-only parameters before the output
 
334
        parameters.
 
335
      </p>
 
336
      <p>
 
337
        This is not a hard-and-fast rule.  Parameters that are both
 
338
        input and output (often classes/structs) muddy the waters,
 
339
        and, as always, consistency with related functions may require
 
340
        you to bend the rule.
 
341
      </p>
 
342
    </BODY>
 
343
  </STYLEPOINT>
 
344
 
 
345
  <STYLEPOINT title="Names and Order of Includes">
 
346
    <SUMMARY>
 
347
      Use standard order for readability and to avoid hidden
 
348
      dependencies: C library, C++ library,
 
349
      
 
350
      other libraries' <code>.h</code>, your
 
351
      project's
 
352
      <code>.h</code>.
 
353
    </SUMMARY>
 
354
    <BODY>
 
355
      <p>
 
356
        
 
357
        All of a project's header files should be
 
358
        listed as descendants of the project's source directory
 
359
        without use of UNIX directory shortcuts <code>.</code> (the current
 
360
        directory) or <code>..</code> (the parent directory).  For
 
361
        example,
 
362
        
 
363
        <code>google-awesome-project/src/base/logging.h</code>
 
364
        should be included as
 
365
      </p>
 
366
      <CODE_SNIPPET>
 
367
        #include "base/logging.h"
 
368
      </CODE_SNIPPET>
 
369
      <p>
 
370
        In <code><var>dir/foo</var>.cc</code> or <code><var>dir/foo_test</var>.cc</code>,
 
371
        whose main purpose is to implement or test the stuff in
 
372
        <code><var>dir2/foo2</var>.h</code>, order your includes as
 
373
        follows:
 
374
      </p>
 
375
      <ol>
 
376
        <li> <code><var>dir2/foo2</var>.h</code> (preferred location
 
377
          &#8212; see details below).</li>
 
378
        <li> C system files.</li>
 
379
        <li> C++ system files.</li>
 
380
        <li> Other libraries' <code>.h</code> files.</li>
 
381
        <li> 
 
382
             Your project's
 
383
             <code>.h</code> files.</li>
 
384
      </ol>
 
385
      <p>
 
386
        The preferred ordering reduces hidden dependencies.  We want
 
387
        every header file to be compilable on its own.  The easiest
 
388
        way to achieve this is to make sure that every one of them is
 
389
        the first <code>.h</code> file <code>#include</code>d in some
 
390
        <code>.cc</code>.  
 
391
      </p>
 
392
      <p>
 
393
        <code><var>dir/foo</var>.cc</code> and
 
394
        <code><var>dir2/foo2</var>.h</code> are often in the same
 
395
        directory (e.g. <code>base/basictypes_test.cc</code> and
 
396
        <code>base/basictypes.h</code>), but can be in different
 
397
        directories too.
 
398
      </p>
 
399
      
 
400
      <p>
 
401
        Within each section it is nice to order the includes
 
402
        alphabetically.
 
403
      </p>
 
404
      <p>
 
405
        For example, the includes in
 
406
        
 
407
        <code>google-awesome-project/src/foo/internal/fooserver.cc</code>
 
408
        might look like this:
 
409
      </p>
 
410
      <CODE_SNIPPET>
 
411
        #include "foo/public/fooserver.h"  // Preferred location.
 
412
 
 
413
        #include &lt;sys/types.h&gt;
 
414
        #include &lt;unistd.h&gt;
 
415
 
 
416
        #include &lt;hash_map&gt;
 
417
        #include &lt;vector&gt;
 
418
 
 
419
        #include "base/basictypes.h"
 
420
        #include "base/commandlineflags.h"
 
421
        #include "foo/public/bar.h"
 
422
      </CODE_SNIPPET>
 
423
    </BODY>
 
424
  </STYLEPOINT>
 
425
</CATEGORY>
 
426
 
 
427
<CATEGORY title="Scoping">
 
428
  <STYLEPOINT title="Namespaces">
 
429
    <SUMMARY>
 
430
      Unnamed namespaces in <code>.cc</code> files are encouraged.  With
 
431
      named namespaces, choose the name based on the
 
432
      
 
433
      project, and possibly its path.
 
434
      Do not use a <SYNTAX>using-directive</SYNTAX>.
 
435
    </SUMMARY>
 
436
    <BODY>
 
437
      <DEFINITION>
 
438
        Namespaces subdivide the global scope into distinct, named
 
439
        scopes, and so are useful for preventing name collisions in
 
440
        the global scope.
 
441
      </DEFINITION>
 
442
      <PROS>
 
443
        <p>
 
444
          Namespaces provide a (hierarchical) axis of naming, in
 
445
          addition to the (also hierarchical) name axis provided by
 
446
          classes.
 
447
        </p>
 
448
        <p>
 
449
          For example, if two different projects have a class
 
450
          <code>Foo</code> in the global scope, these symbols may
 
451
          collide at compile time or at runtime.  If each project
 
452
          places their code in a namespace, <code>project1::Foo</code>
 
453
          and <code>project2::Foo</code> are now distinct symbols that
 
454
          do not collide.
 
455
        </p>
 
456
      </PROS>
 
457
      <CONS>
 
458
        <p>
 
459
          Namespaces can be confusing, because they provide an
 
460
          additional (hierarchical) axis of naming, in addition to the
 
461
          (also hierarchical) name axis provided by classes.
 
462
        </p>
 
463
        <p>
 
464
          Use of unnamed spaces in header files can easily cause
 
465
          violations of the C++ One Definition Rule (ODR).
 
466
        </p>
 
467
      </CONS>
 
468
      <DECISION>
 
469
        <p>
 
470
          Use namespaces according to the policy described below.
 
471
        </p>
 
472
 
 
473
        <SUBSECTION title="Unnamed Namespaces">
 
474
          <ul>
 
475
            <li> Unnamed namespaces are allowed and even encouraged in
 
476
                 <code>.cc</code> files, to avoid runtime naming
 
477
                 conflicts:
 
478
                 <CODE_SNIPPET>
 
479
                   namespace {                           // This is in a .cc file.
 
480
 
 
481
                   // The content of a namespace is not indented
 
482
                   enum { kUnused, kEOF, kError };       // Commonly used tokens.
 
483
                   bool AtEof() { return pos_ == kEOF; }  // Uses our namespace's EOF.
 
484
 
 
485
                   }  // namespace
 
486
                 </CODE_SNIPPET>
 
487
 
 
488
                 <p>
 
489
                   However, file-scope declarations that are
 
490
                   associated with a particular class may be declared
 
491
                   in that class as types, static data members or
 
492
                   static member functions rather than as members of
 
493
                   an unnamed namespace.  Terminate the unnamed
 
494
                   namespace as shown, with a comment <code>//
 
495
                   namespace</code>.
 
496
                 </p>
 
497
                 </li>
 
498
            <li> Do not use unnamed namespaces in <code>.h</code>
 
499
                 files.
 
500
                 </li>
 
501
          </ul>
 
502
        </SUBSECTION>
 
503
 
 
504
        <SUBSECTION title="Named Namespaces">
 
505
          <p>
 
506
            Named namespaces should be used as follows:
 
507
          </p>
 
508
          <ul>
 
509
            <li> Namespaces wrap the entire source file after includes,
 
510
                 
 
511
                 <a href="http://google-gflags.googlecode.com/">gflags</a>
 
512
                 definitions/declarations, and forward declarations of classes
 
513
                 from other namespaces:
 
514
                 <CODE_SNIPPET>
 
515
                   // In the .h file
 
516
                   namespace mynamespace {
 
517
 
 
518
                   // All declarations are within the namespace scope.
 
519
                   // Notice the lack of indentation.
 
520
                   class MyClass {
 
521
                    public:
 
522
                     ...
 
523
                     void Foo();
 
524
                   };
 
525
 
 
526
                   }  // namespace mynamespace
 
527
                 </CODE_SNIPPET>
 
528
                 <CODE_SNIPPET>
 
529
                   // In the .cc file
 
530
                   namespace mynamespace {
 
531
 
 
532
                   // Definition of functions is within scope of the namespace.
 
533
                   void MyClass::Foo() {
 
534
                     ...
 
535
                   }
 
536
 
 
537
                   }  // namespace mynamespace
 
538
                 </CODE_SNIPPET>
 
539
                 <p>
 
540
                   The typical <code>.cc</code> file might have more
 
541
                   complex detail, including the need to reference classes
 
542
                   in other namespaces.
 
543
                 </p>
 
544
                 <CODE_SNIPPET>
 
545
                   #include "a.h"
 
546
 
 
547
                   DEFINE_bool(someflag, false, "dummy flag");
 
548
 
 
549
                   class C;  // Forward declaration of class C in the global namespace.
 
550
                   namespace a { class A; }  // Forward declaration of a::A.
 
551
 
 
552
                   namespace b {
 
553
 
 
554
                   ...code for b...         // Code goes against the left margin.
 
555
 
 
556
                   }  // namespace b
 
557
                 </CODE_SNIPPET>
 
558
                 </li>
 
559
 
 
560
            
 
561
 
 
562
            <li> Do not declare anything in namespace
 
563
                 <code>std</code>, not even forward declarations of
 
564
                 standard library classes.  Declaring entities in
 
565
                 namespace <code>std</code> is undefined behavior,
 
566
                 i.e., not portable.  To declare entities from the
 
567
                 standard library, include the appropriate header
 
568
                 file.
 
569
                 </li>
 
570
 
 
571
            <li> You may not use a <SYNTAX>using-directive</SYNTAX> to
 
572
                 make all names from a namespace available.
 
573
                 <BAD_CODE_SNIPPET>
 
574
                   // Forbidden -- This pollutes the namespace.
 
575
                   using namespace foo;
 
576
                 </BAD_CODE_SNIPPET>
 
577
                 </li>
 
578
 
 
579
            <li> You may use a <SYNTAX>using-declaration</SYNTAX>
 
580
                 anywhere in a <code>.cc</code> file, and in functions,
 
581
                 methods or classes in <code>.h</code> files.
 
582
                 <CODE_SNIPPET>
 
583
                   // OK in .cc files.
 
584
                   // Must be in a function, method or class in .h files.
 
585
                   using ::foo::bar;
 
586
                 </CODE_SNIPPET>
 
587
                 </li>
 
588
 
 
589
            <li> Namespace aliases are allowed anywhere in a
 
590
                 <code>.cc</code> file, anywhere inside the named
 
591
                 namespace that wraps an entire <code>.h</code> file,
 
592
                 and in functions and methods.
 
593
                 <CODE_SNIPPET>
 
594
                   // Shorten access to some commonly used names in .cc files.
 
595
                   namespace fbz = ::foo::bar::baz;
 
596
 
 
597
                   // Shorten access to some commonly used names (in a .h file).
 
598
                   namespace librarian {
 
599
                   // The following alias is available to all files including
 
600
                   // this header (in namespace librarian):
 
601
                   // alias names should therefore be chosen consistently
 
602
                   // within a project.
 
603
                   namespace pd_s = ::pipeline_diagnostics::sidetable;
 
604
 
 
605
                   inline void my_inline_function() {
 
606
                     // namespace alias local to a function (or method).
 
607
                     namespace fbz = ::foo::bar::baz;
 
608
                     ...
 
609
                   }
 
610
                   }  // namespace librarian
 
611
                 </CODE_SNIPPET>
 
612
                 <p>
 
613
                 Note that an alias in a .h file is visible to everyone
 
614
                 #including that file, so public headers (those available
 
615
                 outside a project) and headers transitively #included by them,
 
616
                 should avoid defining aliases, as part of the general
 
617
                 goal of keeping public APIs as small as possible.
 
618
                 </p>
 
619
                 </li>
 
620
          </ul>
 
621
        </SUBSECTION>
 
622
 
 
623
        
 
624
 
 
625
        
 
626
 
 
627
        
 
628
      </DECISION>
 
629
    </BODY>
 
630
  </STYLEPOINT>
 
631
 
 
632
  <STYLEPOINT title="Nested Classes">
 
633
    <SUMMARY>
 
634
      Although you may use public nested classes when they are part of
 
635
      an interface, consider a <a HREF="#Namespaces">namespace</a> to
 
636
      keep declarations out of the global scope.
 
637
    </SUMMARY>
 
638
    <BODY>
 
639
      <DEFINITION>
 
640
        A class can define another class within it; this is also
 
641
        called a <SYNTAX>member class</SYNTAX>.
 
642
        <CODE_SNIPPET>
 
643
          class Foo {
 
644
 
 
645
           private:
 
646
            // Bar is a member class, nested within Foo.
 
647
            class Bar {
 
648
              ...
 
649
            };
 
650
 
 
651
          };
 
652
        </CODE_SNIPPET>
 
653
      </DEFINITION>
 
654
      <PROS>
 
655
        This is useful when the nested (or member) class is only used
 
656
        by the enclosing class; making it a member puts it in the
 
657
        enclosing class scope rather than polluting the outer scope
 
658
        with the class name.  Nested classes can be forward declared
 
659
        within the enclosing class and then defined in the
 
660
        <code>.cc</code> file to avoid including the nested class
 
661
        definition in the enclosing class declaration, since the
 
662
        nested class definition is usually only relevant to the
 
663
        implementation.
 
664
      </PROS>
 
665
      <CONS>
 
666
        Nested classes can be forward-declared only within the
 
667
        definition of the enclosing class. Thus, any header file
 
668
        manipulating a <code>Foo::Bar*</code> pointer will have to
 
669
        include the full class declaration for <code>Foo</code>.
 
670
      </CONS>
 
671
      <DECISION>
 
672
        Do not make nested classes public unless they are actually
 
673
        part of the interface, e.g., a class that holds a set of
 
674
        options for some method.
 
675
        
 
676
      </DECISION>
 
677
    </BODY>
 
678
  </STYLEPOINT>
 
679
 
 
680
  <STYLEPOINT title="Nonmember, Static Member, and Global Functions">
 
681
    <SUMMARY>
 
682
      Prefer nonmember functions within a namespace or static member
 
683
      functions to global functions; use completely global functions
 
684
      rarely.
 
685
    </SUMMARY>
 
686
    <BODY>
 
687
      <PROS>
 
688
        Nonmember and static member functions can be useful in some
 
689
        situations.  Putting nonmember functions in a namespace avoids
 
690
        polluting the global namespace.
 
691
      </PROS>
 
692
      <CONS>
 
693
        Nonmember and static member functions may make more sense as
 
694
        members of a new class, especially if they access external
 
695
        resources or have significant dependencies.
 
696
      </CONS>
 
697
      <DECISION>
 
698
        <p>
 
699
          Sometimes it is useful, or even necessary, to define a
 
700
          function not bound to a class instance.  Such a function can
 
701
          be either a static member or a nonmember function.
 
702
          Nonmember functions should not depend on external variables,
 
703
          and should nearly always exist in a namespace.  Rather than
 
704
          creating classes only to group static member functions which
 
705
          do not share static data, use
 
706
          <a href="#Namespaces">namespaces</a> instead.
 
707
        </p>
 
708
        <p>
 
709
          Functions defined in the same compilation unit as production
 
710
          classes may introduce unnecessary coupling and link-time
 
711
          dependencies when directly called from other compilation
 
712
          units; static member functions are particularly susceptible
 
713
          to this.  Consider extracting a new class, or placing the
 
714
          functions in a namespace possibly in a separate library.
 
715
        </p>
 
716
        <p>
 
717
          If you must define a nonmember function and it is only
 
718
          needed in its <code>.cc</code> file, use an unnamed
 
719
          <a HREF="#Namespaces">namespace</a> or <code>static</code>
 
720
          linkage (eg <code>static int Foo() {...}</code>) to limit
 
721
          its scope.
 
722
        </p>
 
723
      </DECISION>
 
724
    </BODY>
 
725
  </STYLEPOINT>
 
726
 
 
727
  <STYLEPOINT title="Local Variables">
 
728
    <SUMMARY>
 
729
      Place a function's variables in the narrowest scope possible,
 
730
      and initialize variables in the declaration.
 
731
    </SUMMARY>
 
732
    <BODY>
 
733
      <p>
 
734
        C++ allows you to declare variables anywhere in a function.
 
735
        We encourage you to declare them in as local a scope as
 
736
        possible, and as close to the first use as possible. This
 
737
        makes it easier for the reader to find the declaration and see
 
738
        what type the variable is and what it was initialized to.  In
 
739
        particular, initialization should be used instead of
 
740
        declaration and assignment, e.g.
 
741
      </p>
 
742
      <BAD_CODE_SNIPPET>
 
743
        int i;
 
744
        i = f();      // Bad -- initialization separate from declaration.
 
745
      </BAD_CODE_SNIPPET>
 
746
      <CODE_SNIPPET>
 
747
        int j = g();  // Good -- declaration has initialization.
 
748
      </CODE_SNIPPET>
 
749
      <p>
 
750
        Note that gcc implements <code>for (int i = 0; i
 
751
        &lt; 10; ++i)</code> correctly (the scope of <code>i</code> is
 
752
        only the scope of the <code>for</code> loop), so you can then
 
753
        reuse <code>i</code> in another <code>for</code> loop in the
 
754
        same scope.  It also correctly scopes declarations in
 
755
        <code>if</code> and <code>while</code> statements, e.g.
 
756
      </p>
 
757
      <CODE_SNIPPET>
 
758
        while (const char* p = strchr(str, '/')) str = p + 1;
 
759
      </CODE_SNIPPET>
 
760
      <p>
 
761
        There is one caveat:  if the variable is an object, its
 
762
        constructor is invoked every time it enters scope and is
 
763
        created, and its destructor is invoked every time it goes
 
764
        out of scope.
 
765
      </p>
 
766
      <BAD_CODE_SNIPPET>
 
767
        // Inefficient implementation:
 
768
        for (int i = 0; i &lt; 1000000; ++i) {
 
769
          Foo f;  // My ctor and dtor get called 1000000 times each.
 
770
          f.DoSomething(i);
 
771
        }
 
772
      </BAD_CODE_SNIPPET>
 
773
      <p>
 
774
        It may be more efficient to declare such a variable used in a
 
775
        loop outside that loop:
 
776
      </p>
 
777
      <CODE_SNIPPET>
 
778
        Foo f;  // My ctor and dtor get called once each.
 
779
        for (int i = 0; i &lt; 1000000; ++i) {
 
780
          f.DoSomething(i);
 
781
        }
 
782
      </CODE_SNIPPET>
 
783
    </BODY>
 
784
  </STYLEPOINT>
 
785
 
 
786
  <STYLEPOINT title="Static and Global Variables">
 
787
    <SUMMARY>
 
788
      Static or global variables of class type are forbidden: they cause
 
789
      hard-to-find bugs due to indeterminate order of construction and
 
790
      destruction.
 
791
    </SUMMARY>
 
792
    <BODY>
 
793
      <p>
 
794
        Objects with static storage duration, including global variables,
 
795
        static variables, static class member variables, and function static
 
796
        variables, must be Plain Old Data (POD): only ints, chars, floats, or
 
797
        pointers, or arrays/structs of POD.
 
798
      </p>
 
799
      <p>
 
800
        The order in which class constructors and initializers for
 
801
        static variables are called is only partially specified in C++ and can
 
802
        even change from build to build, which can cause bugs that are difficult
 
803
        to find.  Therefore in addition to banning globals of class type, we do
 
804
        not allow static POD variables to be initialized with the result of a
 
805
        function, unless that function (such as getenv(), or getpid()) does not
 
806
        itself depend on any other globals.
 
807
      </p>
 
808
      <p>
 
809
        Likewise, the order in which destructors are called is defined to be the
 
810
        reverse of the order in which the constructors were called.  Since
 
811
        constructor order is indeterminate, so is destructor order.
 
812
        For example, at program-end time a static variable might have
 
813
        been destroyed, but code still running -- perhaps in another thread --
 
814
        tries to access it and fails.  Or the destructor for a static 'string'
 
815
        variable might be run prior to the destructor for another variable that
 
816
        contains a reference to that string.
 
817
      </p>
 
818
      <p>
 
819
        As a result we only allow static variables to contain POD data.  This
 
820
        rule completely disallows <code>vector</code> (use C arrays instead), or
 
821
        <code>string</code> (use <code>const char []</code>).
 
822
      </p>
 
823
      
 
824
      <p>
 
825
        If you need a static or global variable of a class type, consider
 
826
        initializing a pointer (which will never be freed), from either your
 
827
        main() function or from pthread_once().  Note that this must be a raw
 
828
        pointer, not a "smart" pointer, since the smart pointer's destructor
 
829
        will have the order-of-destructor issue that we are trying to avoid.
 
830
      </p>
 
831
      
 
832
      
 
833
    </BODY>
 
834
  </STYLEPOINT>
 
835
</CATEGORY>
 
836
 
 
837
<CATEGORY title="Classes">
 
838
  Classes are the fundamental unit of code in C++. Naturally, we use
 
839
  them extensively. This section lists the main dos and don'ts you
 
840
  should follow when writing a class.
 
841
 
 
842
  <STYLEPOINT title="Doing Work in Constructors">
 
843
    <SUMMARY>
 
844
      In general, constructors should merely set member variables to their
 
845
      initial values.  Any complex initialization should go in an explicit
 
846
      <code>Init()</code> method.
 
847
    </SUMMARY>
 
848
    <BODY>
 
849
      <DEFINITION>
 
850
        It is possible to perform initialization in the body of the
 
851
        constructor.
 
852
      </DEFINITION>
 
853
      <PROS>
 
854
        Convenience in typing.  No need to worry about whether the
 
855
        class has been initialized or not.
 
856
      </PROS>
 
857
      <CONS>
 
858
        The problems with doing work in constructors are:
 
859
        <ul>
 
860
          <li> There is no easy way for constructors to signal errors,
 
861
               short of using exceptions (which are
 
862
               <a HREF="#Exceptions">forbidden</a>).
 
863
               </li>
 
864
          <li> If the work fails, we now have an object whose
 
865
               initialization code failed, so it may be an
 
866
               indeterminate state.
 
867
               </li>
 
868
          <li> If the work calls virtual functions, these calls will
 
869
               not get dispatched to the subclass implementations.
 
870
               Future modification to your class can quietly introduce
 
871
               this problem even if your class is not currently
 
872
               subclassed, causing much confusion.
 
873
               </li>
 
874
          <li> If someone creates a global variable of this type
 
875
               (which is against the rules, but still), the
 
876
               constructor code will be called before
 
877
               <code>main()</code>, possibly breaking some implicit
 
878
               assumptions in the constructor code.  For instance,
 
879
               
 
880
               <a href="http://google-gflags.googlecode.com/">gflags</a>
 
881
               will not yet have been initialized.
 
882
               </li>
 
883
        </ul>
 
884
      </CONS>
 
885
      <DECISION>
 
886
        If your object requires non-trivial initialization, consider
 
887
        having an explicit <code>Init()</code> method.  In particular,
 
888
        constructors should not call virtual functions, attempt to raise
 
889
        errors, access potentially uninitialized global variables, etc.
 
890
      </DECISION>
 
891
    </BODY>
 
892
  </STYLEPOINT>
 
893
 
 
894
  <STYLEPOINT title="Default Constructors">
 
895
    <SUMMARY>
 
896
      You must define a default constructor if your class defines
 
897
      member variables and has no other constructors.  Otherwise the
 
898
      compiler will do it for you, badly.
 
899
    </SUMMARY>
 
900
    <BODY>
 
901
      <DEFINITION>
 
902
        The default constructor is called when we <code>new</code> a
 
903
        class object with no arguments.  It is always called when
 
904
        calling <code>new[]</code> (for arrays).
 
905
      </DEFINITION>
 
906
      <PROS>
 
907
        Initializing structures by default, to hold "impossible"
 
908
        values, makes debugging much easier.
 
909
      </PROS>
 
910
      <CONS>
 
911
        Extra work for you, the code writer.
 
912
      </CONS>
 
913
      <DECISION>
 
914
        <p>
 
915
          If your class defines member variables and has no other
 
916
          constructors you must define a default constructor (one that
 
917
          takes no arguments). It should preferably initialize the
 
918
          object in such a way that its internal state is consistent
 
919
          and valid.
 
920
        </p>
 
921
        <p>
 
922
          The reason for this is that if you have no other
 
923
          constructors and do not define a default constructor, the
 
924
          compiler will generate one for you. This compiler
 
925
          generated constructor may not initialize your object
 
926
          sensibly.
 
927
        </p>
 
928
        <p>
 
929
          If your class inherits from an existing class but you add no
 
930
          new member variables, you are not required to have a default
 
931
          constructor.
 
932
          
 
933
        </p>
 
934
      </DECISION>
 
935
    </BODY>
 
936
  </STYLEPOINT>
 
937
 
 
938
  <STYLEPOINT title="Explicit Constructors">
 
939
    <SUMMARY>
 
940
      Use the C++ keyword <code>explicit</code> for constructors with
 
941
      one argument.
 
942
    </SUMMARY>
 
943
    <BODY>
 
944
      <DEFINITION>
 
945
        Normally, if a constructor takes one argument, it can be used
 
946
        as a conversion.  For instance, if you define
 
947
        <code>Foo::Foo(string name)</code> and then pass a string to a
 
948
        function that expects a <code>Foo</code>, the constructor will
 
949
        be called to convert the string into a <code>Foo</code> and
 
950
        will pass the <code>Foo</code> to your function for you.  This
 
951
        can be convenient but is also a source of trouble when things
 
952
        get converted and new objects created without you meaning them
 
953
        to.  Declaring a constructor <code>explicit</code> prevents it
 
954
        from being invoked implicitly as a conversion.
 
955
      </DEFINITION>
 
956
      <PROS>
 
957
        Avoids undesirable conversions.
 
958
      </PROS>
 
959
      <CONS>
 
960
        None.
 
961
      </CONS>
 
962
      <DECISION>
 
963
        <p>
 
964
          We require all single argument constructors to be
 
965
          explicit. Always put <code>explicit</code> in front of
 
966
          one-argument constructors in the class definition:
 
967
          <code>explicit Foo(string name);</code>
 
968
        </p>
 
969
        <p>
 
970
          The exception is copy constructors, which, in the rare
 
971
          cases when we allow them, should probably not be
 
972
          <code>explicit</code>.
 
973
          
 
974
          Classes that are intended to be
 
975
          transparent wrappers around other classes are also
 
976
          exceptions.
 
977
          Such exceptions should be clearly marked with comments.
 
978
        </p>
 
979
      </DECISION>
 
980
    </BODY>
 
981
  </STYLEPOINT>
 
982
 
 
983
  <STYLEPOINT title="Copy Constructors">
 
984
    <SUMMARY>
 
985
      Provide a copy constructor and assignment operator only when necessary.
 
986
      Otherwise, disable them with <code>DISALLOW_COPY_AND_ASSIGN</code>.
 
987
    </SUMMARY>
 
988
    <BODY>
 
989
      <DEFINITION>
 
990
        The copy constructor and assignment operator are used to create copies
 
991
        of objects. The copy constructor is implicitly invoked by the
 
992
        compiler in some situations, e.g. passing objects by value.
 
993
      </DEFINITION>
 
994
      <PROS>
 
995
        Copy constructors make it easy to copy objects.  STL
 
996
        containers require that all contents be copyable and
 
997
        assignable. Copy constructors can be more efficient than
 
998
        <code>CopyFrom()</code>-style workarounds because they combine
 
999
        construction with copying, the compiler can elide them in some
 
1000
        contexts, and they make it easier to avoid heap allocation.
 
1001
      </PROS>
 
1002
      <CONS>
 
1003
        Implicit copying of objects in C++ is a rich source of bugs
 
1004
        and of performance problems. It also reduces readability, as
 
1005
        it becomes hard to track which objects are being passed around
 
1006
        by value as opposed to by reference, and therefore where
 
1007
        changes to an object are reflected.
 
1008
      </CONS>
 
1009
      <DECISION>
 
1010
        <p>
 
1011
          Few classes need to be copyable. Most should have neither a
 
1012
          copy constructor nor an assignment operator. In many situations,
 
1013
          a pointer or reference will work just as well as a copied value,
 
1014
          with better performance. For example, you can pass function
 
1015
          parameters by reference or pointer instead of by value, and you can
 
1016
          store pointers rather than objects in an STL container.
 
1017
        </p>
 
1018
        <p>
 
1019
          If your class needs to be copyable, prefer providing a copy method,
 
1020
          such as <code>CopyFrom()</code> or <code>Clone()</code>, rather than
 
1021
          a copy constructor, because such methods cannot be invoked
 
1022
          implicitly. If a copy method is insufficient in your situation
 
1023
          (e.g. for performance reasons, or because your class needs to be
 
1024
          stored by value in an STL container), provide both a copy
 
1025
          constructor and assignment operator.
 
1026
        </p>
 
1027
        <p>
 
1028
          If your class does not need a copy constructor or assignment
 
1029
          operator, you must explicitly disable them.
 
1030
          
 
1031
          
 
1032
          To do so, add dummy declarations for the copy constructor and
 
1033
          assignment operator in the <code>private:</code> section of your
 
1034
          class, but do not provide any corresponding definition (so that
 
1035
          any attempt to use them results in a link error). 
 
1036
        </p>
 
1037
        <p>
 
1038
          For convenience, a <code>DISALLOW_COPY_AND_ASSIGN</code> macro
 
1039
          can be used:
 
1040
        </p>
 
1041
        <CODE_SNIPPET>
 
1042
          // A macro to disallow the copy constructor and operator= functions
 
1043
          // This should be used in the private: declarations for a class
 
1044
          #define DISALLOW_COPY_AND_ASSIGN(TypeName) \
 
1045
            TypeName(const TypeName&amp;);               \
 
1046
            void operator=(const TypeName&amp;)
 
1047
        </CODE_SNIPPET>
 
1048
        <p>
 
1049
          Then, in <code>class Foo</code>:
 
1050
        </p>
 
1051
        <CODE_SNIPPET>
 
1052
          class Foo {
 
1053
           public:
 
1054
            Foo(int f);
 
1055
            ~Foo();
 
1056
 
 
1057
           private:
 
1058
            DISALLOW_COPY_AND_ASSIGN(Foo);
 
1059
          };
 
1060
        </CODE_SNIPPET>
 
1061
        <p>
 
1062
        </p>
 
1063
        
 
1064
      </DECISION>
 
1065
    </BODY>
 
1066
  </STYLEPOINT>
 
1067
 
 
1068
  <STYLEPOINT title="Structs vs. Classes">
 
1069
    <SUMMARY>
 
1070
      Use a <code>struct</code> only for passive objects that carry data;
 
1071
      everything else is a <code>class</code>.
 
1072
    </SUMMARY>
 
1073
    <BODY>
 
1074
      <p>
 
1075
        The <code>struct</code> and <code>class</code> keywords behave
 
1076
        almost identically in C++.  We add our own semantic meanings
 
1077
        to each keyword, so you should use the appropriate keyword for
 
1078
        the data-type you're defining.
 
1079
      </p>
 
1080
      <p>
 
1081
        <code>structs</code> should be used for passive objects that carry
 
1082
        data, and may have associated constants, but lack any functionality
 
1083
        other than access/setting the data members. The
 
1084
        accessing/setting of fields is done by directly accessing the
 
1085
        fields rather than through method invocations. Methods should
 
1086
        not provide behavior but should only be used to set up the
 
1087
        data members, e.g., constructor, destructor,
 
1088
        <code>Initialize()</code>, <code>Reset()</code>,
 
1089
        <code>Validate()</code>.
 
1090
      </p>
 
1091
      <p>
 
1092
        If more functionality is required, a <code>class</code> is more
 
1093
        appropriate.  If in doubt, make it a <code>class</code>.
 
1094
      </p>
 
1095
      <p>
 
1096
        For consistency with STL, you can use <code>struct</code>
 
1097
        instead of <code>class</code> for functors and traits.
 
1098
      </p>
 
1099
      <p>
 
1100
        Note that member variables in structs and classes have
 
1101
        <a HREF="#Variable_Names">different naming rules</a>.
 
1102
      </p>
 
1103
    </BODY>
 
1104
  </STYLEPOINT>
 
1105
 
 
1106
  <STYLEPOINT title="Inheritance">
 
1107
    <SUMMARY>
 
1108
      Composition is often more appropriate than inheritance.  When
 
1109
      using inheritance, make it <code>public</code>.
 
1110
    </SUMMARY>
 
1111
    <BODY>
 
1112
      <DEFINITION>
 
1113
        When a sub-class inherits from a base class, it includes the
 
1114
        definitions of all the data and operations that the parent
 
1115
        base class defines.  In practice, inheritance is used in two
 
1116
        major ways in C++: implementation inheritance, in which
 
1117
        actual code is inherited by the child, and <A HREF="#Interfaces">interface inheritance</A>, in which only
 
1118
        method names are inherited.
 
1119
      </DEFINITION>
 
1120
      <PROS>
 
1121
        Implementation inheritance reduces code size by re-using the
 
1122
        base class code as it specializes an existing type.  Because
 
1123
        inheritance is a compile-time declaration, you and the
 
1124
        compiler can understand the operation and detect errors.
 
1125
        Interface inheritance can be used to programmatically enforce
 
1126
        that a class expose a particular API.  Again, the compiler
 
1127
        can detect errors, in this case, when a class does not define
 
1128
        a necessary method of the API.
 
1129
      </PROS>
 
1130
      <CONS>
 
1131
        For implementation inheritance, because the code implementing
 
1132
        a sub-class is spread between the base and the sub-class, it
 
1133
        can be more difficult to understand an implementation.  The
 
1134
        sub-class cannot override functions that are not virtual, so
 
1135
        the sub-class cannot change implementation.  The base class
 
1136
        may also define some data members, so that specifies physical
 
1137
        layout of the base class.
 
1138
      </CONS>
 
1139
      <DECISION>
 
1140
        <p>
 
1141
          All inheritance should be <code>public</code>.  If you want to
 
1142
          do private inheritance, you should be including an instance of
 
1143
          the base class as a member instead.
 
1144
        </p>
 
1145
        <p>
 
1146
          Do not overuse implementation inheritance.  Composition is
 
1147
          often more appropriate. Try to restrict use of inheritance
 
1148
          to the "is-a" case: <code>Bar</code> subclasses
 
1149
          <code>Foo</code> if it can reasonably be said that
 
1150
          <code>Bar</code> "is a kind of" <code>Foo</code>.
 
1151
        </p>
 
1152
        <p>
 
1153
          Make your destructor <code>virtual</code> if necessary. If
 
1154
          your class has virtual methods, its destructor
 
1155
          
 
1156
          should be virtual.
 
1157
        </p>
 
1158
        <p>
 
1159
          Limit the use of <code>protected</code> to those member
 
1160
          functions that might need to be accessed from subclasses.
 
1161
          Note that <a href="#Access_Control">data members should
 
1162
          be private</a>.
 
1163
        </p>
 
1164
        <p>
 
1165
          When redefining an inherited virtual function, explicitly
 
1166
          declare it <code>virtual</code> in the declaration of the
 
1167
          derived class.  Rationale: If <code>virtual</code> is
 
1168
          omitted, the reader has to check all ancestors of the
 
1169
          class in question to determine if the function is virtual
 
1170
          or not.
 
1171
        </p>
 
1172
      </DECISION>
 
1173
    </BODY>
 
1174
  </STYLEPOINT>
 
1175
 
 
1176
  <STYLEPOINT title="Multiple Inheritance">
 
1177
    <SUMMARY>
 
1178
      Only very rarely is multiple implementation inheritance actually
 
1179
      useful.  We allow multiple inheritance only when at most one of
 
1180
      the base classes has an implementation; all other base classes
 
1181
      must be <A HREF="#Interfaces">pure interface</A> classes tagged
 
1182
      with the <code>Interface</code> suffix.
 
1183
    </SUMMARY>
 
1184
    <BODY>
 
1185
      <DEFINITION>
 
1186
        Multiple inheritance allows a sub-class to have more than one
 
1187
        base class.  We distinguish between base classes that are
 
1188
        <em>pure interfaces</em> and those that have an
 
1189
        <em>implementation</em>.
 
1190
      </DEFINITION>
 
1191
      <PROS>
 
1192
        Multiple implementation inheritance may let you re-use even more code
 
1193
        than single inheritance (see <a HREF="#Inheritance">Inheritance</a>).
 
1194
      </PROS>
 
1195
      <CONS>
 
1196
        Only very rarely is multiple <em>implementation</em>
 
1197
        inheritance actually useful. When multiple implementation
 
1198
        inheritance seems like the solution, you can usually find a
 
1199
        different, more explicit, and cleaner solution.
 
1200
      </CONS>
 
1201
      <DECISION>
 
1202
        Multiple inheritance is allowed only when all superclasses, with the
 
1203
        possible exception of the first one, are <A HREF="#Interfaces">pure
 
1204
        interfaces</A>.  In order to ensure that they remain pure interfaces,
 
1205
        they must end with the <code>Interface</code> suffix.
 
1206
        <SUBSECTION title="Note:">
 
1207
          There is an <a HREF="#Windows_Code">exception</a> to this
 
1208
          rule on Windows.
 
1209
        </SUBSECTION>
 
1210
      </DECISION>
 
1211
    </BODY>
 
1212
  </STYLEPOINT>
 
1213
 
 
1214
  <STYLEPOINT title="Interfaces">
 
1215
    <SUMMARY>
 
1216
      Classes that satisfy certain conditions are allowed, but not required, to
 
1217
      end with an <code>Interface</code> suffix.
 
1218
    </SUMMARY>
 
1219
    <BODY>
 
1220
      <DEFINITION>
 
1221
        <p>
 
1222
        A class is a pure interface if it meets the following requirements:
 
1223
        </p>
 
1224
        <ul>
 
1225
          <li> It has only public pure virtual ("<code>= 0</code>") methods
 
1226
               and static methods (but see below for destructor).
 
1227
               </li>
 
1228
          <li> It may not have non-static data members.
 
1229
               </li>
 
1230
          <li> It need not have any constructors defined.  If a constructor is
 
1231
               provided, it must take no arguments and it must be protected.
 
1232
               </li>
 
1233
          <li> If it is a subclass, it may only be derived from classes
 
1234
               that satisfy these conditions and are tagged with the
 
1235
               <code>Interface</code> suffix.
 
1236
               </li>
 
1237
        </ul>
 
1238
        <p>
 
1239
          An interface class can never be directly instantiated
 
1240
          because of the pure virtual method(s) it declares.  To make
 
1241
          sure all implementations of the interface can be destroyed
 
1242
          correctly, they must also declare a virtual destructor (in
 
1243
          an exception to the first rule, this should not be pure).  See
 
1244
          Stroustrup, <cite>The C++ Programming Language</cite>, 3rd
 
1245
          edition, section 12.4 for details.
 
1246
        </p>
 
1247
      </DEFINITION>
 
1248
      <PROS>
 
1249
        Tagging a class with the <code>Interface</code> suffix lets
 
1250
        others know that they must not add implemented methods or non
 
1251
        static data members.  This is particularly important in the case of
 
1252
        <A HREF="#Multiple_Inheritance">multiple inheritance</A>.
 
1253
        Additionally, the interface concept is already well-understood by
 
1254
        Java programmers.
 
1255
      </PROS>
 
1256
      <CONS>
 
1257
        The <code>Interface</code> suffix lengthens the class name, which
 
1258
        can make it harder to read and understand.  Also, the interface
 
1259
        property may be considered an implementation detail that shouldn't
 
1260
        be exposed to clients.
 
1261
      </CONS>
 
1262
      <DECISION>
 
1263
        A class may end with <code>Interface</code> only if it meets the
 
1264
        above requirements.  We do not require the converse, however:
 
1265
        classes that meet the above requirements are not required to end
 
1266
        with <code>Interface</code>.
 
1267
      </DECISION>
 
1268
    </BODY>
 
1269
  </STYLEPOINT>
 
1270
 
 
1271
  <STYLEPOINT title="Operator Overloading">
 
1272
    <SUMMARY>
 
1273
      Do not overload operators except in rare, special circumstances.
 
1274
    </SUMMARY>
 
1275
    <BODY>
 
1276
      <DEFINITION>
 
1277
        A class can define that operators such as <code>+</code> and
 
1278
        <code>/</code> operate on the class as if it were a built-in
 
1279
        type.
 
1280
      </DEFINITION>
 
1281
      <PROS>
 
1282
        Can make code appear more intuitive because a class will
 
1283
        behave in the same way as built-in types (such as
 
1284
        <code>int</code>).  Overloaded operators are more playful
 
1285
        names for functions that are less-colorfully named, such as
 
1286
        <code>Equals()</code> or <code>Add()</code>.  For some
 
1287
        template functions to work correctly, you may need to define
 
1288
        operators.
 
1289
      </PROS>
 
1290
      <CONS>
 
1291
        While operator overloading can make code more intuitive, it
 
1292
        has several drawbacks:
 
1293
        <ul>
 
1294
          <li> It can fool our intuition into thinking that expensive
 
1295
               operations are cheap, built-in operations.
 
1296
               </li>
 
1297
          <li> It is much harder to find the call sites for overloaded
 
1298
               operators.  Searching for <code>Equals()</code> is much
 
1299
               easier than searching for relevant invocations of
 
1300
               <code>==</code>.
 
1301
               </li>
 
1302
          <li> Some operators work on pointers too, making it easy to
 
1303
               introduce bugs.  <code>Foo + 4</code> may do one thing,
 
1304
               while <code>&amp;Foo + 4</code> does something totally
 
1305
               different. The compiler does not complain for either of
 
1306
               these, making this very hard to debug.
 
1307
               </li>
 
1308
        </ul>
 
1309
        Overloading also has surprising ramifications.  For instance,
 
1310
        if a class overloads unary <code>operator&amp;</code>, it
 
1311
        cannot safely be forward-declared.
 
1312
      </CONS>
 
1313
      <DECISION>
 
1314
        <p>
 
1315
          In general, do not overload operators. The assignment operator
 
1316
          (<code>operator=</code>), in particular, is insidious and
 
1317
          should be avoided.  You can define functions like
 
1318
          <code>Equals()</code> and <code>CopyFrom()</code> if you
 
1319
          need them.  Likewise, avoid the dangerous
 
1320
          unary <code>operator&amp;</code> at all costs, if there's
 
1321
          any possibility the class might be forward-declared.
 
1322
        </p>
 
1323
        <p>
 
1324
          However, there may be rare cases where you need to overload
 
1325
          an operator to interoperate with templates or "standard" C++
 
1326
          classes (such as <code>operator&lt;&lt;(ostream&amp;, const
 
1327
          T&amp;)</code> for logging).  These are acceptable if fully
 
1328
          justified, but you should try to avoid these whenever
 
1329
          possible.  In particular, do not overload <code>operator==</code>
 
1330
          or <code>operator&lt;</code> just so that your class can be
 
1331
          used as a key in an STL container; instead, you should
 
1332
          create equality and comparison functor types when declaring
 
1333
          the container.
 
1334
        </p>
 
1335
        <p>
 
1336
          Some of the STL algorithms do require you to overload
 
1337
          <code>operator==</code>, and you may do so in these cases,
 
1338
          provided you document why.
 
1339
        </p>
 
1340
        <p>
 
1341
          See also <a HREF="#Copy_Constructors">Copy Constructors</a>
 
1342
          and <a HREF="#Function_Overloading">Function
 
1343
          Overloading</a>.
 
1344
        </p>
 
1345
      </DECISION>
 
1346
    </BODY>
 
1347
  </STYLEPOINT>
 
1348
 
 
1349
  <STYLEPOINT title="Access Control">
 
1350
    <SUMMARY>
 
1351
      Make data members <code>private</code>, and provide
 
1352
      access to them through accessor functions as needed (for
 
1353
      technical reasons, we allow data members of a test fixture class
 
1354
      to be <code>protected</code> when using
 
1355
      
 
1356
      <A HREF="http://code.google.com/p/googletest/">
 
1357
      Google Test</A>). Typically a variable would be
 
1358
      called <code>foo_</code> and the accessor function
 
1359
      <code>foo()</code>.  You may also want a mutator function
 
1360
      <code>set_foo()</code>.
 
1361
      Exception: <code>static const</code> data members (typically
 
1362
      called <code>kFoo</code>) need not be <code>private</code>.
 
1363
    </SUMMARY>
 
1364
    <BODY>
 
1365
      <p>
 
1366
        The definitions of accessors are usually inlined in the header
 
1367
        file.
 
1368
      </p>
 
1369
      <p>
 
1370
        See also <a HREF="#Inheritance">Inheritance</a> and <a HREF="#Function_Names">Function Names</a>.
 
1371
      </p>
 
1372
    </BODY>
 
1373
  </STYLEPOINT>
 
1374
 
 
1375
  <STYLEPOINT title="Declaration Order">
 
1376
    <SUMMARY>
 
1377
      Use the specified order of declarations within a class:
 
1378
      <code>public:</code> before <code>private:</code>, methods
 
1379
      before data members (variables), etc.
 
1380
    </SUMMARY>
 
1381
    <BODY>
 
1382
      <p>
 
1383
        Your class definition should start with its <code>public:</code>
 
1384
        section, followed by its <code>protected:</code> section and
 
1385
        then its <code>private:</code> section. If any of these sections
 
1386
        are empty, omit them.
 
1387
      </p>
 
1388
      <p>
 
1389
        Within each section, the declarations generally should be in
 
1390
        the following order:
 
1391
      </p>
 
1392
      <ul>
 
1393
        <li> Typedefs and Enums</li>
 
1394
        <li> Constants (<code>static const</code> data members)</li>
 
1395
        <li> Constructors</li>
 
1396
        <li> Destructor</li>
 
1397
        <li> Methods, including static methods</li>
 
1398
        <li> Data Members (except <code>static const</code> data members)</li>
 
1399
      </ul>
 
1400
      <p>
 
1401
        Friend declarations should always be in the private section, and
 
1402
        the <code>DISALLOW_COPY_AND_ASSIGN</code> macro invocation
 
1403
        should be at the end of the <code>private:</code> section. It
 
1404
        should be the last thing in the class. See <a HREF="#Copy_Constructors">Copy Constructors</a>.
 
1405
      </p>
 
1406
      <p>
 
1407
        Method definitions in the corresponding <code>.cc</code> file
 
1408
        should be the same as the declaration order, as much as possible.
 
1409
      </p>
 
1410
      <p>
 
1411
        Do not put large method definitions inline in the class
 
1412
        definition.  Usually, only trivial or performance-critical,
 
1413
        and very short, methods may be defined inline.  See <a HREF="#Inline_Functions">Inline Functions</a> for more
 
1414
        details.
 
1415
      </p>
 
1416
    </BODY>
 
1417
  </STYLEPOINT>
 
1418
 
 
1419
  <STYLEPOINT title="Write Short Functions">
 
1420
    <SUMMARY>
 
1421
      Prefer small and focused functions.
 
1422
    </SUMMARY>
 
1423
    <BODY>
 
1424
      <p>
 
1425
        We recognize that long functions are sometimes appropriate, so
 
1426
        no hard limit is placed on functions length. If a function
 
1427
        exceeds about 40 lines, think about whether it can be broken
 
1428
        up without harming the structure of the program.
 
1429
      </p>
 
1430
      <p>
 
1431
        Even if your long function works perfectly now, someone
 
1432
        modifying it in a few months may add new behavior. This could
 
1433
        result in bugs that are hard to find.  Keeping your functions
 
1434
        short and simple makes it easier for other people to read and
 
1435
        modify your code.
 
1436
      </p>
 
1437
      <p>
 
1438
        You could find long and complicated functions when working
 
1439
        with
 
1440
        
 
1441
        some
 
1442
        code.  Do not be intimidated by modifying existing
 
1443
        code: if working with such a function proves to be difficult,
 
1444
        you find that errors are hard to debug, or you want to use a
 
1445
        piece of it in several different contexts, consider breaking
 
1446
        up the function into smaller and more manageable pieces.
 
1447
      </p>
 
1448
    </BODY>
 
1449
  </STYLEPOINT>
 
1450
</CATEGORY>
 
1451
 
 
1452
<CATEGORY title="Google-Specific Magic">
 
1453
  
 
1454
  <p>
 
1455
    There are various tricks and utilities that we use to make C++
 
1456
    code more robust, and various ways we use C++ that may differ from
 
1457
    what you see elsewhere.
 
1458
  </p>
 
1459
 
 
1460
  
 
1461
 
 
1462
  <STYLEPOINT title="Smart Pointers">
 
1463
    
 
1464
    <SUMMARY>
 
1465
      If you actually need pointer semantics, <code>scoped_ptr</code>
 
1466
      is great.  You should only use <code>std::tr1::shared_ptr</code>
 
1467
      with a non-const referent when it is truly necessary to share ownership
 
1468
      of an object (e.g. inside an STL container). You should never use
 
1469
      <code>auto_ptr</code>.
 
1470
    </SUMMARY>
 
1471
    <BODY>
 
1472
      <DEFINITION>
 
1473
        "Smart" pointers are objects that act like pointers, but automate
 
1474
        management of the underlying memory. 
 
1475
      </DEFINITION>
 
1476
      <PROS>
 
1477
        Smart pointers are extremely useful for preventing memory leaks, and
 
1478
        are essential for writing exception-safe code. They also formalize
 
1479
        and document the ownership of dynamically allocated memory.
 
1480
      </PROS>
 
1481
      <CONS>
 
1482
        We prefer designs in which objects have single, fixed owners. Smart
 
1483
        pointers which enable sharing or transfer of ownership can act as a
 
1484
        tempting alternative to a careful design of ownership semantics,
 
1485
        leading to confusing code and even bugs in which memory is never
 
1486
        deleted. The semantics of smart pointers (especially
 
1487
        <code>auto_ptr</code>) can be nonobvious and confusing. The
 
1488
        exception-safety benefits of smart pointers are not decisive, since
 
1489
        we do not allow exceptions.
 
1490
      </CONS>
 
1491
      <DECISION>
 
1492
        <dl>
 
1493
          <dt><code>scoped_ptr</code></dt>
 
1494
          <dd>Straightforward and risk-free. Use wherever appropriate.</dd>
 
1495
          <dt><code>auto_ptr</code></dt>
 
1496
          <dd>Confusing and bug-prone ownership-transfer semantics. Do not use.
 
1497
            </dd>
 
1498
          <dt><code>shared_ptr</code></dt>
 
1499
          <dd>
 
1500
          Safe with const referents (i.e. <code>shared_ptr&lt;const
 
1501
          T&gt;</code>). Reference-counted pointers with non-const referents
 
1502
          can occasionally be the best design, but try to rewrite with single
 
1503
          owners where possible. 
 
1504
          </dd>
 
1505
        </dl>
 
1506
      </DECISION>
 
1507
    </BODY>
 
1508
  </STYLEPOINT>
 
1509
 
 
1510
  <STYLEPOINT title="cpplint">
 
1511
    <SUMMARY>
 
1512
      Use
 
1513
      <code>cpplint.py</code>
 
1514
      to detect style errors.
 
1515
    </SUMMARY>
 
1516
    <BODY>
 
1517
      <p>
 
1518
        <code>cpplint.py</code>
 
1519
        is a tool that reads a source file and
 
1520
        identifies many style errors.  It is not perfect, and has both false
 
1521
        positives and false negatives, but it is still a valuable tool.  False
 
1522
        positives can be ignored by putting <code>// NOLINT</code> at
 
1523
        the end of the line.
 
1524
      </p>
 
1525
      
 
1526
      <p>
 
1527
        Some projects have instructions on how to run <code>cpplint.py</code>
 
1528
        from their project tools. If the project you are contributing to does
 
1529
        not, you can download <A HREF="http://google-styleguide.googlecode.com/svn/trunk/cpplint/cpplint.py"><code>cpplint.py</code></A> separately.
 
1530
      </p>
 
1531
    </BODY>
 
1532
  </STYLEPOINT>
 
1533
 
 
1534
  
 
1535
</CATEGORY>
 
1536
 
 
1537
<CATEGORY title="Other C++ Features">
 
1538
  <STYLEPOINT title="Reference Arguments">
 
1539
    <SUMMARY>
 
1540
      All parameters passed by reference must be labeled
 
1541
      <code>const</code>.
 
1542
    </SUMMARY>
 
1543
    <BODY>
 
1544
      <DEFINITION>
 
1545
        In C, if a function needs to modify a variable, the
 
1546
        parameter must use a pointer, eg <code>int foo(int
 
1547
        *pval)</code>.  In C++, the function can alternatively
 
1548
        declare a reference parameter: <code>int foo(int
 
1549
        &amp;val)</code>.
 
1550
      </DEFINITION>
 
1551
      <PROS>
 
1552
        Defining a parameter as reference avoids ugly code like
 
1553
        <code>(*pval)++</code>.  Necessary for some applications like
 
1554
        copy constructors.  Makes it clear, unlike with pointers, that
 
1555
        <code>NULL</code> is not a possible value.
 
1556
      </PROS>
 
1557
      <CONS>
 
1558
        References can be confusing, as they have value syntax but
 
1559
        pointer semantics.
 
1560
      </CONS>
 
1561
      <DECISION>
 
1562
        <p>
 
1563
          Within function parameter lists all references must be
 
1564
          <code>const</code>:
 
1565
        </p>
 
1566
        <CODE_SNIPPET>
 
1567
          void Foo(const string &amp;in, string *out);
 
1568
        </CODE_SNIPPET>
 
1569
        <p>
 
1570
          In fact it is a very strong convention in Google code that input
 
1571
          arguments are values or <code>const</code> references while
 
1572
          output arguments are pointers.  Input parameters may be
 
1573
          <code>const</code> pointers, but we never allow
 
1574
          non-<code>const</code> reference parameters.
 
1575
        </p>
 
1576
        <p>
 
1577
          One case when you might want an input parameter to be a
 
1578
          <code>const</code> pointer is if you want to emphasize that the
 
1579
          argument is not copied, so it must exist for the lifetime of the
 
1580
          object; it is usually best to document this in comments as
 
1581
          well.  STL adapters such as <code>bind2nd</code> and
 
1582
          <code>mem_fun</code> do not permit reference parameters, so
 
1583
          you must declare functions with pointer parameters in these
 
1584
          cases, too.
 
1585
        </p>
 
1586
      </DECISION>
 
1587
    </BODY>
 
1588
  </STYLEPOINT>
 
1589
 
 
1590
  <STYLEPOINT title="Function Overloading">
 
1591
    <SUMMARY>
 
1592
      Use overloaded functions (including constructors) only if a
 
1593
      reader looking at a call site can get a good idea of what is
 
1594
      happening without having to first figure out exactly which
 
1595
      overload is being called.
 
1596
    </SUMMARY>
 
1597
    <BODY>
 
1598
      <DEFINITION>
 
1599
        <p>
 
1600
          You may write a function that takes a
 
1601
          <code>const string&amp;</code> and overload it with another that
 
1602
          takes <code>const char*</code>.
 
1603
        </p>
 
1604
        <CODE_SNIPPET>
 
1605
          class MyClass {
 
1606
           public:
 
1607
            void Analyze(const string &amp;text);
 
1608
            void Analyze(const char *text, size_t textlen);
 
1609
          };
 
1610
        </CODE_SNIPPET>
 
1611
      </DEFINITION>
 
1612
      <PROS>
 
1613
        Overloading can make code more intuitive by allowing an
 
1614
        identically-named function to take different arguments.  It
 
1615
        may be necessary for templatized code, and it can be
 
1616
        convenient for Visitors.
 
1617
      </PROS>
 
1618
      <CONS>
 
1619
        If a function is overloaded by the argument types alone, a
 
1620
        reader may have to understand C++'s complex matching rules in
 
1621
        order to tell what's going on.  Also many people are confused
 
1622
        by the semantics of inheritance if a derived class overrides
 
1623
        only some of the variants of a function.
 
1624
      </CONS>
 
1625
      <DECISION>
 
1626
        If you want to overload a function, consider qualifying the
 
1627
        name with some information about the arguments, e.g.,
 
1628
        <code>AppendString()</code>, <code>AppendInt()</code> rather
 
1629
        than just <code>Append()</code>.
 
1630
        
 
1631
      </DECISION>
 
1632
    </BODY>
 
1633
  </STYLEPOINT>
 
1634
 
 
1635
  <STYLEPOINT title="Default Arguments">
 
1636
    <SUMMARY>
 
1637
      We do not allow default function parameters, except in
 
1638
      a few uncommon situations explained below.
 
1639
    </SUMMARY>
 
1640
    <BODY>
 
1641
      <PROS>
 
1642
        Often you have a function that uses lots of default values,
 
1643
        but occasionally you want to override the defaults.  Default
 
1644
        parameters allow an easy way to do this without having to
 
1645
        define many functions for the rare exceptions.
 
1646
      </PROS>
 
1647
      <CONS>
 
1648
        People often figure out how to use an
 
1649
        API by looking at existing code that uses it.
 
1650
        Default parameters are more difficult to maintain because
 
1651
        copy-and-paste from previous code may not reveal all the
 
1652
        parameters.  Copy-and-pasting of code segments can cause major
 
1653
        problems when the default arguments are not appropriate for
 
1654
        the new code.
 
1655
      </CONS>
 
1656
      <DECISION>
 
1657
        <p>
 
1658
          Except as described below, we require all arguments to be
 
1659
          explicitly specified, to force programmers to consider the API
 
1660
          and the values they are passing for each argument rather than
 
1661
          silently accepting defaults they may not be aware of.
 
1662
        </p>
 
1663
        <p>
 
1664
          One specific exception is when default arguments are used to
 
1665
          simulate variable-length argument lists.
 
1666
        </p>
 
1667
        <CODE_SNIPPET>
 
1668
          // Support up to 4 params by using a default empty AlphaNum.
 
1669
          string StrCat(const AlphaNum &amp;a,
 
1670
                        const AlphaNum &amp;b = gEmptyAlphaNum,
 
1671
                        const AlphaNum &amp;c = gEmptyAlphaNum,
 
1672
                        const AlphaNum &amp;d = gEmptyAlphaNum);
 
1673
        </CODE_SNIPPET>
 
1674
      </DECISION>
 
1675
    </BODY>
 
1676
  </STYLEPOINT>
 
1677
 
 
1678
  <STYLEPOINT title="Variable-Length Arrays and alloca()">
 
1679
    <SUMMARY>
 
1680
      We do not allow variable-length arrays or <code>alloca()</code>.
 
1681
    </SUMMARY>
 
1682
    <BODY>
 
1683
      <PROS>
 
1684
        Variable-length arrays have natural-looking syntax.  Both
 
1685
        variable-length arrays and <code>alloca()</code> are very
 
1686
        efficient.
 
1687
      </PROS>
 
1688
      <CONS>
 
1689
        Variable-length arrays and alloca are not part of Standard
 
1690
        C++.  More importantly, they allocate a data-dependent amount
 
1691
        of stack space that can trigger difficult-to-find memory
 
1692
        overwriting bugs: "It ran fine on my machine, but dies
 
1693
        mysteriously in production".
 
1694
      </CONS>
 
1695
      
 
1696
      <DECISION>
 
1697
        Use a safe allocator instead, such as
 
1698
        <code>scoped_ptr</code>/<code>scoped_array</code>.
 
1699
      </DECISION>
 
1700
    </BODY>
 
1701
  </STYLEPOINT>
 
1702
 
 
1703
  <STYLEPOINT title="Friends">
 
1704
    <SUMMARY>
 
1705
      We allow use of <code>friend</code> classes and functions,
 
1706
      within reason.
 
1707
    </SUMMARY>
 
1708
    <BODY>
 
1709
      <p>
 
1710
        Friends should usually be defined in the same file so that the
 
1711
        reader does not have to look in another file to find uses of
 
1712
        the private members of a class.  A common use of
 
1713
        <code>friend</code> is to have a <code>FooBuilder</code> class
 
1714
        be a friend of <code>Foo</code> so that it can construct the
 
1715
        inner state of <code>Foo</code> correctly, without exposing
 
1716
        this state to the world.  In some cases it may be useful to
 
1717
        make a unittest class a friend of the class it tests.
 
1718
      </p>
 
1719
      <p>
 
1720
        Friends extend, but do not break, the encapsulation
 
1721
        boundary of a class.  In some cases this is better than making
 
1722
        a member public when you want to give only one other class
 
1723
        access to it.  However, most classes should interact with
 
1724
        other classes solely through their public members.
 
1725
      </p>
 
1726
    </BODY>
 
1727
  </STYLEPOINT>
 
1728
 
 
1729
  <STYLEPOINT title="Exceptions">
 
1730
    <SUMMARY>
 
1731
      We do not use C++ exceptions.
 
1732
    </SUMMARY>
 
1733
    <BODY>
 
1734
      <PROS>
 
1735
        <ul>
 
1736
          <li>Exceptions allow higher levels of an application to
 
1737
          decide how to handle "can't happen" failures in deeply
 
1738
          nested functions, without the obscuring and error-prone
 
1739
          bookkeeping of error codes.</li>
 
1740
 
 
1741
          
 
1742
 
 
1743
          <li>Exceptions are used by most other modern
 
1744
          languages.  Using them in C++ would make it more consistent with
 
1745
          Python, Java, and the C++ that others are familiar with.</li>
 
1746
 
 
1747
          <li>Some third-party C++ libraries use exceptions, and turning
 
1748
          them off internally makes it harder to integrate with those
 
1749
          libraries.</li>
 
1750
 
 
1751
          <li>Exceptions are the only way for a constructor to fail.
 
1752
          We can simulate this with a factory function or an
 
1753
          <code>Init()</code> method, but these require heap
 
1754
          allocation or a new "invalid" state, respectively.</li>
 
1755
 
 
1756
          <li>Exceptions are really handy in testing frameworks.</li>
 
1757
        </ul>
 
1758
      </PROS>
 
1759
      <CONS>
 
1760
        <ul>
 
1761
          <li>When you add a <code>throw</code> statement to an existing
 
1762
          function, you must examine all of its transitive callers. Either
 
1763
          they must make at least the basic exception safety guarantee, or
 
1764
          they must never catch the exception and be happy with the
 
1765
          program terminating as a result. For instance, if
 
1766
          <code>f()</code> calls <code>g()</code> calls
 
1767
          <code>h()</code>, and <code>h</code> throws an exception
 
1768
          that <code>f</code> catches, <code>g</code> has to be
 
1769
          careful or it may not clean up properly.</li>
 
1770
 
 
1771
          <li>More generally, exceptions make the control flow of
 
1772
          programs difficult to evaluate by looking at code: functions
 
1773
          may return in places you don't expect. This causes
 
1774
          maintainability and debugging difficulties. You can minimize
 
1775
          this cost via some rules on how and where exceptions can be
 
1776
          used, but at the cost of more that a developer needs to know
 
1777
          and understand.</li>
 
1778
 
 
1779
          <li>Exception safety requires both RAII and different coding
 
1780
          practices. Lots of supporting machinery is needed to make
 
1781
          writing correct exception-safe code easy. Further, to avoid
 
1782
          requiring readers to understand the entire call graph,
 
1783
          exception-safe code must isolate logic that writes to
 
1784
          persistent state into a "commit" phase. This will have both
 
1785
          benefits and costs (perhaps where you're forced to obfuscate
 
1786
          code to isolate the commit). Allowing exceptions would force
 
1787
          us to always pay those costs even when they're not worth
 
1788
          it.</li>
 
1789
 
 
1790
          <li>Turning on exceptions adds data to each binary produced,
 
1791
          increasing compile time (probably slightly) and possibly
 
1792
          increasing address space pressure.
 
1793
          </li>
 
1794
 
 
1795
          <li>The availability of exceptions may encourage developers
 
1796
          to throw them when they are not appropriate or recover from
 
1797
          them when it's not safe to do so. For example, invalid user
 
1798
          input should not cause exceptions to be thrown. We would
 
1799
          need to make the style guide even longer to document these
 
1800
          restrictions!</li>
 
1801
        </ul>
 
1802
      </CONS>
 
1803
      <DECISION>
 
1804
        <p>
 
1805
          On their face, the benefits of using exceptions outweigh the
 
1806
          costs, especially in new projects.  However, for existing code,
 
1807
          the introduction of exceptions has implications on all dependent
 
1808
          code.  If exceptions can be propagated beyond a new project, it
 
1809
          also becomes problematic to integrate the new project into
 
1810
          existing exception-free code.  Because most existing C++ code at
 
1811
          Google is not prepared to deal with exceptions, it is
 
1812
          comparatively difficult to adopt new code that generates
 
1813
          exceptions.
 
1814
        </p>
 
1815
        <p>
 
1816
          Given that Google's existing code is not exception-tolerant, the
 
1817
          costs of using exceptions are somewhat greater than the costs in
 
1818
          a new project.  The conversion process would be slow and
 
1819
          error-prone.  We don't believe that the available alternatives to
 
1820
          exceptions, such as error codes and assertions, introduce a
 
1821
          significant burden.
 
1822
          
 
1823
        </p>
 
1824
        <p>
 
1825
          Our advice against using exceptions is not predicated on
 
1826
          philosophical or moral grounds, but practical ones.
 
1827
          
 
1828
          Because we'd like to use our open-source
 
1829
          projects at Google and it's difficult to do so if those projects
 
1830
          use exceptions, we need to advise against exceptions in Google
 
1831
          open-source projects as well.
 
1832
          Things would probably be different if we had to do it all over
 
1833
          again from scratch.
 
1834
        </p>
 
1835
        <p>
 
1836
          There is an <a HREF="#Windows_Code">exception</a> to this
 
1837
          rule (no pun intended) for Windows code.
 
1838
        </p>
 
1839
      </DECISION>
 
1840
    </BODY>
 
1841
  </STYLEPOINT>
 
1842
 
 
1843
  <STYLEPOINT title="Run-Time Type Information (RTTI)">
 
1844
    <SUMMARY>
 
1845
      We do not use Run Time Type Information (RTTI).
 
1846
    </SUMMARY>
 
1847
    <BODY>
 
1848
      <DEFINITION>
 
1849
        RTTI allows a programmer to query the C++ class of an
 
1850
        object at run time.
 
1851
      </DEFINITION>
 
1852
      <PROS>
 
1853
        <p>
 
1854
          It is useful in some unittests. For example, it is useful in
 
1855
          tests of factory classes where the test has to verify that a
 
1856
          newly created object has the expected dynamic type.
 
1857
        </p>
 
1858
        <p>
 
1859
          In rare circumstances, it is useful even outside of
 
1860
          tests.
 
1861
        </p>
 
1862
      </PROS>
 
1863
      <CONS>
 
1864
        A query of type during run-time typically means a
 
1865
        design problem.  If you need to know the type of an
 
1866
        object at runtime, that is often an indication that
 
1867
        you should reconsider the design of your class.
 
1868
      </CONS>
 
1869
      <DECISION>
 
1870
        <p>
 
1871
          Do not use RTTI, except in unittests.  If you find yourself
 
1872
          in need of writing code that behaves differently based on
 
1873
          the class of an object, consider one of the alternatives to
 
1874
          querying the type.
 
1875
        </p>
 
1876
        <p>
 
1877
          Virtual methods are the preferred way of executing different
 
1878
          code paths depending on a specific subclass type.  This puts
 
1879
          the work within the object itself.
 
1880
        </p>
 
1881
        <p>
 
1882
          If the work belongs outside the object and instead in some
 
1883
          processing code, consider a double-dispatch solution, such
 
1884
          as the Visitor design pattern.  This allows a facility
 
1885
          outside the object itself to determine the type of class
 
1886
          using the built-in type system.
 
1887
        </p>
 
1888
        <p>
 
1889
          If you think you truly cannot use those ideas,
 
1890
          
 
1891
          you may use RTTI.  But think twice
 
1892
          about it.  :-)  Then think twice again.
 
1893
          Do not hand-implement an RTTI-like workaround. The arguments
 
1894
          against RTTI apply just as much to workarounds like class
 
1895
          hierarchies with type tags.
 
1896
        </p>
 
1897
      </DECISION>
 
1898
    </BODY>
 
1899
  </STYLEPOINT>
 
1900
 
 
1901
  <STYLEPOINT title="Casting">
 
1902
    <SUMMARY>
 
1903
      Use C++ casts like <code>static_cast&lt;&gt;()</code>.  Do not use
 
1904
      other cast formats like <code>int y = (int)x;</code> or
 
1905
      <code>int y = int(x);</code>.
 
1906
    </SUMMARY>
 
1907
    <BODY>
 
1908
      <DEFINITION>
 
1909
        C++ introduced a different cast system from C that
 
1910
        distinguishes the types of cast operations.
 
1911
      </DEFINITION>
 
1912
      <PROS>
 
1913
        The problem with C casts is the ambiguity of the operation;
 
1914
        sometimes you are doing a <em>conversion</em> (e.g.,
 
1915
        <code>(int)3.5</code>) and sometimes you are doing a
 
1916
        <em>cast</em> (e.g., <code>(int)"hello"</code>); C++ casts
 
1917
        avoid this.  Additionally C++ casts are more visible when
 
1918
        searching for them.
 
1919
      </PROS>
 
1920
      <CONS>
 
1921
        The syntax is nasty.
 
1922
      </CONS>
 
1923
      <DECISION>
 
1924
        <p>
 
1925
          Do not use C-style casts.  Instead, use these C++-style
 
1926
          casts.
 
1927
          
 
1928
        </p>
 
1929
        <ul>
 
1930
          
 
1931
          <li> Use <code>static_cast</code> as the equivalent of a
 
1932
               C-style cast that does value conversion, or when you need to explicitly up-cast
 
1933
               a pointer from a class to its superclass.
 
1934
               </li>
 
1935
          <li> Use <code>const_cast</code> to remove the <code>const</code>
 
1936
               qualifier (see <a HREF="#Use_of_const">const</a>).
 
1937
               </li>
 
1938
          
 
1939
          
 
1940
          <li> Use <code>reinterpret_cast</code> to do unsafe
 
1941
               conversions of pointer types to and from integer and
 
1942
               other pointer types. Use this only if you know what you are
 
1943
               doing and you understand the aliasing issues.
 
1944
               
 
1945
               </li>
 
1946
          <li> Do not use <code>dynamic_cast</code> except in test code.
 
1947
               If you need to know type information at runtime in this way
 
1948
               outside of a unittest, you probably have a <A HREF="#Run-Time_Type_Information__RTTI_">design
 
1949
               flaw</A>.
 
1950
               </li>
 
1951
        </ul>
 
1952
      </DECISION>
 
1953
    </BODY>
 
1954
  </STYLEPOINT>
 
1955
 
 
1956
  <STYLEPOINT title="Streams">
 
1957
    <SUMMARY>
 
1958
      Use streams only for logging.
 
1959
    </SUMMARY>
 
1960
    <BODY>
 
1961
      <DEFINITION>
 
1962
        Streams are a replacement for <code>printf()</code> and
 
1963
        <code>scanf()</code>.
 
1964
      </DEFINITION>
 
1965
      <PROS>
 
1966
        With streams, you do not need to know the type of the object
 
1967
        you are printing.  You do not have problems with format
 
1968
        strings not matching the argument list.  (Though with gcc, you
 
1969
        do not have that problem with <code>printf</code> either.)  Streams
 
1970
        have automatic constructors and destructors that open and close the
 
1971
        relevant files.
 
1972
      </PROS>
 
1973
      <CONS>
 
1974
        Streams make it difficult to do functionality like
 
1975
        <code>pread()</code>.  Some formatting (particularly the common
 
1976
        format string idiom <code>%.*s</code>) is difficult if not
 
1977
        impossible to do efficiently using streams without using
 
1978
        <code>printf</code>-like hacks.  Streams do not support operator
 
1979
        reordering (the <code>%1s</code> directive), which is helpful for
 
1980
        internationalization.
 
1981
      </CONS>
 
1982
      <DECISION>
 
1983
        
 
1984
        <p>
 
1985
          Do not use streams, except where required by a logging interface.
 
1986
          Use <code>printf</code>-like routines instead.
 
1987
        </p>
 
1988
        <p>
 
1989
          There are various pros and cons to using streams, but in
 
1990
          this case, as in many other cases, consistency trumps the
 
1991
          debate.  Do not use streams in your code.
 
1992
        </p>
 
1993
 
 
1994
        <SUBSECTION title="Extended Discussion">
 
1995
          <p>
 
1996
            There has been debate on this issue, so this explains the
 
1997
            reasoning in greater depth.  Recall the Only One Way
 
1998
            guiding principle: we want to make sure that whenever we
 
1999
            do a certain type of I/O, the code looks the same in all
 
2000
            those places.  Because of this, we do not want to allow
 
2001
            users to decide between using streams or using
 
2002
            <code>printf</code> plus Read/Write/etc.  Instead, we should
 
2003
            settle on one or the other.  We made an exception for logging
 
2004
            because it is a pretty specialized application, and for
 
2005
            historical reasons.
 
2006
          </p>
 
2007
          <p>
 
2008
            Proponents of streams have argued that streams are the obvious
 
2009
            choice of the two, but the issue is not actually so clear.  For
 
2010
            every advantage of streams they point out, there is an
 
2011
            equivalent disadvantage.  The biggest advantage is that
 
2012
            you do not need to know the type of the object to be
 
2013
            printing.  This is a fair point.  But, there is a
 
2014
            downside: you can easily use the wrong type, and the
 
2015
            compiler will not warn you.  It is easy to make this
 
2016
            kind of mistake without knowing when using streams.
 
2017
          </p>
 
2018
          <CODE_SNIPPET>
 
2019
            cout &lt;&lt; this;  // Prints the address
 
2020
            cout &lt;&lt; *this;  // Prints the contents
 
2021
          </CODE_SNIPPET>
 
2022
          <p>
 
2023
            The compiler does not generate an error because
 
2024
            <code>&lt;&lt;</code> has been overloaded.  We discourage
 
2025
            overloading for just this reason.
 
2026
          </p>
 
2027
          <p>
 
2028
            Some say <code>printf</code> formatting is ugly and hard to
 
2029
            read, but streams are often no better.  Consider the following
 
2030
            two fragments, both with the same typo.  Which is easier to
 
2031
            discover?
 
2032
          </p>
 
2033
          <CODE_SNIPPET>
 
2034
             cerr &lt;&lt; "Error connecting to '" &lt;&lt; foo-&gt;bar()-&gt;hostname.first
 
2035
                  &lt;&lt; ":" &lt;&lt; foo-&gt;bar()-&gt;hostname.second &lt;&lt; ": " &lt;&lt; strerror(errno);
 
2036
 
 
2037
             fprintf(stderr, "Error connecting to '%s:%u: %s",
 
2038
                     foo-&gt;bar()-&gt;hostname.first, foo-&gt;bar()-&gt;hostname.second,
 
2039
                     strerror(errno));
 
2040
          </CODE_SNIPPET>
 
2041
          <p>
 
2042
            And so on and so forth for any issue you might bring up.
 
2043
            (You could argue, "Things would be better with the right
 
2044
            wrappers," but if it is true for one scheme, is it not
 
2045
            also true for the other?  Also, remember the goal is to
 
2046
            make the language smaller, not add yet more machinery that
 
2047
            someone has to learn.)
 
2048
          </p>
 
2049
          <p>
 
2050
            Either path would yield different advantages and
 
2051
            disadvantages, and there is not a clearly superior
 
2052
            solution.  The simplicity doctrine mandates we settle on
 
2053
            one of them though, and the majority decision was on
 
2054
            <code>printf</code> + <code>read</code>/<code>write</code>.
 
2055
          </p>
 
2056
        </SUBSECTION>
 
2057
      </DECISION>
 
2058
    </BODY>
 
2059
  </STYLEPOINT>
 
2060
 
 
2061
  <STYLEPOINT title="Preincrement and Predecrement">
 
2062
    <SUMMARY>
 
2063
      Use prefix form (<code>++i</code>) of the increment and
 
2064
      decrement operators with iterators and other template objects.
 
2065
    </SUMMARY>
 
2066
    <BODY>
 
2067
      <DEFINITION>
 
2068
        When a variable is incremented (<code>++i</code> or
 
2069
        <code>i++</code>) or decremented (<code>--i</code> or
 
2070
        <code>i--</code>) and the value of the expression is not used,
 
2071
        one must decide whether to preincrement (decrement) or
 
2072
        postincrement (decrement).
 
2073
      </DEFINITION>
 
2074
      <PROS>
 
2075
        When the return value is ignored, the "pre" form
 
2076
        (<code>++i</code>) is never less efficient than the "post"
 
2077
        form (<code>i++</code>), and is often more efficient.  This is
 
2078
        because post-increment (or decrement) requires a copy of
 
2079
        <code>i</code> to be made, which is the value of the
 
2080
        expression.  If <code>i</code> is an iterator or other
 
2081
        non-scalar type, copying <code>i</code> could be expensive.
 
2082
        Since the two types of increment behave the same when the
 
2083
        value is ignored, why not just always pre-increment?
 
2084
      </PROS>
 
2085
      <CONS>
 
2086
        The tradition developed, in C, of using post-increment when
 
2087
        the expression value is not used, especially in <code>for</code>
 
2088
        loops.  Some find post-increment easier to read, since the
 
2089
        "subject" (<code>i</code>) precedes the "verb" (<code>++</code>),
 
2090
        just like in English.
 
2091
      </CONS>
 
2092
      <DECISION>
 
2093
        For simple scalar (non-object) values there is no reason to
 
2094
        prefer one form and we allow either.  For iterators and other
 
2095
        template types, use pre-increment.
 
2096
      </DECISION>
 
2097
    </BODY>
 
2098
  </STYLEPOINT>
 
2099
 
 
2100
  <STYLEPOINT title="Use of const">
 
2101
    <SUMMARY>
 
2102
      We strongly recommend that you use <code>const</code> whenever
 
2103
      it makes sense to do so.
 
2104
    </SUMMARY>
 
2105
    <BODY>
 
2106
      <DEFINITION>
 
2107
        Declared variables and parameters can be preceded by the
 
2108
        keyword <code>const</code> to indicate the variables are not
 
2109
        changed (e.g., <code>const int foo</code>).  Class functions
 
2110
        can have the <code>const</code> qualifier to indicate the
 
2111
        function does not change the state of the class member
 
2112
        variables (e.g., <code>class Foo { int Bar(char c) const;
 
2113
        };</code>).
 
2114
      </DEFINITION>
 
2115
      <PROS>
 
2116
        Easier for people to understand how variables are being used.
 
2117
        Allows the compiler to do better type checking, and,
 
2118
        conceivably, generate better code.  Helps people convince
 
2119
        themselves of program correctness because they know the
 
2120
        functions they call are limited in how they can modify your
 
2121
        variables.  Helps people know what functions are safe to use
 
2122
        without locks in multi-threaded programs.
 
2123
      </PROS>
 
2124
      <CONS>
 
2125
        <code>const</code> is viral: if you pass a <code>const</code>
 
2126
        variable to a function, that function must have <code>const</code>
 
2127
        in its prototype (or the variable will need a
 
2128
        <code>const_cast</code>).  This can be a particular problem
 
2129
        when calling library functions.
 
2130
      </CONS>
 
2131
      <DECISION>
 
2132
        <p>
 
2133
          <code>const</code> variables, data members, methods and
 
2134
          arguments add a level of compile-time type checking; it
 
2135
          is better to detect errors as soon as possible.
 
2136
          Therefore we strongly recommend that you use
 
2137
          <code>const</code> whenever it makes sense to do so:
 
2138
        </p>
 
2139
        <ul>
 
2140
          <li> If a function does not modify an argument passed by
 
2141
               reference or by pointer, that argument should be
 
2142
               <code>const</code>.
 
2143
               </li>
 
2144
          <li> Declare methods to be <code>const</code> whenever
 
2145
               possible. Accessors should almost always be
 
2146
               <code>const</code>. Other methods should be const if they do
 
2147
               not modify any data members, do not call any
 
2148
               non-<code>const</code> methods, and do not return a
 
2149
               non-<code>const</code> pointer or non-<code>const</code>
 
2150
               reference to a data member.
 
2151
               </li>
 
2152
          <li> Consider making data members <code>const</code>
 
2153
               whenever they do not need to be modified after
 
2154
               construction.
 
2155
               </li>
 
2156
        </ul>
 
2157
        <p>
 
2158
          However, do not go crazy with <code>const</code>.  Something like
 
2159
          <code>const int * const * const x;</code> is likely
 
2160
          overkill, even if it accurately describes how const x is.
 
2161
          Focus on what's really useful to know: in this case,
 
2162
          <code>const int** x</code> is probably sufficient.
 
2163
        </p>
 
2164
        <p>
 
2165
          The <code>mutable</code> keyword is allowed but is unsafe
 
2166
          when used with threads, so thread safety should be carefully
 
2167
          considered first.
 
2168
        </p>
 
2169
      </DECISION>
 
2170
      <SUBSECTION title="Where to put the const">
 
2171
        <p>
 
2172
          Some people favor the form <code>int const *foo</code> to
 
2173
          <code>const int* foo</code>.  They argue that this is more
 
2174
          readable because it's more consistent: it keeps the rule
 
2175
          that <code>const</code> always follows the object it's
 
2176
          describing.  However, this consistency argument doesn't
 
2177
          apply in this case, because the "don't go crazy" dictum
 
2178
          eliminates most of the uses you'd have to be consistent with.
 
2179
          
 
2180
          Putting the <code>const</code> first is arguably more readable,
 
2181
          since it follows English in putting the "adjective"
 
2182
          (<code>const</code>) before the "noun" (<code>int</code>).
 
2183
        </p>
 
2184
        <p>
 
2185
          That said, while we encourage putting <code>const</code> first,
 
2186
          we do not require it.  But be consistent with the code around
 
2187
          you!
 
2188
        </p>
 
2189
      </SUBSECTION>
 
2190
    </BODY>
 
2191
  </STYLEPOINT>
 
2192
 
 
2193
  <STYLEPOINT title="Integer Types">
 
2194
    <SUMMARY>
 
2195
      Of the built-in C++ integer types, the only one used
 
2196
      
 
2197
      is <code>int</code>.  If a program needs a variable of a different
 
2198
      size, use
 
2199
      
 
2200
      a precise-width integer type from
 
2201
      <code>&lt;stdint.h&gt;</code>, such as <code>int16_t</code>.
 
2202
    </SUMMARY>
 
2203
    <BODY>
 
2204
      <DEFINITION>
 
2205
        C++ does not specify the sizes of its integer types. Typically
 
2206
        people assume that <code>short</code> is 16 bits,
 
2207
        <code>int</code> is 32 bits, <code>long</code> is 32 bits and
 
2208
        <code>long long</code> is 64 bits.
 
2209
      </DEFINITION>
 
2210
      <PROS>
 
2211
        Uniformity of declaration.
 
2212
      </PROS>
 
2213
      <CONS>
 
2214
        The sizes of integral types in C++ can vary based on compiler
 
2215
        and architecture.
 
2216
      </CONS>
 
2217
      <DECISION>
 
2218
        <p>
 
2219
          
 
2220
          <code>&lt;stdint.h&gt;</code> defines
 
2221
          types like <code>int16_t</code>, <code>uint32_t</code>,
 
2222
          <code>int64_t</code>, etc.
 
2223
          You should always use those in preference to
 
2224
          <code>short</code>, <code>unsigned long long</code> and the
 
2225
          like, when you need a guarantee on the size of an integer.
 
2226
          Of the C integer types, only <code>int</code> should be
 
2227
          used.  When appropriate, you are welcome to use standard
 
2228
          types like <code>size_t</code> and <code>ptrdiff_t</code>.
 
2229
        </p>
 
2230
        <p>
 
2231
          We use <code>int</code> very often, for integers we know are not
 
2232
          going to be too big, e.g., loop counters. Use plain old
 
2233
          <code>int</code> for such things. You should assume that an
 
2234
          <code>int</code> is
 
2235
          
 
2236
          at least 32 bits,
 
2237
          but don't assume that it has more than 32 bits.
 
2238
          If you need a 64-bit integer type, use
 
2239
          <code>int64_t</code> or
 
2240
          <code>uint64_t</code>.
 
2241
        </p>
 
2242
        <p>
 
2243
          For integers we know can be "big",
 
2244
           use
 
2245
          <code>int64_t</code>.
 
2246
          
 
2247
        </p>
 
2248
        <p>
 
2249
          You should not use the unsigned integer types such as
 
2250
          <code>uint32_t</code>,
 
2251
          unless the quantity you are representing is really a bit pattern
 
2252
          rather than a number, or unless you need defined
 
2253
          twos-complement overflow. In particular, do not use unsigned
 
2254
          types to say a number will never be negative.  Instead, use
 
2255
          
 
2256
          assertions for this.
 
2257
        </p>
 
2258
        
 
2259
      </DECISION>
 
2260
 
 
2261
      <SUBSECTION title="On Unsigned Integers">
 
2262
        <p>
 
2263
          Some people, including some textbook authors, recommend
 
2264
          using unsigned types to represent numbers that are never
 
2265
          negative.  This is intended as a form of self-documentation.
 
2266
          However, in C, the advantages of such documentation are
 
2267
          outweighed by the real bugs it can introduce.  Consider:
 
2268
        </p>
 
2269
        <CODE_SNIPPET>
 
2270
          for (unsigned int i = foo.Length()-1; i &gt;= 0; --i) ...
 
2271
        </CODE_SNIPPET>
 
2272
        <p>
 
2273
          This code will never terminate!  Sometimes gcc will notice
 
2274
          this bug and warn you, but often it will not.  Equally bad
 
2275
          bugs can occur when comparing signed and unsigned
 
2276
          variables.  Basically, C's type-promotion scheme causes
 
2277
          unsigned types to behave differently than one might expect.
 
2278
        </p>
 
2279
        <p>
 
2280
          So, document that a variable is non-negative using
 
2281
          assertions.
 
2282
          Don't use an unsigned type.
 
2283
        </p>
 
2284
      </SUBSECTION>
 
2285
    </BODY>
 
2286
  </STYLEPOINT>
 
2287
 
 
2288
  <STYLEPOINT title="64-bit Portability">
 
2289
    <SUMMARY>
 
2290
      Code should be 64-bit and 32-bit friendly.  Bear in mind problems of
 
2291
      printing, comparisons, and structure alignment.
 
2292
    </SUMMARY>
 
2293
    <BODY>
 
2294
      <ul>
 
2295
        <li>
 
2296
          <p>
 
2297
            <code>printf()</code> specifiers for some types are
 
2298
            not cleanly portable between 32-bit and 64-bit
 
2299
            systems. C99 defines some portable format
 
2300
            specifiers. Unfortunately, MSVC 7.1 does not
 
2301
            understand some of these specifiers and the
 
2302
            standard is missing a few, so we have to define our
 
2303
            own ugly versions in some cases (in the style of the
 
2304
            standard include file <code>inttypes.h</code>):
 
2305
          </p>
 
2306
          <CODE_SNIPPET>
 
2307
            // printf macros for size_t, in the style of inttypes.h
 
2308
            #ifdef _LP64
 
2309
            #define __PRIS_PREFIX "z"
 
2310
            #else
 
2311
            #define __PRIS_PREFIX
 
2312
            #endif
 
2313
 
 
2314
            // Use these macros after a % in a printf format string
 
2315
            // to get correct 32/64 bit behavior, like this:
 
2316
            // size_t size = records.size();
 
2317
            // printf("%"PRIuS"\n", size);
 
2318
 
 
2319
            #define PRIdS __PRIS_PREFIX "d"
 
2320
            #define PRIxS __PRIS_PREFIX "x"
 
2321
            #define PRIuS __PRIS_PREFIX "u"
 
2322
            #define PRIXS __PRIS_PREFIX "X"
 
2323
            #define PRIoS __PRIS_PREFIX "o"
 
2324
          </CODE_SNIPPET>
 
2325
          <table border="1" summary="portable printf specifiers">
 
2326
            <TBODY>
 
2327
              <tr align="center">
 
2328
                <th>Type</th>
 
2329
                <th>DO NOT use</th>
 
2330
                <th>DO use</th>
 
2331
                <th>Notes</th>
 
2332
              </tr>
 
2333
              <tr align="center">
 
2334
                <td><code>void *</code> (or any pointer)</td>
 
2335
                <td><code>%lx</code></td>
 
2336
                <td><code>%p</code></td>
 
2337
                <td> </td>
 
2338
              </tr>
 
2339
              
 
2340
              <tr align="center">
 
2341
                <td><code>int64_t</code></td>
 
2342
                <td><code>%qd</code>,
 
2343
                     <code>%lld</code></td>
 
2344
                <td><code>%"PRId64"</code></td>
 
2345
                <td/>
 
2346
              </tr>
 
2347
              
 
2348
              <tr align="center">
 
2349
                <td><code>uint64_t</code></td>
 
2350
                <td><code>%qu</code>,
 
2351
                    <code>%llu</code>,
 
2352
                    <code>%llx</code></td>
 
2353
                <td><code>%"PRIu64"</code>,
 
2354
                    <code>%"PRIx64"</code></td>
 
2355
                <td/>
 
2356
              </tr>
 
2357
              
 
2358
              <tr align="center">
 
2359
                <td><code>size_t</code></td>
 
2360
                <td><code>%u</code></td>
 
2361
                <td><code>%"PRIuS"</code>,
 
2362
                    <code>%"PRIxS"</code></td>
 
2363
                <td>C99 specifies <code>%zu</code></td>
 
2364
              </tr>
 
2365
              <tr align="center">
 
2366
                <td><code>ptrdiff_t</code></td>
 
2367
                <td><code>%d</code></td>
 
2368
                <td><code>%"PRIdS"</code></td>
 
2369
                <td>C99 specifies <code>%zd</code></td>
 
2370
              </tr>
 
2371
              
 
2372
            </TBODY>
 
2373
          </table>
 
2374
          <p>
 
2375
            Note that the <code>PRI*</code> macros expand to independent
 
2376
            strings which are concatenated by the compiler. Hence
 
2377
            if you are using a non-constant format string, you
 
2378
            need to insert the value of the macro into the format,
 
2379
            rather than the name. It is still possible, as usual,
 
2380
            to include length specifiers, etc., after the
 
2381
            <code>%</code> when using the <code>PRI*</code>
 
2382
            macros. So, e.g.  <code>printf("x = %30"PRIuS"\n",
 
2383
            x)</code> would expand on 32-bit Linux to
 
2384
            <code>printf("x = %30" "u" "\n", x)</code>, which the
 
2385
            compiler will treat as <code>printf("x = %30u\n",
 
2386
            x)</code>.
 
2387
          </p>
 
2388
          
 
2389
          </li>
 
2390
 
 
2391
        <li> Remember that <code>sizeof(void *)</code> !=
 
2392
             <code>sizeof(int)</code>.  Use <code>intptr_t</code> if
 
2393
             you want a pointer-sized integer.
 
2394
             </li>
 
2395
 
 
2396
        <li> You may need to be careful with structure alignments,
 
2397
             particularly for structures being stored on disk. Any
 
2398
             class/structure with a
 
2399
             
 
2400
             <code>int64_t</code>/<code>uint64_t</code>
 
2401
             member will by default end up being 8-byte aligned on a 64-bit
 
2402
             system. If you have such structures being shared on disk
 
2403
             between 32-bit and 64-bit code, you will need to ensure
 
2404
             that they are packed the same on both architectures.
 
2405
             
 
2406
             Most compilers offer a way to alter
 
2407
             structure alignment.  For gcc, you can use
 
2408
             <code>__attribute__((packed))</code>.  MSVC offers
 
2409
             <code>#pragma pack()</code> and
 
2410
             <code>__declspec(align())</code>.
 
2411
             </li>
 
2412
 
 
2413
        <li>
 
2414
             
 
2415
             Use the <code>LL</code> or <code>ULL</code> suffixes as
 
2416
             needed to create 64-bit constants.  For example:
 
2417
             
 
2418
             <CODE_SNIPPET>
 
2419
             int64_t my_value = 0x123456789LL;
 
2420
             uint64_t my_mask = 3ULL &lt;&lt; 48;
 
2421
             </CODE_SNIPPET>
 
2422
             </li>
 
2423
 
 
2424
        <li> If you really need different code on 32-bit and 64-bit
 
2425
             systems, use <code>#ifdef _LP64</code> to choose between
 
2426
             the code variants. (But please avoid this if
 
2427
             possible, and keep any such changes localized.)
 
2428
             </li>
 
2429
      </ul>
 
2430
    </BODY>
 
2431
  </STYLEPOINT>
 
2432
 
 
2433
  <STYLEPOINT title="Preprocessor Macros">
 
2434
    <SUMMARY>
 
2435
      Be very cautious with macros.  Prefer inline functions, enums,
 
2436
      and <code>const</code> variables to macros.
 
2437
    </SUMMARY>
 
2438
    <BODY>
 
2439
      <p>
 
2440
        Macros mean that the code you see is not the same as the code
 
2441
        the compiler sees.  This can introduce unexpected behavior,
 
2442
        especially since macros have global scope.
 
2443
      </p>
 
2444
      <p>
 
2445
        Luckily, macros are not nearly as necessary in C++ as they are
 
2446
        in C.  Instead of using a macro to inline performance-critical
 
2447
        code, use an inline function.  Instead of using a macro to
 
2448
        store a constant, use a <code>const</code> variable.  Instead of
 
2449
        using a macro to "abbreviate" a long variable name, use a
 
2450
        reference.  Instead of using a macro to conditionally compile code
 
2451
        ... well, don't do that at all (except, of course, for the
 
2452
        <code>#define</code> guards to prevent double inclusion of
 
2453
        header files).  It makes testing much more difficult.
 
2454
      </p>
 
2455
      <p>
 
2456
        Macros can do things these other techniques cannot, and you do
 
2457
        see them in the codebase, especially in the lower-level
 
2458
        libraries.  And some of their special features (like
 
2459
        stringifying, concatenation, and so forth) are not available
 
2460
        through the language proper.  But before using a macro,
 
2461
        consider carefully whether there's a non-macro way to achieve
 
2462
        the same result.
 
2463
      </p>
 
2464
      <p>
 
2465
        The following usage pattern will avoid many problems with
 
2466
        macros; if you use macros, follow it whenever possible:
 
2467
      </p>
 
2468
      <ul>
 
2469
        <li> Don't define macros in a <code>.h</code> file.
 
2470
             </li>
 
2471
        <li> <code>#define</code> macros right before you use them,
 
2472
             and <code>#undef</code> them right after.
 
2473
             </li>
 
2474
        <li> Do not just <code>#undef</code> an existing macro before
 
2475
             replacing it with your own; instead, pick a name that's
 
2476
             likely to be unique.
 
2477
             </li>
 
2478
        <li> Try not to use macros that expand to unbalanced C++
 
2479
             constructs, or at least document that behavior well.
 
2480
             </li>
 
2481
        <li> Prefer not using <code>##</code> to generate function/class/variable
 
2482
             names.
 
2483
             </li>
 
2484
      </ul>
 
2485
    </BODY>
 
2486
  </STYLEPOINT>
 
2487
 
 
2488
  <STYLEPOINT title="0 and NULL">
 
2489
  <SUMMARY>
 
2490
    Use <code>0</code> for integers, <code>0.0</code> for reals,
 
2491
    <code>NULL</code> for pointers, and <code>'\0'</code> for chars.
 
2492
  </SUMMARY>
 
2493
  <BODY>
 
2494
    <p>
 
2495
      Use <code>0</code> for integers and <code>0.0</code> for reals.
 
2496
      This is not controversial.
 
2497
    </p>
 
2498
    <p>
 
2499
      For pointers (address values), there is a choice between <code>0</code>
 
2500
      and <code>NULL</code>.  Bjarne Stroustrup prefers an unadorned
 
2501
      <code>0</code>.  We prefer <code>NULL</code> because it looks like a
 
2502
      pointer.  In fact, some C++ compilers, such as gcc 4.1.0, provide special
 
2503
      definitions of <code>NULL</code> which enable them to give useful
 
2504
      warnings, particularly in situations where <code>sizeof(NULL)</code>
 
2505
      is not equal to <code>sizeof(0)</code>.
 
2506
    </p>
 
2507
    <p>
 
2508
      Use <code>'\0'</code> for chars.
 
2509
      This is the correct type and also makes code more readable.
 
2510
    </p>
 
2511
  </BODY>
 
2512
  </STYLEPOINT>
 
2513
 
 
2514
  <STYLEPOINT title="sizeof">
 
2515
  <SUMMARY>
 
2516
    Use <code>sizeof(<var>varname</var>)</code> instead of
 
2517
    <code>sizeof(<var>type</var>)</code> whenever possible.
 
2518
  </SUMMARY>
 
2519
  <BODY>
 
2520
    <p>
 
2521
      Use <code>sizeof(<var>varname</var>)</code> because it will update
 
2522
      appropriately if the type of the variable changes.
 
2523
      <code>sizeof(<var>type</var>)</code> may make sense in some cases,
 
2524
      but should generally be avoided because it can fall out of sync if
 
2525
      the variable's type changes.
 
2526
    </p>
 
2527
    <p>
 
2528
      <CODE_SNIPPET>
 
2529
        Struct data;
 
2530
        memset(&amp;data, 0, sizeof(data));
 
2531
      </CODE_SNIPPET>
 
2532
      <BAD_CODE_SNIPPET>
 
2533
        memset(&amp;data, 0, sizeof(Struct));
 
2534
      </BAD_CODE_SNIPPET>
 
2535
    </p>
 
2536
  </BODY>
 
2537
  </STYLEPOINT>
 
2538
 
 
2539
  <STYLEPOINT title="Boost">
 
2540
  <SUMMARY>
 
2541
    Use only approved libraries from the Boost library collection.
 
2542
  </SUMMARY>
 
2543
  <BODY>
 
2544
    <DEFINITION>
 
2545
      The <a href="http://www.boost.org/">Boost library collection</a> is
 
2546
      a popular collection of peer-reviewed, free, open-source C++ libraries.
 
2547
    </DEFINITION>
 
2548
    <PROS>
 
2549
      Boost code is generally very high-quality, is widely portable, and fills
 
2550
      many important gaps in the C++ standard library, such as type traits,
 
2551
      better binders, and better smart pointers. It also provides an
 
2552
      implementation of the TR1 extension to the standard library.
 
2553
    </PROS>
 
2554
    <CONS>
 
2555
      Some Boost libraries encourage coding practices which can hamper
 
2556
      readability, such as metaprogramming and other advanced template
 
2557
      techniques, and an excessively "functional" style of programming.
 
2558
      
 
2559
    </CONS>
 
2560
    <DECISION>
 
2561
      
 
2562
      <div>
 
2563
        
 
2564
        In order to maintain a high level of readability for all contributors
 
2565
        who might read and maintain code, we only allow an approved subset of
 
2566
        Boost features.  Currently, the following libraries are permitted:
 
2567
        <ul>
 
2568
          <li> <a href="http://www.boost.org/libs/utility/call_traits.htm">
 
2569
               Call Traits</a> from <code>boost/call_traits.hpp</code>
 
2570
               </li>
 
2571
          <li> <a href="http://www.boost.org/libs/utility/compressed_pair.htm">
 
2572
               Compressed Pair</a> from <code>boost/compressed_pair.hpp</code>
 
2573
               </li>
 
2574
          <li> <a href="http://www.boost.org/libs/ptr_container/">
 
2575
               Pointer Container</a> from <code>boost/ptr_container</code> except
 
2576
               serialization and wrappers for containers not in the C++03
 
2577
               standard (<code>ptr_circular_buffer.hpp</code> and
 
2578
               <code>ptr_unordered*</code>)
 
2579
               </li>
 
2580
          <li> <a href="http://www.boost.org/libs/array/">
 
2581
               Array</a> from <code>boost/array.hpp</code>
 
2582
               </li>
 
2583
          <li> <a href="http://www.boost.org/libs/graph/">
 
2584
               The Boost Graph Library (BGL)</a> from <code>boost/graph</code>,
 
2585
               except serialization (<code>adj_list_serialize.hpp</code>) and
 
2586
               parallel/distributed algorithms and data structures
 
2587
               (<code>boost/graph/parallel/*</code> and
 
2588
               <code>boost/graph/distributed/*</code>).
 
2589
               </li>
 
2590
          <li> <a href="http://www.boost.org/libs/property_map/">
 
2591
               Property Map</a> from <code>boost/property_map</code>, except
 
2592
               parallel/distributed property maps
 
2593
               (<code>boost/property_map/parallel/*</code>).
 
2594
               </li>
 
2595
          <li> The part of
 
2596
               <a href="http://www.boost.org/libs/iterator/">
 
2597
               Iterator</a> that deals with defining iterators:
 
2598
               <code>boost/iterator/iterator_adaptor.hpp</code>,
 
2599
               <code>boost/iterator/iterator_facade.hpp</code>, and
 
2600
               <code>boost/function_output_iterator.hpp</code></li>
 
2601
        </ul>
 
2602
        We are actively considering adding other Boost features to the list, so
 
2603
        this rule may be relaxed in the future.
 
2604
      </div>
 
2605
    </DECISION>
 
2606
  </BODY>
 
2607
  </STYLEPOINT>
 
2608
 
 
2609
  <STYLEPOINT title="C++0x">
 
2610
  <SUMMARY>
 
2611
    Use only approved libraries and language extensions from C++0x.
 
2612
    Currently, none are approved.
 
2613
  </SUMMARY>
 
2614
  <BODY>
 
2615
    <DEFINITION>
 
2616
      C++0x is the next ISO C++ standard, currently in
 
2617
      <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3092.pdf">final
 
2618
      committee draft</a> form.  It contains
 
2619
      <a href="http://en.wikipedia.org/wiki/C%2B%2B0x">significant
 
2620
      changes</a> both to the language and libraries.
 
2621
    </DEFINITION>
 
2622
    <PROS>
 
2623
      We expect that C++0x will become the next standard, and eventually will
 
2624
      be supported by most C++ compilers.  It standardizes some common C++
 
2625
      extensions that we use already, allows shorthands for some operations,
 
2626
      and has some safety improvements.
 
2627
    </PROS>
 
2628
    <CONS>
 
2629
      <p>
 
2630
        The C++0x standard is substantialy more complex than its predecessor
 
2631
        (1,300 pages versus 800 pages), and is
 
2632
        unfamilar to many developers.  The long-term effects of some
 
2633
        features on code readability and maintenance are unknown.  We cannot
 
2634
        predict when its various features will be implemented uniformly by
 
2635
        tools that may be of interest (gcc, icc, clang, Eclipse, etc.).
 
2636
      </p>
 
2637
      <p>
 
2638
        As with <a href="#Boost">Boost</a>, some C++0x extensions encourage
 
2639
        coding practices that hamper readability&#8212;for example by removing
 
2640
        checked redundancy (such as type names) that may be helpful to readers,
 
2641
        or by encouraging template metaprogramming.  Other extensions
 
2642
        duplicate functionality available through existing
 
2643
        mechanisms, which may lead to
 
2644
        confusion and conversion costs.
 
2645
      </p>
 
2646
    </CONS>
 
2647
    <DECISION>
 
2648
      Use only C++0x libraries and language features that have been approved
 
2649
      for use.  Currently, no such features are approved.
 
2650
      Features will be approved individually as appropriate.
 
2651
    </DECISION>
 
2652
  </BODY>
 
2653
  </STYLEPOINT>
 
2654
 
 
2655
</CATEGORY>
 
2656
 
 
2657
<CATEGORY title="Naming">
 
2658
  <p>
 
2659
    The most important consistency rules are those that govern
 
2660
    naming. The style of a name immediately informs us what sort of
 
2661
    thing the named entity is: a type, a variable, a function, a
 
2662
    constant, a macro, etc., without requiring us to search for the
 
2663
    declaration of that entity. The pattern-matching engine in our
 
2664
    brains relies a great deal on these naming rules.
 
2665
    
 
2666
  </p>
 
2667
  <p>
 
2668
    Naming rules are pretty arbitrary, but
 
2669
    
 
2670
    we feel that consistency is more important than individual preferences
 
2671
    in this area, so regardless of whether you find them sensible or not,
 
2672
    the rules are the rules.
 
2673
  </p>
 
2674
 
 
2675
  <STYLEPOINT title="General Naming Rules">
 
2676
    <SUMMARY>
 
2677
      Function names, variable names, and filenames should be
 
2678
      descriptive; eschew abbreviation.  Types and variables should be
 
2679
      nouns, while functions should be "command" verbs.
 
2680
    </SUMMARY>
 
2681
    <BODY>
 
2682
      <SUBSECTION title="How to Name">
 
2683
        <p>
 
2684
          Give as descriptive a name as possible, within reason. Do
 
2685
          not worry about saving horizontal space as it is far more
 
2686
          important to make your code immediately understandable by a
 
2687
          new reader. Examples of well-chosen names:
 
2688
        </p>
 
2689
        <CODE_SNIPPET>
 
2690
          int num_errors;                  // Good.
 
2691
          int num_completed_connections;   // Good.
 
2692
        </CODE_SNIPPET>
 
2693
        <p>
 
2694
          Poorly-chosen names use ambiguous abbreviations or arbitrary
 
2695
          characters that do not convey meaning:
 
2696
        </p>
 
2697
        <BAD_CODE_SNIPPET>
 
2698
          int n;                           // Bad - meaningless.
 
2699
          int nerr;                        // Bad - ambiguous abbreviation.
 
2700
          int n_comp_conns;                // Bad - ambiguous abbreviation.
 
2701
        </BAD_CODE_SNIPPET>
 
2702
        <p>
 
2703
          Type and variable names should typically be nouns: e.g.,
 
2704
          <code>FileOpener</code>,
 
2705
          
 
2706
          <code>num_errors</code>.
 
2707
        </p>
 
2708
        <p>
 
2709
          Function names should typically be imperative (that is they
 
2710
          should be commands): e.g., <code>OpenFile()</code>,
 
2711
          <code>set_num_errors()</code>.  There is an exception for
 
2712
          accessors, which, described more completely in <a HREF="#Function_Names">Function Names</a>, should be named
 
2713
          the same as the variable they access.
 
2714
        </p>
 
2715
      </SUBSECTION>
 
2716
 
 
2717
      <SUBSECTION title="Abbreviations">
 
2718
        <p>
 
2719
          Do not use abbreviations unless they are extremely well
 
2720
          known outside your project. For example:
 
2721
        </p>
 
2722
        <CODE_SNIPPET>
 
2723
          // Good
 
2724
          // These show proper names with no abbreviations.
 
2725
          int num_dns_connections;  // Most people know what "DNS" stands for.
 
2726
          int price_count_reader;   // OK, price count. Makes sense.
 
2727
        </CODE_SNIPPET>
 
2728
        <BAD_CODE_SNIPPET>
 
2729
          // Bad!
 
2730
          // Abbreviations can be confusing or ambiguous outside a small group.
 
2731
          int wgc_connections;  // Only your group knows what this stands for.
 
2732
          int pc_reader;        // Lots of things can be abbreviated "pc".
 
2733
        </BAD_CODE_SNIPPET>
 
2734
        <p>
 
2735
          Never abbreviate by leaving out letters:
 
2736
        </p>
 
2737
        <CODE_SNIPPET>
 
2738
          int error_count;  // Good.
 
2739
        </CODE_SNIPPET>
 
2740
        <BAD_CODE_SNIPPET>
 
2741
          int error_cnt;    // Bad.
 
2742
        </BAD_CODE_SNIPPET>
 
2743
      </SUBSECTION>
 
2744
    </BODY>
 
2745
  </STYLEPOINT>
 
2746
 
 
2747
  <STYLEPOINT title="File Names">
 
2748
    <SUMMARY>
 
2749
      Filenames should be all lowercase and can include underscores
 
2750
      (<code>_</code>) or dashes (<code>-</code>).  Follow the
 
2751
      convention that your
 
2752
      
 
2753
      project
 
2754
      uses. If there is no consistent local pattern to follow, prefer "_".
 
2755
    </SUMMARY>
 
2756
    <BODY>
 
2757
      <p>
 
2758
        Examples of acceptable file names:
 
2759
      </p>
 
2760
      <p>
 
2761
        <code>
 
2762
          my_useful_class.cc<br/>
 
2763
          my-useful-class.cc<br/>
 
2764
          myusefulclass.cc<br/>
 
2765
          myusefulclass_test.cc  // _unittest and _regtest are deprecated.<br/>
 
2766
        </code>
 
2767
      </p>
 
2768
      <p>
 
2769
        C++ files should end in <code>.cc</code> and header files
 
2770
        should end in <code>.h</code>.
 
2771
      </p>
 
2772
      <p>
 
2773
        Do not use filenames that already exist
 
2774
        in <code>/usr/include</code>, such as <code>db.h</code>.
 
2775
      </p>
 
2776
      <p>
 
2777
        In general, make your filenames very specific.  For example,
 
2778
        use <code>http_server_logs.h</code> rather
 
2779
        than <code>logs.h</code>.  A very common case is to have a
 
2780
        pair of files called, e.g., <code>foo_bar.h</code>
 
2781
        and <code>foo_bar.cc</code>, defining a class
 
2782
        called <code>FooBar</code>.
 
2783
      </p>
 
2784
      <p>
 
2785
        Inline functions must be in a <code>.h</code> file. If your
 
2786
        inline functions are very short, they should go directly into your
 
2787
        <code>.h</code> file. However, if your inline functions
 
2788
        include a lot of code, they may go into a third file that
 
2789
        ends in <code>-inl.h</code>.  In a class with a lot of inline
 
2790
        code, your class could have three files:
 
2791
      </p>
 
2792
      <CODE_SNIPPET>
 
2793
        url_table.h      // The class declaration.
 
2794
        url_table.cc     // The class definition.
 
2795
        url_table-inl.h  // Inline functions that include lots of code.
 
2796
      </CODE_SNIPPET>
 
2797
      <p>
 
2798
        See also the section <a href="#The_-inl.h_Files">-inl.h Files</a>
 
2799
      </p>
 
2800
    </BODY>
 
2801
  </STYLEPOINT>
 
2802
 
 
2803
  <STYLEPOINT title="Type Names">
 
2804
    <SUMMARY>
 
2805
      Type names start with a capital letter and have a capital
 
2806
      letter for each new word, with no underscores:
 
2807
      <code>MyExcitingClass</code>, <code>MyExcitingEnum</code>.
 
2808
    </SUMMARY>
 
2809
    <BODY>
 
2810
      <p>
 
2811
        The names of all types &#8212; classes, structs, typedefs, and enums
 
2812
        &#8212; have the same naming convention.  Type names should start
 
2813
        with a capital letter and have a capital letter for each new
 
2814
        word.  No underscores.  For example:
 
2815
      </p>
 
2816
      <CODE_SNIPPET>
 
2817
        // classes and structs
 
2818
        class UrlTable { ...
 
2819
        class UrlTableTester { ...
 
2820
        struct UrlTableProperties { ...
 
2821
 
 
2822
        // typedefs
 
2823
        typedef hash_map&lt;UrlTableProperties *, string&gt; PropertiesMap;
 
2824
 
 
2825
        // enums
 
2826
        enum UrlTableErrors { ...
 
2827
      </CODE_SNIPPET>
 
2828
    </BODY>
 
2829
  </STYLEPOINT>
 
2830
 
 
2831
  <STYLEPOINT title="Variable Names">
 
2832
    <SUMMARY>
 
2833
      Variable names are all lowercase, with underscores between
 
2834
      words.  Class member variables have trailing underscores.  For
 
2835
      instance: <code>my_exciting_local_variable</code>,
 
2836
      <code>my_exciting_member_variable_</code>.
 
2837
    </SUMMARY>
 
2838
    <BODY>
 
2839
      <SUBSECTION title="Common Variable names">
 
2840
        <p>
 
2841
          For example:
 
2842
        </p>
 
2843
        <CODE_SNIPPET>
 
2844
          string table_name;  // OK - uses underscore.
 
2845
          string tablename;   // OK - all lowercase.
 
2846
        </CODE_SNIPPET>
 
2847
        <BAD_CODE_SNIPPET>
 
2848
          string tableName;   // Bad - mixed case.
 
2849
        </BAD_CODE_SNIPPET>
 
2850
      </SUBSECTION>
 
2851
 
 
2852
      <SUBSECTION title="Class Data Members">
 
2853
        <p>
 
2854
          Data members (also called instance variables or member
 
2855
          variables) are lowercase with optional underscores like
 
2856
          regular variable names, but always end with a trailing
 
2857
          underscore.
 
2858
        </p>
 
2859
        <CODE_SNIPPET>
 
2860
          string table_name_;  // OK - underscore at end.
 
2861
          string tablename_;   // OK.
 
2862
        </CODE_SNIPPET>
 
2863
      </SUBSECTION>
 
2864
 
 
2865
      <SUBSECTION title="Struct Variables">
 
2866
        <p>
 
2867
          Data members in structs should be named like regular
 
2868
          variables without the trailing underscores that data members
 
2869
          in classes have.
 
2870
        </p>
 
2871
        <CODE_SNIPPET>
 
2872
          struct UrlTableProperties {
 
2873
            string name;
 
2874
            int num_entries;
 
2875
          }
 
2876
        </CODE_SNIPPET>
 
2877
        <p>
 
2878
          See <a HREF="#Structs_vs._Classes">Structs vs. Classes</a> for a
 
2879
          discussion of when to use a struct versus a class.
 
2880
        </p>
 
2881
      </SUBSECTION>
 
2882
 
 
2883
      <SUBSECTION title="Global Variables">
 
2884
        <p>
 
2885
          There are no special requirements for global variables,
 
2886
          which should be rare in any case, but if you use one,
 
2887
          consider prefixing it with <code>g_</code> or some other
 
2888
          marker to easily distinguish it from local variables.
 
2889
        </p>
 
2890
      </SUBSECTION>
 
2891
    </BODY>
 
2892
  </STYLEPOINT>
 
2893
 
 
2894
  <STYLEPOINT title="Constant Names">
 
2895
    <SUMMARY>
 
2896
      Use a <code>k</code> followed by mixed case:
 
2897
      <code>kDaysInAWeek</code>.
 
2898
    </SUMMARY>
 
2899
    <BODY>
 
2900
      <p>
 
2901
        All compile-time constants, whether they are declared locally,
 
2902
        globally, or as part of a class, follow a slightly different
 
2903
        naming convention from other variables. Use a <code>k</code>
 
2904
        followed by words with uppercase first letters:
 
2905
      </p>
 
2906
      <CODE_SNIPPET>
 
2907
        const int kDaysInAWeek = 7;
 
2908
      </CODE_SNIPPET>
 
2909
    </BODY>
 
2910
  </STYLEPOINT>
 
2911
 
 
2912
  <STYLEPOINT title="Function Names">
 
2913
    <SUMMARY>
 
2914
      Regular functions have mixed case; accessors and mutators match
 
2915
      the name of the variable: <code>MyExcitingFunction()</code>,
 
2916
      <code>MyExcitingMethod()</code>,
 
2917
      <code>my_exciting_member_variable()</code>,
 
2918
      <code>set_my_exciting_member_variable()</code>.
 
2919
    </SUMMARY>
 
2920
    <BODY>
 
2921
      <SUBSECTION title="Regular Functions">
 
2922
        <p>
 
2923
          Functions should start with a capital letter and have a
 
2924
          capital letter for each new word. No underscores.
 
2925
        </p>
 
2926
        <p>
 
2927
          If your function crashes upon an error, you should append OrDie to
 
2928
          the function name. This only applies to functions which could be
 
2929
          used by production code and to errors that are reasonably
 
2930
          likely to occur during normal operation.
 
2931
        </p>
 
2932
        <CODE_SNIPPET>
 
2933
          AddTableEntry()
 
2934
          DeleteUrl()
 
2935
          OpenFileOrDie()
 
2936
        </CODE_SNIPPET>
 
2937
      </SUBSECTION>
 
2938
 
 
2939
      <SUBSECTION title="Accessors and Mutators">
 
2940
        <p>
 
2941
          Accessors and mutators (get and set functions) should match
 
2942
          the name of the variable they are getting and setting.  This
 
2943
          shows an excerpt of a class whose instance variable is
 
2944
          <code>num_entries_</code>.
 
2945
        </p>
 
2946
        <CODE_SNIPPET>
 
2947
          class MyClass {
 
2948
           public:
 
2949
            ...
 
2950
            int num_entries() const { return num_entries_; }
 
2951
            void set_num_entries(int num_entries) { num_entries_ = num_entries; }
 
2952
 
 
2953
           private:
 
2954
            int num_entries_;
 
2955
          };
 
2956
        </CODE_SNIPPET>
 
2957
        <p>
 
2958
          You may also use lowercase letters for other very short
 
2959
          inlined functions. For example if a function were so cheap
 
2960
          you would not cache the value if you were calling it in a
 
2961
          loop, then lowercase naming would be acceptable.
 
2962
        </p>
 
2963
      </SUBSECTION>
 
2964
    </BODY>
 
2965
  </STYLEPOINT>
 
2966
 
 
2967
  <STYLEPOINT title="Namespace Names">
 
2968
    
 
2969
    <SUMMARY>
 
2970
      Namespace names are all lower-case, and based on project names and
 
2971
      possibly their directory structure:
 
2972
      <code>google_awesome_project</code>.
 
2973
    </SUMMARY>
 
2974
    <BODY>
 
2975
      <p>
 
2976
        See <a HREF="#Namespaces">Namespaces</a> for a discussion of
 
2977
        namespaces and how to name them.
 
2978
      </p>
 
2979
    </BODY>
 
2980
  </STYLEPOINT>
 
2981
 
 
2982
  <STYLEPOINT title="Enumerator Names">
 
2983
    <SUMMARY>
 
2984
      Enumerators should be named <i>either</i> like
 
2985
      <A HREF="#Constant_Names">constants</A> or like
 
2986
      <A HREF="#Macro_Names">macros</A>: either <code>kEnumName</code>
 
2987
      or <code>ENUM_NAME</code>.
 
2988
    </SUMMARY>
 
2989
    <BODY>
 
2990
      <p>
 
2991
        Preferably, the individual enumerators should be named like
 
2992
        <A HREF="#Constant_Names">constants</A>.  However, it is also
 
2993
        acceptable to name them like <A HREF="#Macro_Names">macros</A>.    The enumeration name,
 
2994
        <code>UrlTableErrors</code> (and
 
2995
        <code>AlternateUrlTableErrors</code>), is a type, and
 
2996
        therefore mixed case.
 
2997
      </p>
 
2998
      <CODE_SNIPPET>
 
2999
        enum UrlTableErrors {
 
3000
          kOK = 0,
 
3001
          kErrorOutOfMemory,
 
3002
          kErrorMalformedInput,
 
3003
        };
 
3004
        enum AlternateUrlTableErrors {
 
3005
          OK = 0,
 
3006
          OUT_OF_MEMORY = 1,
 
3007
          MALFORMED_INPUT = 2,
 
3008
        };
 
3009
      </CODE_SNIPPET>
 
3010
      <p>
 
3011
        Until January 2009, the style was to name enum values like
 
3012
        <A HREF="#Macro_Names">macros</A>.  This caused problems with
 
3013
        name collisions between enum values and macros.  Hence, the
 
3014
        change to prefer constant-style naming was put in place.  New
 
3015
        code should prefer constant-style naming if possible.
 
3016
        However, there is no reason to change old code to use
 
3017
        constant-style names, unless the old names are actually
 
3018
        causing a compile-time problem.
 
3019
      </p>
 
3020
      
 
3021
    </BODY>
 
3022
  </STYLEPOINT>
 
3023
 
 
3024
  <STYLEPOINT title="Macro Names">
 
3025
    <SUMMARY>
 
3026
      You're not really going to <A HREF="#Preprocessor_Macros">define
 
3027
      a macro</A>, are you?  If you do, they're like this:
 
3028
      <code>MY_MACRO_THAT_SCARES_SMALL_CHILDREN</code>.
 
3029
    </SUMMARY>
 
3030
    <BODY>
 
3031
      <p>
 
3032
        Please see the <a href="#Preprocessor_Macros">description of
 
3033
        macros</a>; in general macros should <em>not</em> be used.
 
3034
        However, if they are absolutely needed, then they should be
 
3035
        named with all capitals and underscores.
 
3036
      </p>
 
3037
      <CODE_SNIPPET>
 
3038
        #define ROUND(x) ...
 
3039
        #define PI_ROUNDED 3.0
 
3040
      </CODE_SNIPPET>
 
3041
    </BODY>
 
3042
  </STYLEPOINT>
 
3043
 
 
3044
  <STYLEPOINT title="Exceptions to Naming Rules">
 
3045
    <SUMMARY>
 
3046
      If you are naming something that is analogous to an existing C
 
3047
      or C++ entity then you can follow the existing naming convention
 
3048
      scheme.
 
3049
    </SUMMARY>
 
3050
    <BODY>
 
3051
      <p>
 
3052
        <dl>
 
3053
          <dt> <code>bigopen()</code> </dt>
 
3054
          <dd>   function name, follows form of <code>open()</code> </dd>
 
3055
          <dt> <code>uint</code> </dt>
 
3056
          <dd>   <code>typedef</code> </dd>
 
3057
          <dt> <code>bigpos</code> </dt>
 
3058
          <dd>   <code>struct</code> or <code>class</code>, follows form of
 
3059
                 <code>pos</code> </dd>
 
3060
          <dt> <code>sparse_hash_map</code> </dt>
 
3061
          <dd>   STL-like entity; follows STL naming conventions </dd>
 
3062
          <dt> <code>LONGLONG_MAX</code> </dt>
 
3063
          <dd>   a constant, as in <code>INT_MAX</code> </dd>
 
3064
        </dl>
 
3065
      </p>
 
3066
    </BODY>
 
3067
  </STYLEPOINT>
 
3068
</CATEGORY>
 
3069
 
 
3070
<CATEGORY title="Comments">
 
3071
  <p>
 
3072
    Though a pain to write, comments are absolutely vital to keeping our
 
3073
    code readable.  The following rules describe what you should
 
3074
    comment and where.  But remember: while comments are very
 
3075
    important, the best code is self-documenting.  Giving sensible
 
3076
    names to types and variables is much better than using obscure
 
3077
    names that you must then explain through comments.
 
3078
  </p>
 
3079
  <p>
 
3080
    When writing your comments, write for your audience: the next
 
3081
    
 
3082
    contributor
 
3083
    who will need to understand your code.  Be generous &#8212; the next
 
3084
    one may be you!
 
3085
  </p>
 
3086
 
 
3087
  
 
3088
 
 
3089
  <STYLEPOINT title="Comment Style">
 
3090
    <SUMMARY>
 
3091
      Use either the <code>//</code> or <code>/* */</code> syntax, as long
 
3092
      as you are consistent.
 
3093
    </SUMMARY>
 
3094
    <BODY>
 
3095
      <p>
 
3096
        You can use either the <code>//</code> or the <code>/* */</code>
 
3097
        syntax; however, <code>//</code> is <em>much</em> more common.
 
3098
        Be consistent with how you comment and what style you use where.
 
3099
      </p>
 
3100
    </BODY>
 
3101
  </STYLEPOINT>
 
3102
 
 
3103
  <STYLEPOINT title="File Comments">
 
3104
    <SUMMARY>
 
3105
      Start each file with a copyright notice, followed by a
 
3106
      description of the contents of the file.
 
3107
    </SUMMARY>
 
3108
    <BODY>
 
3109
      <SUBSECTION title="Legal Notice and Author Line">
 
3110
        
 
3111
        
 
3112
        <p>
 
3113
          Every file should contain the following items, in order:
 
3114
          <ul>
 
3115
            <li>a copyright statement (for example,
 
3116
                <code>Copyright 2008 Google Inc.</code>)</li>
 
3117
            <li>a license boilerplate.  Choose the appropriate boilerplate
 
3118
                for the license used by the project (for example,
 
3119
                Apache 2.0, BSD, LGPL, GPL)</li>
 
3120
            <li>an author line to identify the original author of the
 
3121
                file</li>
 
3122
          </ul>
 
3123
        </p>
 
3124
        <p>
 
3125
          If you make significant changes to a file that someone else
 
3126
          originally wrote, add yourself to the author line. This can
 
3127
          be very helpful when another
 
3128
          
 
3129
          contributor
 
3130
          has questions about the file and needs to know whom to contact
 
3131
          about it.
 
3132
        </p>
 
3133
      </SUBSECTION>
 
3134
 
 
3135
      <SUBSECTION title="File Contents">
 
3136
        <p>
 
3137
          Every file should have a comment at the top, below the copyright
 
3138
          notice and author line, that describes the contents of the file.
 
3139
        </p>
 
3140
        <p>
 
3141
          Generally a <code>.h</code> file will describe the classes
 
3142
          that are declared in the file with an overview of what they
 
3143
          are for and how they are used. A <code>.cc</code> file
 
3144
          should contain more information about implementation details
 
3145
          or discussions of tricky algorithms. If you feel the
 
3146
          implementation details or a discussion of the algorithms
 
3147
          would be useful for someone reading the <code>.h</code>,
 
3148
          feel free to put it there instead, but mention in the
 
3149
          <code>.cc</code> that the documentation is in the
 
3150
          <code>.h</code> file.
 
3151
        </p>
 
3152
        <p>
 
3153
          Do not duplicate comments in both the <code>.h</code> and
 
3154
          the <code>.cc</code>. Duplicated comments diverge.
 
3155
        </p>
 
3156
      </SUBSECTION>
 
3157
    </BODY>
 
3158
  </STYLEPOINT>
 
3159
 
 
3160
  <STYLEPOINT title="Class Comments">
 
3161
    <SUMMARY>
 
3162
      Every class definition should have an accompanying comment that
 
3163
      describes what it is for and how it should be used.
 
3164
    </SUMMARY>
 
3165
    <BODY>
 
3166
      <CODE_SNIPPET>
 
3167
        // Iterates over the contents of a GargantuanTable.  Sample usage:
 
3168
        //    GargantuanTableIterator* iter = table-&gt;NewIterator();
 
3169
        //    for (iter-&gt;Seek("foo"); !iter-&gt;done(); iter-&gt;Next()) {
 
3170
        //      process(iter-&gt;key(), iter-&gt;value());
 
3171
        //    }
 
3172
        //    delete iter;
 
3173
        class GargantuanTableIterator {
 
3174
          ...
 
3175
        };
 
3176
      </CODE_SNIPPET>
 
3177
      <p>
 
3178
        If you have already described a class in detail in the
 
3179
        comments at the top of your file feel free to simply state
 
3180
        "See comment at top of file for a complete description", but
 
3181
        be sure to have some sort of comment.
 
3182
      </p>
 
3183
      <p>
 
3184
        Document the synchronization assumptions the class makes, if
 
3185
        any.  If an instance of the class can be accessed by multiple
 
3186
        threads, take extra care to document the rules and invariants
 
3187
        surrounding multithreaded use.
 
3188
      </p>
 
3189
    </BODY>
 
3190
  </STYLEPOINT>
 
3191
 
 
3192
  <STYLEPOINT title="Function Comments">
 
3193
    <SUMMARY>
 
3194
      Declaration comments describe use of the function; comments at
 
3195
      the definition of a function describe operation.
 
3196
    </SUMMARY>
 
3197
    <BODY>
 
3198
      <SUBSECTION title="Function Declarations">
 
3199
        <p>
 
3200
          Every function declaration should have comments immediately
 
3201
          preceding it that describe what the function does and how to
 
3202
          use it.  These comments should be descriptive ("Opens the
 
3203
          file") rather than imperative ("Open the file"); the comment
 
3204
          describes the function, it does not tell the function what
 
3205
          to do.  In general, these comments do not describe how the
 
3206
          function performs its task.  Instead, that should be left to
 
3207
          comments in the function definition.
 
3208
        </p>
 
3209
        <p>
 
3210
          Types of things to mention in comments at the function
 
3211
          declaration:
 
3212
        </p>
 
3213
        <ul>
 
3214
          <li> What the inputs and outputs are.
 
3215
               </li>
 
3216
          <li> For class member functions:  whether the object
 
3217
               remembers reference arguments beyond the
 
3218
               duration of the method call, and whether it will
 
3219
               free them or not.
 
3220
               </li>
 
3221
          <li> If the function allocates memory that the caller
 
3222
               must free.
 
3223
               </li>
 
3224
          <li> Whether any of the arguments can be <code>NULL</code>.
 
3225
               </li>
 
3226
          <li> If there are any performance implications of how a
 
3227
               function is used.
 
3228
               </li>
 
3229
          <li> If the function is re-entrant.  What are its
 
3230
               synchronization assumptions?
 
3231
               </li>
 
3232
        </ul>
 
3233
        <p>
 
3234
          Here is an example:
 
3235
        </p>
 
3236
        <CODE_SNIPPET>
 
3237
          // Returns an iterator for this table.  It is the client's
 
3238
          // responsibility to delete the iterator when it is done with it,
 
3239
          // and it must not use the iterator once the GargantuanTable object
 
3240
          // on which the iterator was created has been deleted.
 
3241
          //
 
3242
          // The iterator is initially positioned at the beginning of the table.
 
3243
          //
 
3244
          // This method is equivalent to:
 
3245
          //    Iterator* iter = table-&gt;NewIterator();
 
3246
          //    iter-&gt;Seek("");
 
3247
          //    return iter;
 
3248
          // If you are going to immediately seek to another place in the
 
3249
          // returned iterator, it will be faster to use NewIterator()
 
3250
          // and avoid the extra seek.
 
3251
          Iterator* GetIterator() const;
 
3252
        </CODE_SNIPPET>
 
3253
        <p>
 
3254
          However, do not be unnecessarily verbose or state the
 
3255
          completely obvious.  Notice below that it is not necessary
 
3256
          to say "returns false otherwise" because this is implied.
 
3257
        </p>
 
3258
        <CODE_SNIPPET>
 
3259
          // Returns true if the table cannot hold any more entries.
 
3260
          bool IsTableFull();
 
3261
        </CODE_SNIPPET>
 
3262
        <p>
 
3263
          When commenting constructors and destructors, remember that
 
3264
          the person reading your code knows what constructors and
 
3265
          destructors are for, so comments that just say something like
 
3266
          "destroys this object" are not useful.  Document what
 
3267
          constructors do with their arguments (for example, if they
 
3268
          take ownership of pointers), and what cleanup the destructor
 
3269
          does.  If this is trivial, just skip the comment.  It is
 
3270
          quite common for destructors not to have a header comment.
 
3271
        </p>
 
3272
      </SUBSECTION>
 
3273
 
 
3274
      <SUBSECTION title="Function Definitions">
 
3275
        <p>
 
3276
          Each function definition should have a comment describing
 
3277
          what the function does if there's anything tricky about how it does
 
3278
          its job.  For example, in the definition comment you might
 
3279
          describe any coding tricks you use, give an overview of the
 
3280
          steps you go through, or explain why you chose to implement
 
3281
          the function in the way you did rather than using a viable
 
3282
          alternative.  For instance, you might mention why it must
 
3283
          acquire a lock for the first half of the function but why it
 
3284
          is not needed for the second half.
 
3285
        </p>
 
3286
        <p>
 
3287
          Note you should <em>not</em> just repeat the comments given
 
3288
          with the function declaration, in the <code>.h</code> file or
 
3289
          wherever.  It's okay to recapitulate briefly what the function
 
3290
          does, but the focus of the comments should be on how it does it.
 
3291
        </p>
 
3292
      </SUBSECTION>
 
3293
    </BODY>
 
3294
  </STYLEPOINT>
 
3295
 
 
3296
  <STYLEPOINT title="Variable Comments">
 
3297
    <SUMMARY>
 
3298
      In general the actual name of the variable should be descriptive
 
3299
      enough to give a good idea of what the variable is used for.  In
 
3300
      certain cases, more comments are required.
 
3301
    </SUMMARY>
 
3302
    <BODY>
 
3303
      <SUBSECTION title="Class Data Members">
 
3304
        <p>
 
3305
          Each class data member (also called an instance variable or
 
3306
          member variable) should have a comment describing what it is
 
3307
          used for.  If the variable can take sentinel values with
 
3308
          special meanings, such as <code>NULL</code> or -1, document this.
 
3309
          For example:
 
3310
        </p>
 
3311
        <CODE_SNIPPET>
 
3312
          private:
 
3313
           // Keeps track of the total number of entries in the table.
 
3314
           // Used to ensure we do not go over the limit. -1 means
 
3315
           // that we don't yet know how many entries the table has.
 
3316
           int num_total_entries_;
 
3317
        </CODE_SNIPPET>
 
3318
      </SUBSECTION>
 
3319
 
 
3320
      <SUBSECTION title="Global Variables">
 
3321
        <p>
 
3322
          As with data members, all global variables should have a
 
3323
          comment describing what they are and what they are used for.
 
3324
          For example:
 
3325
        </p>
 
3326
        <CODE_SNIPPET>
 
3327
          // The total number of tests cases that we run through in this regression test.
 
3328
          const int kNumTestCases = 6;
 
3329
        </CODE_SNIPPET>
 
3330
      </SUBSECTION>
 
3331
    </BODY>
 
3332
  </STYLEPOINT>
 
3333
 
 
3334
  <STYLEPOINT title="Implementation Comments">
 
3335
    <SUMMARY>
 
3336
      In your implementation you should have comments in tricky,
 
3337
      non-obvious, interesting, or important parts of your code.
 
3338
    </SUMMARY>
 
3339
    <BODY>
 
3340
      <SUBSECTION title="Class Data Members">
 
3341
        <p>
 
3342
          Tricky or complicated code blocks should have comments
 
3343
          before them. Example:
 
3344
        </p>
 
3345
        <CODE_SNIPPET>
 
3346
          // Divide result by two, taking into account that x
 
3347
          // contains the carry from the add.
 
3348
          for (int i = 0; i &lt; result-&gt;size(); i++) {
 
3349
            x = (x &lt;&lt; 8) + (*result)[i];
 
3350
            (*result)[i] = x &gt;&gt; 1;
 
3351
            x &amp;= 1;
 
3352
          }
 
3353
        </CODE_SNIPPET>
 
3354
      </SUBSECTION>
 
3355
      <SUBSECTION title="Line Comments">
 
3356
        <p>
 
3357
          Also, lines that are non-obvious should get a comment at the
 
3358
          end of the line. These end-of-line comments should be
 
3359
          separated from the code by 2 spaces.  Example:
 
3360
        </p>
 
3361
        <CODE_SNIPPET>
 
3362
          // If we have enough memory, mmap the data portion too.
 
3363
          mmap_budget = max&lt;int64&gt;(0, mmap_budget - index_-&gt;length());
 
3364
          if (mmap_budget &gt;= data_size_ &amp;&amp; !MmapData(mmap_chunk_bytes, mlock))
 
3365
            return;  // Error already logged.
 
3366
        </CODE_SNIPPET>
 
3367
        <p>
 
3368
          Note that there are both comments that describe what the
 
3369
          code is doing, and comments that mention that an error has
 
3370
          already been logged when the function returns.
 
3371
        </p>
 
3372
        <p>
 
3373
          If you have several comments on subsequent lines, it can
 
3374
          often be more readable to line them up:
 
3375
        </p>
 
3376
        <CODE_SNIPPET>
 
3377
          DoSomething();                  // Comment here so the comments line up.
 
3378
          DoSomethingElseThatIsLonger();  // Comment here so there are two spaces between
 
3379
                                          // the code and the comment.
 
3380
          { // One space before comment when opening a new scope is allowed,
 
3381
            // thus the comment lines up with the following comments and code.
 
3382
            DoSomethingElse();  // Two spaces before line comments normally.
 
3383
          }
 
3384
        </CODE_SNIPPET>
 
3385
      </SUBSECTION>
 
3386
      <SUBSECTION title="NULL, true/false, 1, 2, 3...">
 
3387
        <p>
 
3388
          When you pass in <code>NULL</code>, boolean, or literal integer
 
3389
          values to functions, you should consider adding a comment about
 
3390
          what they are, or make your code self-documenting by using
 
3391
          constants. For example, compare:
 
3392
        </p>
 
3393
        <BAD_CODE_SNIPPET>
 
3394
          bool success = CalculateSomething(interesting_value,
 
3395
                                            10,
 
3396
                                            false,
 
3397
                                            NULL);  // What are these arguments??
 
3398
        </BAD_CODE_SNIPPET>
 
3399
        <p>
 
3400
          versus:
 
3401
        </p>
 
3402
        <CODE_SNIPPET>
 
3403
          bool success = CalculateSomething(interesting_value,
 
3404
                                            10,     // Default base value.
 
3405
                                            false,  // Not the first time we're calling this.
 
3406
                                            NULL);  // No callback.
 
3407
        </CODE_SNIPPET>
 
3408
        <p>
 
3409
          Or alternatively, constants or self-describing variables:
 
3410
        </p>
 
3411
        <CODE_SNIPPET>
 
3412
          const int kDefaultBaseValue = 10;
 
3413
          const bool kFirstTimeCalling = false;
 
3414
          Callback *null_callback = NULL;
 
3415
          bool success = CalculateSomething(interesting_value,
 
3416
                                            kDefaultBaseValue,
 
3417
                                            kFirstTimeCalling,
 
3418
                                            null_callback);
 
3419
        </CODE_SNIPPET>
 
3420
      </SUBSECTION>
 
3421
 
 
3422
      <SUBSECTION title="Don'ts">
 
3423
        <p>
 
3424
          Note that you should <em>never</em> describe the code
 
3425
          itself. Assume that the person reading the code knows C++
 
3426
          better than you do, even though he or she does not know what
 
3427
          you are trying to do:
 
3428
        </p>
 
3429
        <BAD_CODE_SNIPPET>
 
3430
           // Now go through the b array and make sure that if i occurs,
 
3431
           // the next element is i+1.
 
3432
           ...        // Geez.  What a useless comment.
 
3433
        </BAD_CODE_SNIPPET>
 
3434
      </SUBSECTION>
 
3435
    </BODY>
 
3436
  </STYLEPOINT>
 
3437
 
 
3438
  <STYLEPOINT title="Punctuation, Spelling and Grammar">
 
3439
    <SUMMARY>
 
3440
      Pay attention to punctuation, spelling, and grammar; it is
 
3441
      easier to read well-written comments than badly written ones.
 
3442
    </SUMMARY>
 
3443
    <BODY>
 
3444
      <p>
 
3445
        Comments should usually be written as complete
 
3446
        sentences with proper capitalization and periods at the end.
 
3447
        Shorter comments, such as comments at the end of a line of
 
3448
        code, can sometimes be less formal, but you should be
 
3449
        consistent with your style.  Complete sentences are more
 
3450
        readable, and they provide some assurance that the comment is
 
3451
        complete and not an unfinished thought.
 
3452
      </p>
 
3453
      <p>
 
3454
        Although it can be frustrating to have a code reviewer point
 
3455
        out that you are using a comma when you should be using a
 
3456
        semicolon, it is very important that source code maintain a
 
3457
        high level of clarity and readability.  Proper punctuation,
 
3458
        spelling, and grammar help with that goal.
 
3459
      </p>
 
3460
    </BODY>
 
3461
  </STYLEPOINT>
 
3462
 
 
3463
  <STYLEPOINT title="TODO Comments">
 
3464
    <SUMMARY>
 
3465
      Use <code>TODO</code> comments for code that is temporary, a
 
3466
      short-term solution, or good-enough but not perfect.
 
3467
    </SUMMARY>
 
3468
    <BODY>
 
3469
      <p>
 
3470
        <code>TODO</code>s should include the string <code>TODO</code> in
 
3471
        all caps, followed by the
 
3472
        
 
3473
        name, e-mail address, or other
 
3474
        identifier
 
3475
        of the person who can best provide context about the problem
 
3476
        referenced by the <code>TODO</code>.  A colon is optional.  The main
 
3477
        purpose is to have a consistent <code>TODO</code> format that can be
 
3478
        searched to find the person who can provide more details upon request.
 
3479
        A <code>TODO</code> is not a commitment that the person referenced
 
3480
        will fix the problem.  Thus when you create a <code>TODO</code>, it is
 
3481
        almost always your
 
3482
        
 
3483
        name
 
3484
        that is given.
 
3485
      </p>
 
3486
      
 
3487
      <CODE_SNIPPET>
 
3488
        // TODO(kl@gmail.com): Use a "*" here for concatenation operator.
 
3489
        // TODO(Zeke) change this to use relations.
 
3490
      </CODE_SNIPPET>
 
3491
      <p>
 
3492
        If your <code>TODO</code> is of the form "At a future date do
 
3493
        something" make sure that you either include a very specific
 
3494
        date ("Fix by November 2005") or a very specific event
 
3495
        ("Remove this code when all clients can handle XML responses.").
 
3496
      </p>
 
3497
    </BODY>
 
3498
  </STYLEPOINT>
 
3499
 
 
3500
  <STYLEPOINT title="Deprecation Comments">
 
3501
    <SUMMARY>
 
3502
      Mark deprecated interface points with <code>DEPRECATED</code> comments.
 
3503
    </SUMMARY>
 
3504
    <BODY>
 
3505
      <p>
 
3506
      You can mark an interface as deprecated by writing a comment containing
 
3507
      the word <code>DEPRECATED</code> in all caps.  The comment goes either
 
3508
      before the declaration of the interface or on the same line as the
 
3509
      declaration.
 
3510
      </p>
 
3511
      
 
3512
      <p>
 
3513
      After the word <code>DEPRECATED</code>, write your name, e-mail address,
 
3514
      or other identifier in parentheses.
 
3515
      </p>
 
3516
      <p>
 
3517
      A deprecation comment must include simple, clear directions for people to
 
3518
      fix their callsites.  In C++, you can implement a deprecated function as
 
3519
      an inline function that calls the new interface point.
 
3520
      </p>
 
3521
      <p>
 
3522
      Marking an interface point <code>DEPRECATED</code> will not magically
 
3523
      cause any callsites to change.  If you want people to actually stop using
 
3524
      the deprecated facility, you will have to fix the callsites yourself or
 
3525
      recruit a crew to help you.
 
3526
      </p>
 
3527
      <p>
 
3528
      New code should not contain calls to deprecated interface points.  Use
 
3529
      the new interface point instead.  If you cannot understand the
 
3530
      directions, find the person who created the deprecation and ask them for
 
3531
      help using the new interface point.
 
3532
      </p>
 
3533
      
 
3534
    </BODY>
 
3535
  </STYLEPOINT>
 
3536
 
 
3537
</CATEGORY>
 
3538
 
 
3539
<CATEGORY title="Formatting">
 
3540
  <p>
 
3541
    Coding style and formatting are pretty arbitrary, but a
 
3542
    
 
3543
    project
 
3544
    is much easier to follow if everyone uses the same style. Individuals
 
3545
    may not agree with every aspect of the formatting rules, and some of
 
3546
    the rules may take some getting used to, but it is important that all
 
3547
    
 
3548
    project contributors
 
3549
    follow the style rules so that
 
3550
    
 
3551
    they
 
3552
    can all read and understand everyone's code easily.
 
3553
  </p>
 
3554
  
 
3555
  <p>
 
3556
    To help you format code correctly, we've created a <A HREF="http://google-styleguide.googlecode.com/svn/trunk/google-c-style.el">settings
 
3557
    file for emacs</A>.
 
3558
  </p>
 
3559
 
 
3560
  <STYLEPOINT title="Line Length">
 
3561
    <SUMMARY>
 
3562
      Each line of text in your code should be at most 80 characters
 
3563
      long.
 
3564
    </SUMMARY>
 
3565
    <BODY>
 
3566
      
 
3567
      <p>
 
3568
        We recognize that this rule is controversial, but so much existing
 
3569
        code already adheres to it, and we feel that consistency is
 
3570
        important.
 
3571
      </p>
 
3572
      <PROS>
 
3573
          Those who favor
 
3574
          
 
3575
          this rule argue
 
3576
          that it is rude to force them to resize their windows and there
 
3577
          is no need for anything longer.  Some folks are used to having
 
3578
          several code windows side-by-side, and thus don't have room to
 
3579
          widen their windows in any case.  People set up their work
 
3580
          environment assuming a particular maximum window width, and 80
 
3581
          columns has been the traditional standard.  Why change it?
 
3582
      </PROS>
 
3583
      <CONS>
 
3584
          Proponents of change argue that a wider line can make code
 
3585
          more readable.  The 80-column limit is an hidebound
 
3586
          throwback to 1960s mainframes;
 
3587
          
 
3588
          modern equipment has
 
3589
          wide screens that can easily show longer lines.
 
3590
      </CONS>
 
3591
      <DECISION>
 
3592
        <p>
 
3593
          
 
3594
          80 characters is the maximum.
 
3595
        </p>
 
3596
        <p>
 
3597
          Exception: if a comment line contains an example command or
 
3598
          a literal URL longer than 80 characters, that line may be
 
3599
          longer than 80 characters for ease of cut and paste.
 
3600
        </p>
 
3601
        <p>
 
3602
          Exception: an <code>#include</code> statement with a long
 
3603
          path may exceed 80 columns.  Try to avoid situations where this
 
3604
          becomes necessary.
 
3605
        </p>
 
3606
        <p>
 
3607
          Exception:  you needn't be concerned about
 
3608
          <a href="#The__define_Guard">header guards</a>
 
3609
          that exceed the maximum length.
 
3610
          
 
3611
        </p>
 
3612
      </DECISION>
 
3613
    </BODY>
 
3614
  </STYLEPOINT>
 
3615
 
 
3616
  <STYLEPOINT title="Non-ASCII Characters">
 
3617
    <SUMMARY>
 
3618
      Non-ASCII characters should be rare, and must use UTF-8 formatting.
 
3619
    </SUMMARY>
 
3620
    <BODY>
 
3621
      <p>
 
3622
        You shouldn't hard-code user-facing text in source, even English,
 
3623
        so use of non-ASCII characters should be rare.  However, in certain
 
3624
        cases it is appropriate to include such words in your code.  For
 
3625
        example, if your code parses data files from foreign sources,
 
3626
        it may be appropriate to hard-code the non-ASCII string(s) used in
 
3627
        those data files as delimiters.  More commonly, unittest code
 
3628
        (which does not
 
3629
        
 
3630
        need to be localized) might contain non-ASCII strings.  In such
 
3631
        cases, you should use UTF-8, since that is
 
3632
        
 
3633
        an encoding understood by most tools able
 
3634
        to handle more than just ASCII.
 
3635
        Hex encoding is also OK, and encouraged where it enhances
 
3636
        readability &#8212; for example, <code>"\xEF\xBB\xBF"</code> is the
 
3637
        Unicode zero-width no-break space character, which would be
 
3638
        invisible if included in the source as straight UTF-8.
 
3639
      </p>
 
3640
    </BODY>
 
3641
  </STYLEPOINT>
 
3642
 
 
3643
  <STYLEPOINT title="Spaces vs. Tabs">
 
3644
    <SUMMARY>
 
3645
      Use only spaces, and indent 2 spaces at a time.
 
3646
    </SUMMARY>
 
3647
    <BODY>
 
3648
      <p>
 
3649
        We use spaces for indentation. Do not use tabs in your code.
 
3650
        You should set your editor to emit spaces when you hit the tab
 
3651
        key.
 
3652
      </p>
 
3653
    </BODY>
 
3654
  </STYLEPOINT>
 
3655
 
 
3656
  <STYLEPOINT title="Function Declarations and Definitions">
 
3657
    <SUMMARY>
 
3658
      Return type on the same line as function name, parameters on the
 
3659
      same line if they fit.
 
3660
    </SUMMARY>
 
3661
    <BODY>
 
3662
      <p>
 
3663
        Functions look like this:
 
3664
      </p>
 
3665
      <CODE_SNIPPET>
 
3666
        ReturnType ClassName::FunctionName(Type par_name1, Type par_name2) {
 
3667
          DoSomething();
 
3668
          ...
 
3669
        }
 
3670
      </CODE_SNIPPET>
 
3671
      <p>
 
3672
        If you have too much text to fit on one line:
 
3673
      </p>
 
3674
      <CODE_SNIPPET>
 
3675
        ReturnType ClassName::ReallyLongFunctionName(Type par_name1, Type par_name2,
 
3676
                                                     Type par_name3) {
 
3677
          DoSomething();
 
3678
          ...
 
3679
        }
 
3680
      </CODE_SNIPPET>
 
3681
      <p>
 
3682
        or if you cannot fit even the first parameter:
 
3683
      </p>
 
3684
      <CODE_SNIPPET>
 
3685
        ReturnType LongClassName::ReallyReallyReallyLongFunctionName(
 
3686
            Type par_name1,  // 4 space indent
 
3687
            Type par_name2,
 
3688
            Type par_name3) {
 
3689
          DoSomething();  // 2 space indent
 
3690
          ...
 
3691
        }
 
3692
      </CODE_SNIPPET>
 
3693
      <p>
 
3694
        Some points to note:
 
3695
      </p>
 
3696
      <ul>
 
3697
        <li> The return type is always on the same line as the
 
3698
             function name.
 
3699
             </li>
 
3700
        <li> The open parenthesis is always on the same line as the
 
3701
             function name.
 
3702
             </li>
 
3703
        <li> There is never a space between the function name and the
 
3704
             open parenthesis.
 
3705
             </li>
 
3706
        <li> There is never a space between the parentheses and the
 
3707
             parameters.
 
3708
             </li>
 
3709
        <li> The open curly brace is always at the end of the same
 
3710
             line as the last parameter.
 
3711
             </li>
 
3712
        <li> The close curly brace is either on the last line by itself
 
3713
             or (if other style rules permit) on the same line as the
 
3714
             open curly brace.
 
3715
             </li>
 
3716
        <li> There should be a space between the close parenthesis and
 
3717
             the open curly brace.
 
3718
             </li>
 
3719
        <li> All parameters should be named, with identical names in the
 
3720
             declaration and implementation.
 
3721
             </li>
 
3722
        <li> All parameters should be aligned if possible.
 
3723
             </li>
 
3724
        <li> Default indentation is 2 spaces.
 
3725
             </li>
 
3726
        <li> Wrapped parameters have a 4 space indent.
 
3727
             </li>
 
3728
      </ul>
 
3729
      <p>
 
3730
        If your function is <code>const</code>, the <code>const</code>
 
3731
        keyword should be on the same line as the last parameter:
 
3732
      </p>
 
3733
      <CODE_SNIPPET>
 
3734
        // Everything in this function signature fits on a single line
 
3735
        ReturnType FunctionName(Type par) const {
 
3736
          ...
 
3737
        }
 
3738
 
 
3739
        // This function signature requires multiple lines, but
 
3740
        // the const keyword is on the line with the last parameter.
 
3741
        ReturnType ReallyLongFunctionName(Type par1,
 
3742
                                          Type par2) const {
 
3743
          ...
 
3744
        }
 
3745
      </CODE_SNIPPET>
 
3746
      <p>
 
3747
        If some parameters are unused, comment out the variable name in the
 
3748
        function definition:
 
3749
      </p>
 
3750
      <CODE_SNIPPET>
 
3751
        // Always have named parameters in interfaces.
 
3752
        class Shape {
 
3753
         public:
 
3754
          virtual void Rotate(double radians) = 0;
 
3755
        }
 
3756
 
 
3757
        // Always have named parameters in the declaration.
 
3758
        class Circle : public Shape {
 
3759
         public:
 
3760
          virtual void Rotate(double radians);
 
3761
        }
 
3762
 
 
3763
        // Comment out unused named parameters in definitions.
 
3764
        void Circle::Rotate(double /*radians*/) {}
 
3765
      </CODE_SNIPPET>
 
3766
      <BAD_CODE_SNIPPET>
 
3767
        // Bad - if someone wants to implement later, it's not clear what the
 
3768
        // variable means.
 
3769
        void Circle::Rotate(double) {}
 
3770
      </BAD_CODE_SNIPPET>
 
3771
    </BODY>
 
3772
  </STYLEPOINT>
 
3773
 
 
3774
  <STYLEPOINT title="Function Calls">
 
3775
    <SUMMARY>
 
3776
      On one line if it fits; otherwise, wrap arguments at the
 
3777
      parenthesis.
 
3778
    </SUMMARY>
 
3779
    <BODY>
 
3780
      <p>
 
3781
        Function calls have the following format:
 
3782
      </p>
 
3783
      <CODE_SNIPPET>
 
3784
        bool retval = DoSomething(argument1, argument2, argument3);
 
3785
      </CODE_SNIPPET>
 
3786
      <p>
 
3787
        If the arguments do not all fit on one line, they should be
 
3788
        broken up onto multiple lines, with each subsequent line
 
3789
        aligned with the first argument.  Do not add spaces after the
 
3790
        open paren or before the close paren:
 
3791
      </p>
 
3792
      <CODE_SNIPPET>
 
3793
        bool retval = DoSomething(averyveryveryverylongargument1,
 
3794
                                  argument2, argument3);
 
3795
      </CODE_SNIPPET>
 
3796
      <p>
 
3797
        If the function has many arguments, consider having one per
 
3798
        line if this makes the code more readable:
 
3799
      </p>
 
3800
      <CODE_SNIPPET>
 
3801
        bool retval = DoSomething(argument1,
 
3802
                                  argument2,
 
3803
                                  argument3,
 
3804
                                  argument4);
 
3805
      </CODE_SNIPPET>
 
3806
      <p>
 
3807
        If the function signature is so long that it cannot fit within
 
3808
        the maximum <a href="#Line_Length">line length</a>, you may
 
3809
        place all arguments on subsequent lines:
 
3810
      </p>
 
3811
      <CODE_SNIPPET>
 
3812
        if (...) {
 
3813
          ...
 
3814
          ...
 
3815
          if (...) {
 
3816
            DoSomethingThatRequiresALongFunctionName(
 
3817
                very_long_argument1,  // 4 space indent
 
3818
                argument2,
 
3819
                argument3,
 
3820
                argument4);
 
3821
          }
 
3822
      </CODE_SNIPPET>
 
3823
    </BODY>
 
3824
  </STYLEPOINT>
 
3825
 
 
3826
  <STYLEPOINT title="Conditionals">
 
3827
    <SUMMARY>
 
3828
      Prefer no spaces inside parentheses.  The <code>else</code>
 
3829
      keyword belongs on a new line.
 
3830
    </SUMMARY>
 
3831
    <BODY>
 
3832
      <p>
 
3833
        There are two acceptable formats for a basic conditional
 
3834
        statement. One includes spaces between the parentheses and the
 
3835
        condition, and one does not.
 
3836
      </p>
 
3837
      <p>
 
3838
        The most common form is without spaces.  Either is fine, but
 
3839
        <em>be consistent</em>. If you are modifying a file, use the
 
3840
        format that is already present. If you are writing new code,
 
3841
        use the format that the other files in that directory or
 
3842
        project use. If in doubt and you have no personal preference,
 
3843
        do not add the spaces.
 
3844
      </p>
 
3845
      <CODE_SNIPPET>
 
3846
        if (condition) {  // no spaces inside parentheses
 
3847
          ...  // 2 space indent.
 
3848
        } else {  // The else goes on the same line as the closing brace.
 
3849
          ...
 
3850
        }
 
3851
      </CODE_SNIPPET>
 
3852
      <p>
 
3853
        If you prefer you may add spaces inside the
 
3854
        parentheses:
 
3855
      </p>
 
3856
      <CODE_SNIPPET>
 
3857
        if ( condition ) {  // spaces inside parentheses - rare
 
3858
          ...  // 2 space indent.
 
3859
        } else {  // The else goes on the same line as the closing brace.
 
3860
          ...
 
3861
        }
 
3862
      </CODE_SNIPPET>
 
3863
      <p>
 
3864
        Note that in all cases you must have a space between the
 
3865
        <code>if</code> and the open parenthesis.  You must also have
 
3866
        a space between the close parenthesis and the curly brace, if
 
3867
        you're using one.
 
3868
      </p>
 
3869
      <BAD_CODE_SNIPPET>
 
3870
        if(condition)     // Bad - space missing after IF.
 
3871
        if (condition){   // Bad - space missing before {.
 
3872
        if(condition){    // Doubly bad.
 
3873
      </BAD_CODE_SNIPPET>
 
3874
      <CODE_SNIPPET>
 
3875
        if (condition) {  // Good - proper space after IF and before {.
 
3876
      </CODE_SNIPPET>
 
3877
      <p>
 
3878
        Short conditional statements may be written on one line if
 
3879
        this enhances readability.  You may use this only when the
 
3880
        line is brief and the statement does not use the
 
3881
        <code>else</code> clause.
 
3882
      </p>
 
3883
      <CODE_SNIPPET>
 
3884
        if (x == kFoo) return new Foo();
 
3885
        if (x == kBar) return new Bar();
 
3886
      </CODE_SNIPPET>
 
3887
      <p>
 
3888
        This is not allowed when the if statement has an
 
3889
        <code>else</code>:
 
3890
      </p>
 
3891
      <BAD_CODE_SNIPPET>
 
3892
        // Not allowed - IF statement on one line when there is an ELSE clause
 
3893
        if (x) DoThis();
 
3894
        else DoThat();
 
3895
      </BAD_CODE_SNIPPET>
 
3896
      <p>
 
3897
        In general, curly braces are not required for single-line
 
3898
        statements, but they are allowed if you like them;
 
3899
        conditional or loop statements with complex conditions or
 
3900
        statements may be more readable with curly braces. Some
 
3901
        
 
3902
        projects
 
3903
        require that an <CODE>if</CODE> must always always have an
 
3904
        accompanying brace.
 
3905
      </p>
 
3906
      <CODE_SNIPPET>
 
3907
        if (condition)
 
3908
          DoSomething();  // 2 space indent.
 
3909
 
 
3910
        if (condition) {
 
3911
          DoSomething();  // 2 space indent.
 
3912
        }
 
3913
      </CODE_SNIPPET>
 
3914
      <p>
 
3915
        However, if one part of an <code>if</code>-<code>else</code>
 
3916
        statement uses curly braces, the other part must too:
 
3917
      </p>
 
3918
      <BAD_CODE_SNIPPET>
 
3919
        // Not allowed - curly on IF but not ELSE
 
3920
        if (condition) {
 
3921
          foo;
 
3922
        } else
 
3923
          bar;
 
3924
 
 
3925
        // Not allowed - curly on ELSE but not IF
 
3926
        if (condition)
 
3927
          foo;
 
3928
        else {
 
3929
          bar;
 
3930
        }
 
3931
      </BAD_CODE_SNIPPET>
 
3932
      <CODE_SNIPPET>
 
3933
        // Curly braces around both IF and ELSE required because
 
3934
        // one of the clauses used braces.
 
3935
        if (condition) {
 
3936
          foo;
 
3937
        } else {
 
3938
          bar;
 
3939
        }
 
3940
      </CODE_SNIPPET>
 
3941
    </BODY>
 
3942
  </STYLEPOINT>
 
3943
 
 
3944
  <STYLEPOINT title="Loops and Switch Statements">
 
3945
    <SUMMARY>
 
3946
      Switch statements may use braces for blocks.  Empty loop bodies should use
 
3947
      <code>{}</code> or <code>continue</code>.
 
3948
    </SUMMARY>
 
3949
    <BODY>
 
3950
      <p>
 
3951
        <code>case</code> blocks in <code>switch</code> statements can have
 
3952
        curly braces or not, depending on your preference.  If you do
 
3953
        include curly braces they should be placed as shown below.
 
3954
      </p>
 
3955
      <p>
 
3956
        If not conditional on an enumerated value, switch statements
 
3957
        should always have a <code>default</code> case (in the case of
 
3958
        an enumerated value, the compiler will warn you if any values
 
3959
        are not handled).  If the default case should never execute,
 
3960
        simply
 
3961
        <code>assert</code>:
 
3962
      </p>
 
3963
      
 
3964
      <CODE_SNIPPET>
 
3965
        switch (var) {
 
3966
          case 0: {  // 2 space indent
 
3967
            ...      // 4 space indent
 
3968
            break;
 
3969
          }
 
3970
          case 1: {
 
3971
            ...
 
3972
            break;
 
3973
          }
 
3974
          default: {
 
3975
            assert(false);
 
3976
          }
 
3977
        }
 
3978
      </CODE_SNIPPET>
 
3979
      <p>
 
3980
        Empty loop bodies should use <code>{}</code> or
 
3981
        <code>continue</code>, but not a single semicolon.
 
3982
      </p>
 
3983
      <CODE_SNIPPET>
 
3984
        while (condition) {
 
3985
          // Repeat test until it returns false.
 
3986
        }
 
3987
        for (int i = 0; i &lt; kSomeNumber; ++i) {}  // Good - empty body.
 
3988
        while (condition) continue;  // Good - continue indicates no logic.
 
3989
      </CODE_SNIPPET>
 
3990
      <BAD_CODE_SNIPPET>
 
3991
        while (condition);  // Bad - looks like part of do/while loop.
 
3992
      </BAD_CODE_SNIPPET>
 
3993
    </BODY>
 
3994
  </STYLEPOINT>
 
3995
 
 
3996
  <STYLEPOINT title="Pointer and Reference Expressions">
 
3997
    <SUMMARY>
 
3998
      No spaces around period or arrow.  Pointer operators do not have
 
3999
      trailing spaces.
 
4000
    </SUMMARY>
 
4001
    <BODY>
 
4002
      <p>
 
4003
        The following are examples of correctly-formatted pointer and
 
4004
        reference expressions:
 
4005
      </p>
 
4006
      <CODE_SNIPPET>
 
4007
        x = *p;
 
4008
        p = &amp;x;
 
4009
        x = r.y;
 
4010
        x = r-&gt;y;
 
4011
      </CODE_SNIPPET>
 
4012
      <p>
 
4013
        Note that:
 
4014
      </p>
 
4015
      <ul>
 
4016
        <li> There are no spaces around the period or arrow when
 
4017
             accessing a member.
 
4018
             </li>
 
4019
        <li> Pointer operators have no space after the <code>*</code> or
 
4020
             <code>&amp;</code>.
 
4021
             </li>
 
4022
      </ul>
 
4023
      <p>
 
4024
        When declaring a pointer variable or argument, you may place
 
4025
        the asterisk adjacent to either the type or to the variable
 
4026
        name:
 
4027
      </p>
 
4028
      <CODE_SNIPPET>
 
4029
        // These are fine, space preceding.
 
4030
        char *c;
 
4031
        const string &amp;str;
 
4032
 
 
4033
        // These are fine, space following.
 
4034
        char* c;    // but remember to do "char* c, *d, *e, ...;"!
 
4035
        const string&amp; str;
 
4036
      </CODE_SNIPPET>
 
4037
      <BAD_CODE_SNIPPET>
 
4038
        char * c;  // Bad - spaces on both sides of *
 
4039
        const string &amp; str;  // Bad - spaces on both sides of &amp;
 
4040
      </BAD_CODE_SNIPPET>
 
4041
      <p>
 
4042
        You should do this consistently within a single
 
4043
        file,
 
4044
        so, when modifying an existing file, use the style in that
 
4045
        file.
 
4046
      </p>
 
4047
    </BODY>
 
4048
  </STYLEPOINT>
 
4049
 
 
4050
  <STYLEPOINT title="Boolean Expressions">
 
4051
    <SUMMARY>
 
4052
      When you have a boolean expression that is longer than the <a href="#Line_Length">standard line length</a>, be consistent in
 
4053
      how you break up the lines.
 
4054
    </SUMMARY>
 
4055
    <BODY>
 
4056
      <p>
 
4057
        In this example, the logical AND operator is always at the end
 
4058
        of the lines:
 
4059
      </p>
 
4060
      <CODE_SNIPPET>
 
4061
        if (this_one_thing &gt; this_other_thing &amp;&amp;
 
4062
            a_third_thing == a_fourth_thing &amp;&amp;
 
4063
            yet_another &amp;&amp; last_one) {
 
4064
          ...
 
4065
        }
 
4066
      </CODE_SNIPPET>
 
4067
      <p>
 
4068
        Note that when the code wraps in this example, both of
 
4069
        the <code>&amp;&amp;</code> logical AND operators are at the
 
4070
        end of the line.  This is more common in Google code, though
 
4071
        wrapping all operators at the beginning of the line is also
 
4072
        allowed.  Feel free to insert extra parentheses judiciously,
 
4073
        because they can be very helpful in increasing readability
 
4074
        when used appropriately.  Also note that you should always use the
 
4075
        punctuation operators, such as <code>&amp;&amp;</code> and
 
4076
        <code>~</code>, rather than the word operators, such as <code>and</code>
 
4077
        and <code>compl</code>.
 
4078
      </p>
 
4079
    </BODY>
 
4080
  </STYLEPOINT>
 
4081
 
 
4082
  <STYLEPOINT title="Return Values">
 
4083
    <SUMMARY>
 
4084
      Do not needlessly surround the <code>return</code> expression with
 
4085
      parentheses.
 
4086
    </SUMMARY>
 
4087
    <BODY>
 
4088
      <p>
 
4089
        Use parentheses in <code>return expr;</code> only where you would use
 
4090
        them in <code>x = expr;</code>.
 
4091
      </p>
 
4092
      <CODE_SNIPPET>
 
4093
        return result;                  // No parentheses in the simple case.
 
4094
        return (some_long_condition &amp;&amp;  // Parentheses ok to make a complex
 
4095
                another_condition);     //     expression more readable.
 
4096
      </CODE_SNIPPET>
 
4097
      <BAD_CODE_SNIPPET>
 
4098
        return (value);                // You wouldn't write var = (value);
 
4099
        return(result);                // return is not a function!
 
4100
      </BAD_CODE_SNIPPET>
 
4101
    </BODY>
 
4102
  </STYLEPOINT>
 
4103
 
 
4104
  
 
4105
 
 
4106
  <STYLEPOINT title="Variable and Array Initialization">
 
4107
    <SUMMARY>
 
4108
      Your choice of <code>=</code> or <code>()</code>.
 
4109
    </SUMMARY>
 
4110
    <BODY>
 
4111
      <p>
 
4112
        You may choose between <code>=</code> and <code>()</code>; the
 
4113
        following are all correct:
 
4114
      </p>
 
4115
      <CODE_SNIPPET>
 
4116
        int x = 3;
 
4117
        int x(3);
 
4118
        string name("Some Name");
 
4119
        string name = "Some Name";
 
4120
      </CODE_SNIPPET>
 
4121
    </BODY>
 
4122
  </STYLEPOINT>
 
4123
 
 
4124
  <STYLEPOINT title="Preprocessor Directives">
 
4125
    <SUMMARY>
 
4126
      The hash mark that starts a preprocessor directive should
 
4127
      always be at the beginning of the line.
 
4128
    </SUMMARY>
 
4129
    <BODY>
 
4130
      <p>
 
4131
        Even when preprocessor directives are within the body of
 
4132
        indented code, the directives should start at the beginning of
 
4133
        the line.
 
4134
      </p>
 
4135
      <CODE_SNIPPET>
 
4136
        // Good - directives at beginning of line
 
4137
          if (lopsided_score) {
 
4138
        #if DISASTER_PENDING      // Correct -- Starts at beginning of line
 
4139
            DropEverything();
 
4140
        # if NOTIFY               // OK but not required -- Spaces after #
 
4141
            NotifyClient();
 
4142
        # endif
 
4143
        #endif
 
4144
            BackToNormal();
 
4145
          }
 
4146
      </CODE_SNIPPET>
 
4147
      <BAD_CODE_SNIPPET>
 
4148
        // Bad - indented directives
 
4149
          if (lopsided_score) {
 
4150
            #if DISASTER_PENDING  // Wrong!  The "#if" should be at beginning of line
 
4151
            DropEverything();
 
4152
            #endif                // Wrong!  Do not indent "#endif"
 
4153
            BackToNormal();
 
4154
          }
 
4155
      </BAD_CODE_SNIPPET>
 
4156
    </BODY>
 
4157
  </STYLEPOINT>
 
4158
 
 
4159
  <STYLEPOINT title="Class Format">
 
4160
    <SUMMARY>
 
4161
      Sections in <code>public</code>, <code>protected</code> and
 
4162
      <code>private</code> order, each indented one space.
 
4163
    </SUMMARY>
 
4164
    <BODY>
 
4165
      <p>
 
4166
        The basic format for a class declaration (lacking the
 
4167
        comments, see <a HREF="#Class_Comments">Class Comments</a> for
 
4168
        a discussion of what comments are needed) is:
 
4169
      </p>
 
4170
      <CODE_SNIPPET>
 
4171
        class MyClass : public OtherClass {
 
4172
         public:      // Note the 1 space indent!
 
4173
          MyClass();  // Regular 2 space indent.
 
4174
          explicit MyClass(int var);
 
4175
          ~MyClass() {}
 
4176
 
 
4177
          void SomeFunction();
 
4178
          void SomeFunctionThatDoesNothing() {
 
4179
          }
 
4180
 
 
4181
          void set_some_var(int var) { some_var_ = var; }
 
4182
          int some_var() const { return some_var_; }
 
4183
 
 
4184
         private:
 
4185
          bool SomeInternalFunction();
 
4186
 
 
4187
          int some_var_;
 
4188
          int some_other_var_;
 
4189
          DISALLOW_COPY_AND_ASSIGN(MyClass);
 
4190
        };
 
4191
      </CODE_SNIPPET>
 
4192
      <p>
 
4193
        Things to note:
 
4194
      </p>
 
4195
      <ul>
 
4196
        <li> Any base class name should be on the same line as the
 
4197
             subclass name, subject to the 80-column limit.
 
4198
             </li>
 
4199
        <li> The <code>public:</code>, <code>protected:</code>, and
 
4200
             <code>private:</code> keywords should be indented one
 
4201
             space.
 
4202
             </li>
 
4203
        <li> Except for the first instance, these keywords should be preceded
 
4204
             by a blank line. This rule is optional in small classes.
 
4205
             </li>
 
4206
        <li> Do not leave a blank line after these keywords.
 
4207
             </li>
 
4208
        <li> The <code>public</code> section should be first, followed by
 
4209
             the <code>protected</code> and finally the
 
4210
             <code>private</code> section.
 
4211
             </li>
 
4212
        <li> See <a HREF="#Declaration_Order">Declaration Order</a> for
 
4213
             rules on ordering declarations within each of these sections.
 
4214
             </li>
 
4215
      </ul>
 
4216
    </BODY>
 
4217
  </STYLEPOINT>
 
4218
 
 
4219
  <STYLEPOINT title="Constructor Initializer Lists">
 
4220
    <SUMMARY>
 
4221
      Constructor initializer lists can be all on one line or with
 
4222
      subsequent lines indented four spaces.
 
4223
    </SUMMARY>
 
4224
    <BODY>
 
4225
      <p>
 
4226
        There are two acceptable formats for initializer lists:
 
4227
      </p>
 
4228
      <CODE_SNIPPET>
 
4229
        // When it all fits on one line:
 
4230
        MyClass::MyClass(int var) : some_var_(var), some_other_var_(var + 1) {}
 
4231
      </CODE_SNIPPET>
 
4232
      <p>
 
4233
        or
 
4234
      </p>
 
4235
      <CODE_SNIPPET>
 
4236
        // When it requires multiple lines, indent 4 spaces, putting the colon on
 
4237
        // the first initializer line:
 
4238
        MyClass::MyClass(int var)
 
4239
            : some_var_(var),             // 4 space indent
 
4240
              some_other_var_(var + 1) {  // lined up
 
4241
          ...
 
4242
          DoSomething();
 
4243
          ...
 
4244
        }
 
4245
      </CODE_SNIPPET>
 
4246
    </BODY>
 
4247
  </STYLEPOINT>
 
4248
 
 
4249
  <STYLEPOINT title="Namespace Formatting">
 
4250
    <SUMMARY>
 
4251
      The contents of namespaces are not indented.
 
4252
    </SUMMARY>
 
4253
    <BODY>
 
4254
      <p>
 
4255
        <a href="#Namespaces">Namespaces</a> do not add an extra level of
 
4256
        indentation. For example, use:
 
4257
      </p>
 
4258
      <CODE_SNIPPET>
 
4259
        namespace {
 
4260
 
 
4261
        void foo() {  // Correct.  No extra indentation within namespace.
 
4262
          ...
 
4263
        }
 
4264
 
 
4265
        }  // namespace
 
4266
      </CODE_SNIPPET>
 
4267
      <p>
 
4268
        Do not indent within a namespace:
 
4269
      </p>
 
4270
      <BAD_CODE_SNIPPET>
 
4271
        namespace {
 
4272
 
 
4273
          // Wrong.  Indented when it should not be.
 
4274
          void foo() {
 
4275
            ...
 
4276
          }
 
4277
 
 
4278
        }  // namespace
 
4279
      </BAD_CODE_SNIPPET>
 
4280
      <p>
 
4281
        When declaring nested namespaces, put each namespace on its own line.
 
4282
      </p>
 
4283
      <CODE_SNIPPET>
 
4284
        namespace foo {
 
4285
        namespace bar {
 
4286
      </CODE_SNIPPET>
 
4287
    </BODY>
 
4288
  </STYLEPOINT>
 
4289
 
 
4290
  <STYLEPOINT title="Horizontal Whitespace">
 
4291
    <SUMMARY>
 
4292
      Use of horizontal whitespace depends on location.  Never put trailing
 
4293
      whitespace at the end of a line.
 
4294
    </SUMMARY>
 
4295
    <BODY>
 
4296
      <SUBSECTION title="General">
 
4297
        <CODE_SNIPPET>
 
4298
        void f(bool b) {  // Open braces should always have a space before them.
 
4299
          ...
 
4300
        int i = 0;  // Semicolons usually have no space before them.
 
4301
        int x[] = { 0 };  // Spaces inside braces for array initialization are
 
4302
        int x[] = {0};    // optional.  If you use them, put them on both sides!
 
4303
        // Spaces around the colon in inheritance and initializer lists.
 
4304
        class Foo : public Bar {
 
4305
         public:
 
4306
          // For inline function implementations, put spaces between the braces
 
4307
          // and the implementation itself.
 
4308
          Foo(int b) : Bar(), baz_(b) {}  // No spaces inside empty braces.
 
4309
          void Reset() { baz_ = 0; }  // Spaces separating braces from implementation.
 
4310
          ...
 
4311
        </CODE_SNIPPET>
 
4312
        <p>
 
4313
          Adding trailing whitespace can cause extra work for others editing
 
4314
          the same file, when they merge, as can removing existing trailing
 
4315
          whitespace.  So:  Don't introduce trailing whitespace.  Remove it
 
4316
          if you're already changing that line, or do it in a separate
 
4317
          clean-up
 
4318
          
 
4319
          operation (preferably when no-one else
 
4320
          is working on the file).
 
4321
        </p>
 
4322
      </SUBSECTION>
 
4323
      <SUBSECTION title="Loops and Conditionals">
 
4324
        <CODE_SNIPPET>
 
4325
        if (b) {          // Space after the keyword in conditions and loops.
 
4326
        } else {          // Spaces around else.
 
4327
        }
 
4328
        while (test) {}   // There is usually no space inside parentheses.
 
4329
        switch (i) {
 
4330
        for (int i = 0; i &lt; 5; ++i) {
 
4331
        switch ( i ) {    // Loops and conditions may have spaces inside
 
4332
        if ( test ) {     // parentheses, but this is rare.  Be consistent.
 
4333
        for ( int i = 0; i &lt; 5; ++i ) {
 
4334
        for ( ; i &lt; 5 ; ++i) {  // For loops always have a space after the
 
4335
          ...                   // semicolon, and may have a space before the
 
4336
                                // semicolon.
 
4337
        switch (i) {
 
4338
          case 1:         // No space before colon in a switch case.
 
4339
            ...
 
4340
          case 2: break;  // Use a space after a colon if there's code after it.
 
4341
        </CODE_SNIPPET>
 
4342
      </SUBSECTION>
 
4343
      <SUBSECTION title="Operators">
 
4344
        <CODE_SNIPPET>
 
4345
        x = 0;              // Assignment operators always have spaces around
 
4346
                            // them.
 
4347
        x = -5;             // No spaces separating unary operators and their
 
4348
        ++x;                // arguments.
 
4349
        if (x &amp;&amp; !y)
 
4350
          ...
 
4351
        v = w * x + y / z;  // Binary operators usually have spaces around them,
 
4352
        v = w*x + y/z;      // but it's okay to remove spaces around factors.
 
4353
        v = w * (x + z);    // Parentheses should have no spaces inside them.
 
4354
        </CODE_SNIPPET>
 
4355
      </SUBSECTION>
 
4356
      <SUBSECTION title="Templates and Casts">
 
4357
        <CODE_SNIPPET>
 
4358
        vector&lt;string&gt; x;           // No spaces inside the angle
 
4359
        y = static_cast&lt;char*&gt;(x);  // brackets (&lt; and &gt;), before
 
4360
                                    // &lt;, or between &gt;( in a cast.
 
4361
        vector&lt;char *&gt; x;           // Spaces between type and pointer are
 
4362
                                    // okay, but be consistent.
 
4363
        set&lt;list&lt;string&gt; &gt; x;       // C++ requires a space in &gt; &gt;.
 
4364
        set&lt; list&lt;string&gt; &gt; x;      // You may optionally use
 
4365
                                    // symmetric spacing in &lt; &lt;.
 
4366
        </CODE_SNIPPET>
 
4367
      </SUBSECTION>
 
4368
    </BODY>
 
4369
  </STYLEPOINT>
 
4370
 
 
4371
 
 
4372
  <STYLEPOINT title="Vertical Whitespace">
 
4373
    <SUMMARY>
 
4374
      Minimize use of vertical whitespace.
 
4375
    </SUMMARY>
 
4376
    <BODY>
 
4377
      <p>
 
4378
        This is more a principle than a rule: don't use blank lines
 
4379
        when you don't have to.  In particular, don't put more than
 
4380
        one or two blank lines between functions, resist starting
 
4381
        functions with a blank line, don't end functions with a blank
 
4382
        line, and be discriminating with your use of blank lines
 
4383
        inside functions.
 
4384
      </p>
 
4385
      <p>
 
4386
        The basic principle is: The more code that fits on one screen,
 
4387
        the easier it is to follow and understand the control flow of
 
4388
        the program.  Of course, readability can suffer from code
 
4389
        being too dense as well as too spread out, so use your
 
4390
        judgement.  But in general, minimize use of vertical
 
4391
        whitespace.
 
4392
      </p>
 
4393
      <p>
 
4394
        Some rules of thumb to help when blank lines may be useful:
 
4395
      </p>
 
4396
      <ul>
 
4397
        <li> Blank lines at the beginning or end of a function very
 
4398
             rarely help readability.
 
4399
             </li>
 
4400
        <li> Blank lines inside a chain of if-else blocks may well
 
4401
             help readability.
 
4402
             </li>
 
4403
      </ul>
 
4404
    </BODY>
 
4405
  </STYLEPOINT>
 
4406
</CATEGORY>
 
4407
 
 
4408
<CATEGORY title="Exceptions to the Rules">
 
4409
  <p>
 
4410
    The coding conventions described above are mandatory.  However,
 
4411
    like all good rules, these sometimes have exceptions, which we
 
4412
    discuss here.
 
4413
  </p>
 
4414
 
 
4415
  
 
4416
 
 
4417
  <STYLEPOINT title="Existing Non-conformant Code">
 
4418
    <SUMMARY>
 
4419
      You may diverge from the rules when dealing with code that does not
 
4420
      conform to this style guide.
 
4421
    </SUMMARY>
 
4422
    <BODY>
 
4423
      <p>
 
4424
        If you find yourself modifying code that was written to
 
4425
        specifications other than those presented by this guide, you may
 
4426
        have to diverge from these rules in order to stay consistent with
 
4427
        the local conventions in that code.  If you are in doubt about
 
4428
        how to do this, ask the original author or the person currently
 
4429
        responsible for the code.  Remember that <em>consistency</em>
 
4430
        includes local consistency, too.
 
4431
      </p>
 
4432
    </BODY>
 
4433
  </STYLEPOINT>
 
4434
 
 
4435
  
 
4436
 
 
4437
  <STYLEPOINT title="Windows Code">
 
4438
    <SUMMARY>
 
4439
      
 
4440
      Windows programmers have developed their own set of coding
 
4441
      conventions, mainly derived from the conventions in Windows headers
 
4442
      and other Microsoft code.  We want to make it easy for anyone to
 
4443
      understand your code, so we have a single set of guidelines for
 
4444
      everyone writing C++ on any platform.
 
4445
    </SUMMARY>
 
4446
    <BODY>
 
4447
      <p>
 
4448
        It is worth reiterating a few of the guidelines that you might
 
4449
        forget if you are used to the prevalent Windows style:
 
4450
      </p>
 
4451
      <ul>
 
4452
        <li> Do not use Hungarian notation (for example, naming an
 
4453
             integer <code>iNum</code>). Use the Google naming conventions,
 
4454
             including the <code>.cc</code> extension for source files.
 
4455
             </li>
 
4456
        <li> Windows defines many of its own synonyms for primitive
 
4457
             types, such as <code>DWORD</code>, <code>HANDLE</code>, etc.
 
4458
             It is perfectly acceptable, and encouraged, that you use these
 
4459
             types when calling Windows API functions. Even so, keep as
 
4460
             close as you can to the underlying C++ types. For example, use
 
4461
             <code>const TCHAR *</code> instead of <code>LPCTSTR</code>.
 
4462
             </li>
 
4463
        <li> When compiling with Microsoft Visual C++, set the
 
4464
             compiler to warning level 3 or higher, and treat all
 
4465
             warnings as errors.
 
4466
             </li>
 
4467
        <li> Do not use <code>#pragma once</code>; instead use the
 
4468
             standard Google include guards.  The path in the include
 
4469
             guards should be relative to the top of your project
 
4470
             tree.
 
4471
             </li>
 
4472
        <li> In fact, do not use any nonstandard extensions, like
 
4473
             <code>#pragma</code> and <code>__declspec</code>, unless you
 
4474
             absolutely must.  Using <code>__declspec(dllimport)</code> and
 
4475
             <code>__declspec(dllexport)</code> is allowed; however, you
 
4476
             must use them through macros such as <code>DLLIMPORT</code>
 
4477
             and <code>DLLEXPORT</code>, so that someone can easily disable
 
4478
             the extensions if they share the code.
 
4479
             </li>
 
4480
      </ul>
 
4481
      <p>
 
4482
        However, there are just a few rules that we occasionally need
 
4483
        to break on Windows:
 
4484
      </p>
 
4485
      <ul>
 
4486
        <li> Normally we <a HREF="#Multiple_Inheritance">forbid
 
4487
             the use of multiple implementation inheritance</a>; however,
 
4488
             it is required when using COM and some ATL/WTL
 
4489
             classes. You may use multiple implementation inheritance
 
4490
             to implement COM or ATL/WTL classes and interfaces.
 
4491
             </li>
 
4492
        <li> Although you should not use exceptions in your own code,
 
4493
             they are used extensively in the ATL and some STLs,
 
4494
             including the one that comes with Visual C++. When using
 
4495
             the ATL, you should define <code>_ATL_NO_EXCEPTIONS</code> to
 
4496
             disable exceptions. You should investigate whether you can
 
4497
             also disable exceptions in your STL, but if not, it is OK to
 
4498
             turn on exceptions in the compiler. (Note that this is
 
4499
             only to get the STL to compile. You should still not
 
4500
             write exception handling code yourself.)
 
4501
             </li>
 
4502
        <li> The usual way of working with precompiled headers is to
 
4503
             include a header file at the top of each source file,
 
4504
             typically with a name like <code>StdAfx.h</code> or
 
4505
             <code>precompile.h</code>. To make your code easier to share
 
4506
             with other projects, avoid including this file explicitly
 
4507
             (except in <code>precompile.cc</code>), and use the
 
4508
             <code>/FI</code> compiler option to include the file
 
4509
             automatically.
 
4510
             </li>
 
4511
        <li> Resource headers, which are usually named
 
4512
             <code>resource.h</code> and contain only macros, do not need
 
4513
             to conform to these style guidelines.
 
4514
             </li>
 
4515
      </ul>
 
4516
    </BODY>
 
4517
  </STYLEPOINT>
 
4518
 
 
4519
  
 
4520
</CATEGORY>
 
4521
 
 
4522
<PARTING_WORDS>
 
4523
  <p>
 
4524
    Use common sense and <em>BE CONSISTENT</em>.
 
4525
  </p>
 
4526
  <p>
 
4527
    If you are editing code, take a few minutes to look at the
 
4528
    code around you and determine its style. If they use spaces
 
4529
    around their <code>if</code> clauses, you should, too. If
 
4530
    their comments have little boxes of stars around them, make
 
4531
    your comments have little boxes of stars around them too.
 
4532
  </p>
 
4533
  <p>
 
4534
    The point of having style guidelines is to have a common
 
4535
    vocabulary of coding so people can concentrate on what you are
 
4536
    saying, rather than on how you are saying it.  We present
 
4537
    global style rules here so people know the vocabulary. But
 
4538
    local style is also important.  If code you add to a file
 
4539
    looks drastically different from the existing code around it,
 
4540
    the discontinuity throws readers out of their rhythm when they
 
4541
    go to read it. Try to avoid this.
 
4542
  </p>
 
4543
  
 
4544
  <p>
 
4545
    OK, enough writing about writing code; the code itself is much
 
4546
    more interesting. Have fun!
 
4547
  </p>
 
4548
</PARTING_WORDS>
 
4549
 
 
4550
<HR/>
 
4551
 
 
4552
<p align="right">
 
4553
Revision 3.188
 
4554
</p>
 
4555
 
 
4556
 
 
4557
 
 
4558
<address>
 
4559
Benjy Weinberger<br/>
 
4560
Craig Silverstein<br/>
 
4561
Gregory Eitzmann<br/>
 
4562
Mark Mentovai<br/>
 
4563
Tashana Landray
 
4564
</address>
 
4565
 
 
4566
</GUIDE>