~plane1/maus/devel_624

« back to all changes in this revision

Viewing changes to third_party/google-styleguide/.svn/text-base/objcguide.xml.svn-base

  • Committer: tunnell
  • Date: 2010-09-30 13:56:05 UTC
  • Revision ID: tunnell@itchy-20100930135605-wxbkfgy75p0sndk3
add third party

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 Objective-C Style Guide">
 
4
 
 
5
<p align="right">
 
6
 
 
7
Revision 2.20
 
8
</p>
 
9
 
 
10
 
 
11
 
 
12
<div align="right">
 
13
  <address>
 
14
    Mike Pinkerton<br/>
 
15
    Greg Miller <br/>
 
16
    Dave MacLachlan
 
17
  </address>
 
18
</div>
 
19
 
 
20
<OVERVIEW>
 
21
 
 
22
<CATEGORY title="Important Note">
 
23
  <STYLEPOINT title="Displaying Hidden Details in this Guide">
 
24
     <SUMMARY>
 
25
       This style guide contains many details that are initially
 
26
       hidden from view.  They are marked by the triangle icon, which you
 
27
       see here on your left.  Click it now.
 
28
       You should see "Hooray" appear below.
 
29
     </SUMMARY>
 
30
     <BODY>
 
31
       <p>
 
32
        Hooray!  Now you know you can expand points to get more
 
33
        details.  Alternatively, there's an "expand all" at the
 
34
        top of this document.
 
35
       </p>
 
36
     </BODY>
 
37
  </STYLEPOINT>
 
38
</CATEGORY>
 
39
 
 
40
<CATEGORY title="Background">
 
41
 
 
42
  <p>
 
43
    Objective-C is a very dynamic, object-oriented extension of C.  It's
 
44
    designed to be easy to use and read, while enabling sophisticated
 
45
    object-oriented design. It is the primary development language for new
 
46
    applications on Mac OS X and the iPhone.
 
47
  </p>
 
48
 
 
49
  <p>
 
50
    Cocoa is one of the main application frameworks on Mac OS X. It is a
 
51
    collection of Objective-C classes that provide for rapid development of
 
52
    full-featured Mac OS X applications.
 
53
  </p>
 
54
 
 
55
  <p>
 
56
    Apple has already written a very good, and widely accepted, coding guide
 
57
    for Objective-C. Google has also written a similar guide for C++. This
 
58
    Objective-C guide aims to be a very natural combination of Apple's and
 
59
    Google's general recommendations. So, before reading this guide, please make
 
60
    sure you've read:
 
61
    <ul>
 
62
      <li>
 
63
        <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/CodingGuidelines/index.html">
 
64
          Apple's Cocoa Coding Guidelines
 
65
        </a>
 
66
      </li>
 
67
      <li>
 
68
        
 
69
        <div>
 
70
          <a href="http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml">
 
71
            Google's Open Source C++ Style Guide
 
72
          </a>
 
73
        </div>
 
74
      </li>
 
75
    </ul>
 
76
  </p>
 
77
 
 
78
  
 
79
 
 
80
  <p>
 
81
    <em>Note that all things that are banned in Google's C++ guide are also
 
82
    banned in Objective-C++, unless explicitly noted in this document.</em>
 
83
  </p>
 
84
 
 
85
  <p>
 
86
    The purpose of this document is to describe the Objective-C (and
 
87
    Objective-C++) coding guidelines and practices that should be used for all
 
88
    Mac OS X code. Many of these guidelines have evolved and been proven over
 
89
    time on other projects and teams.
 
90
    
 
91
    Open-source projects developed by Google
 
92
    conform to the requirements in this guide.
 
93
  </p>
 
94
 
 
95
  <p>
 
96
    Google has already released open-source code that conforms to these
 
97
    guidelines as part of the
 
98
    <a href="http://code.google.com/p/google-toolbox-for-mac/">
 
99
      Google Toolbox for Mac project
 
100
    </a>
 
101
    (abbreviated GTM throughout this document).
 
102
    Code meant to be shared across different projects is a good candidate to
 
103
    be included in this repository.
 
104
  </p>
 
105
 
 
106
  
 
107
 
 
108
  <p>
 
109
    Note that this guide is not an Objective-C tutorial. We assume that the
 
110
    reader is familiar with the language. If you are new to Objective-C or
 
111
    need a refresher, please read
 
112
    <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/index.html">
 
113
      The Objective-C Programming Language
 
114
    </a>.
 
115
  </p>
 
116
</CATEGORY>
 
117
</OVERVIEW>
 
118
 
 
119
<CATEGORY title="Example">
 
120
 
 
121
  <p>
 
122
    They say an example is worth a thousand words so let's start off with an
 
123
    example that should give you a feel for the style, spacing, naming, etc.
 
124
  </p>
 
125
 
 
126
  <p>
 
127
    An example header file, demonstrating the correct commenting and spacing
 
128
    for an <code>@interface</code> declaration
 
129
  </p>
 
130
 
 
131
<CODE_SNIPPET>
 
132
    //  GTMFoo.h
 
133
    //  FooProject
 
134
    //
 
135
    //  Created by Greg Miller on 6/13/08.
 
136
    //  Copyright 2008 Google, Inc. All rights reserved.
 
137
    //
 
138
   
 
139
    #import &lt;Foundation/Foundation.h&gt;
 
140
   
 
141
    // A sample class demonstrating good Objective-C style. All interfaces,
 
142
    // categories, and protocols (read: all top-level declarations in a header)
 
143
    // MUST be commented. Comments must also be adjacent to the object they're
 
144
    // documenting.
 
145
    //
 
146
    // (no blank line between this comment and the interface)
 
147
    @interface GTMFoo : NSObject {
 
148
     @private
 
149
      NSString *foo_;
 
150
      NSString *bar_;
 
151
    }
 
152
   
 
153
    // Returns an autoreleased instance of GMFoo. See -initWithString: for details
 
154
    // about the argument.
 
155
    + (id)fooWithString:(NSString *)string;
 
156
   
 
157
    // Designated initializer. |string| will be copied and assigned to |foo_|.
 
158
    - (id)initWithString:(NSString *)string;
 
159
   
 
160
    // Gets and sets the string for |foo_|.
 
161
    - (NSString *)foo;
 
162
    - (void)setFoo:(NSString *)newFoo;
 
163
   
 
164
    // Does some work on |blah| and returns YES if the work was completed
 
165
    // successfuly, and NO otherwise.
 
166
    - (BOOL)doWorkWithString:(NSString *)blah;
 
167
   
 
168
    @end
 
169
  </CODE_SNIPPET>
 
170
 
 
171
  <p>
 
172
    An example source file, demonstating the correct commenting and spacing
 
173
    for the <code>@implementation</code> of an interface. It also includes the
 
174
    reference implementations for important methods like getters and setters,
 
175
    <code>init</code>, and <code>dealloc</code>.
 
176
  </p>
 
177
 
 
178
  <CODE_SNIPPET>
 
179
    //
 
180
    //  GTMFoo.m
 
181
    //  FooProject
 
182
    //
 
183
    //  Created by Greg Miller on 6/13/08.
 
184
    //  Copyright 2008 Google, Inc. All rights reserved.
 
185
    //
 
186
   
 
187
    #import "GTMFoo.h"
 
188
   
 
189
   
 
190
    @implementation GTMFoo
 
191
   
 
192
    + (id)fooWithString:(NSString *)string {
 
193
      return [[[self alloc] initWithString:string] autorelease];
 
194
    }
 
195
   
 
196
    // Must always override super's designated initializer.
 
197
    - (id)init {
 
198
      return [self initWithString:nil];
 
199
    }
 
200
   
 
201
    - (id)initWithString:(NSString *)string {
 
202
      if ((self = [super init])) {
 
203
        foo_ = [string copy];
 
204
        bar_ = [[NSString alloc] initWithFormat:@"hi %d", 3];
 
205
      }
 
206
      return self;  
 
207
    }
 
208
   
 
209
    - (void)dealloc {
 
210
      [foo_ release];
 
211
      [bar_ release];
 
212
      [super dealloc];
 
213
    }
 
214
   
 
215
    - (NSString *)foo {
 
216
      return foo_;
 
217
    }
 
218
   
 
219
    - (void)setFoo:(NSString *)newFoo {
 
220
      [foo_ autorelease];
 
221
      foo_ = [newFoo copy];  
 
222
    }
 
223
   
 
224
    - (BOOL)doWorkWithString:(NSString *)blah {
 
225
      // ...
 
226
      return NO;
 
227
    }
 
228
   
 
229
    @end
 
230
  </CODE_SNIPPET>
 
231
 
 
232
</CATEGORY>
 
233
 
 
234
<CATEGORY title="Spacing And Formatting">
 
235
 
 
236
  <STYLEPOINT title="Spaces vs. Tabs">
 
237
    <SUMMARY>
 
238
      Use only spaces, and indent 2 spaces at a time.
 
239
    </SUMMARY>
 
240
    <BODY>
 
241
      <p>
 
242
        We use spaces for indentation. Do not use tabs in your code.
 
243
        You should set your editor to emit spaces when you hit the tab
 
244
        key.
 
245
      </p>
 
246
    </BODY>
 
247
  </STYLEPOINT>
 
248
 
 
249
  <STYLEPOINT title="Line Length">
 
250
    <SUMMARY>
 
251
      Each line of text in your code should be at most 80 characters long.
 
252
    </SUMMARY>
 
253
    <BODY>
 
254
      <p>
 
255
        Even though Objective-C tends to be a more verbose language than C++,
 
256
        to aid in the interoperability with that guide, we have decided
 
257
        to keep the limit at 80 columns as well. It's easier to live with
 
258
        than you might expect.
 
259
      </p>
 
260
      
 
261
      <p>
 
262
        We recognize that this rule is controversial, but so much existing
 
263
        code already adheres to it, and we feel that consistency is
 
264
        important.
 
265
      </p>
 
266
      <p>
 
267
        You can make violations easier to spot in Xcode by going to <i>Xcode
 
268
        &gt; Preferences &gt; Text Editing &gt; Show page guide</i>.
 
269
      </p>
 
270
    </BODY>
 
271
  </STYLEPOINT>
 
272
 
 
273
  <STYLEPOINT title="Method Declarations and Definitions">
 
274
    <SUMMARY>
 
275
      One space should be used between the <code>-</code> or <code>+</code>
 
276
      and the return type, and no spacing in the parameter list except between
 
277
      parameters.
 
278
    </SUMMARY>
 
279
    <BODY>
 
280
      <p>
 
281
        Methods should look like this:
 
282
      </p>
 
283
      <CODE_SNIPPET>
 
284
        - (void)doSomethingWithString:(NSString *)theString {
 
285
          ...
 
286
        }
 
287
      </CODE_SNIPPET>
 
288
      <p>
 
289
        The spacing before the asterisk is optional. When adding new code,
 
290
        be consistent with the surrounding file's style.
 
291
      </p>
 
292
      <p>
 
293
        If you have too many parameters to fit on one line, giving each its
 
294
        own line is preferred. If multiple lines are used, align each using
 
295
        the colon before the parameter.
 
296
      </p>
 
297
      <CODE_SNIPPET>
 
298
        - (void)doSomethingWith:(GTMFoo *)theFoo
 
299
                           rect:(NSRect)theRect
 
300
                       interval:(float)theInterval {
 
301
          ...
 
302
        }
 
303
      </CODE_SNIPPET>
 
304
      <p>
 
305
        When the first keyword is shorter than the others, indent the later
 
306
        lines by at least four spaces. You can do this by making keywords
 
307
        line up vertically, not aligning colons:
 
308
      </p>
 
309
      <CODE_SNIPPET>
 
310
        - (void)short:(GTMFoo *)theFoo
 
311
            longKeyword:(NSRect)theRect
 
312
            evenLongerKeyword:(float)theInterval {
 
313
          ...
 
314
        }
 
315
      </CODE_SNIPPET>
 
316
    </BODY>
 
317
  </STYLEPOINT>
 
318
 
 
319
  <STYLEPOINT title="Method Invocations">
 
320
    <SUMMARY>
 
321
      Method invocations should be formatted much like method declarations.
 
322
      When there's a choice of formatting styles, follow the convention
 
323
      already used in a given source file.
 
324
    </SUMMARY>
 
325
    <BODY>
 
326
      <p>
 
327
        Invocations should have all arguments on one line:
 
328
      </p>
 
329
      <CODE_SNIPPET>
 
330
        [myObject doFooWith:arg1 name:arg2 error:arg3];
 
331
      </CODE_SNIPPET>
 
332
      <p>
 
333
        or have one argument per line, with colons aligned:
 
334
      </p>
 
335
      <CODE_SNIPPET>
 
336
        [myObject doFooWith:arg1
 
337
                       name:arg2
 
338
                      error:arg3];
 
339
      </CODE_SNIPPET>
 
340
      <p>
 
341
        Don't use any of these styles:
 
342
      </p>
 
343
      <BAD_CODE_SNIPPET>
 
344
        [myObject doFooWith:arg1 name:arg2  // some lines with &gt;1 arg
 
345
                      error:arg3];
 
346
 
 
347
        [myObject doFooWith:arg1
 
348
                       name:arg2 error:arg3];
 
349
 
 
350
        [myObject doFooWith:arg1
 
351
                  name:arg2  // aligning keywords instead of colons
 
352
                  error:arg3];
 
353
      </BAD_CODE_SNIPPET>
 
354
 
 
355
      <p>
 
356
        As with declarations and definitions, when the keyword lengths make
 
357
        it impossible to align colons and still have four leading
 
358
        spaces, indent later lines by four spaces and align keywords after the
 
359
        first one, instead of aligning the colons.
 
360
      </p>
 
361
      <CODE_SNIPPET>
 
362
        [myObj short:arg1
 
363
            longKeyword:arg2
 
364
            evenLongerKeyword:arg3];
 
365
      </CODE_SNIPPET>
 
366
    </BODY>
 
367
  </STYLEPOINT>
 
368
 
 
369
  <STYLEPOINT title="@public and @private">
 
370
    <SUMMARY>
 
371
      The <code>@public</code> and <code>@private</code> access modifiers
 
372
      should be indented by 1 space.
 
373
    </SUMMARY>
 
374
    <BODY>
 
375
      <p>
 
376
        This is similar to <code>public</code>, <code>private</code>, and
 
377
        <code>protected</code> in C++.
 
378
      </p>
 
379
      <CODE_SNIPPET>
 
380
        @interface MyClass : NSObject {
 
381
         @public
 
382
          ...
 
383
         @private
 
384
          ...
 
385
        }
 
386
        @end
 
387
      </CODE_SNIPPET>
 
388
    </BODY>
 
389
  </STYLEPOINT>
 
390
 
 
391
  <STYLEPOINT title="Exceptions">
 
392
    <SUMMARY>
 
393
      Format exceptions with each <code>@</code> label on its own line and a
 
394
      space between the <code>@</code> label and the opening brace
 
395
      (<code>{</code>), as well as between the <code>@catch</code> and the
 
396
      caught object declaration.
 
397
    </SUMMARY>
 
398
    <BODY>
 
399
      <p>
 
400
        If you must use Obj-C exceptions, format them as follows.  However, see
 
401
        <a href="#Avoid_Throwing_Exceptions">Avoid Throwing Exceptions</a> for
 
402
        reasons why you <b>should not</b> be using exceptions.
 
403
      </p>
 
404
      <CODE_SNIPPET>
 
405
        @try {
 
406
          foo();
 
407
        }
 
408
        @catch (NSException *ex) {
 
409
          bar(ex);
 
410
        }
 
411
        @finally {
 
412
          baz();
 
413
        }
 
414
      </CODE_SNIPPET>
 
415
    </BODY>
 
416
  </STYLEPOINT>
 
417
 
 
418
  <STYLEPOINT title="Protocols">
 
419
    <SUMMARY>
 
420
      There should not be a space between the type identifier and the name
 
421
      of the protocol encased in angle brackets.
 
422
    </SUMMARY>
 
423
    <BODY>
 
424
      <p>
 
425
        This applies to class declarations, instance variables, and method
 
426
        delcarations. For example:
 
427
      </p>
 
428
      <CODE_SNIPPET>
 
429
        @interface MyProtocoledClass : NSObject&lt;NSWindowDelegate&gt; {
 
430
         @private
 
431
          id&lt;MyFancyDelegate&gt; delegate_;
 
432
        }
 
433
        - (void)setDelegate:(id&lt;MyFancyDelegate&gt;)aDelegate;
 
434
        @end
 
435
      </CODE_SNIPPET>
 
436
    </BODY>
 
437
  </STYLEPOINT>
 
438
 
 
439
</CATEGORY>
 
440
 
 
441
<CATEGORY title="Naming">
 
442
 
 
443
  <p>
 
444
    Naming rules are very important in maintainable code. Objective-C method
 
445
    names tend to be very long, but this has the benefit that a block of code
 
446
    can almost read like prose, thus rendering many comments unnecessary. </p>
 
447
    <p> When writing pure Objective-C code, we mostly follow standard <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html">Objective-C
 
448
    naming rules</a>. These naming guidelines may differ
 
449
    significantly from those outlined in the C++ style guide. For example,
 
450
    Google's C++ style guide recommends the use of underscores between words
 
451
    in variable names, whereas this guide recommends the use of intercaps,
 
452
    which is standard in the Objective-C community.
 
453
  </p>
 
454
  <p>
 
455
    Any class, category, method, or variable name may use all capitals for
 
456
    <a href="http://en.wikipedia.org/wiki/Initialism">initialisms</a>
 
457
    within the name. This follows Apple's standard of using all capitals
 
458
    within a name for initialisms such as URL, TIFF, and EXIF.
 
459
  </p>
 
460
  <p>
 
461
    When writing Objective-C++, however, things are not so cut and dry. Many
 
462
    projects need to implement cross-platform C++ APIs with some Objective-C
 
463
    or Cocoa, or bridge between a C++ back-end and a native Cocoa front-end.
 
464
    This leads to situations where the two guides are directly at odds.
 
465
  </p>
 
466
  <p>
 
467
    Our solution is that the style follows that of the method/function being
 
468
    implemented. If you're in an <code>@implementation</code> block, use the
 
469
    Objective-C naming rules. If you're implementing a method for a C++
 
470
    <code>class</code>, use the C++ naming rules. This avoids the situation
 
471
    where instance variable and local variable naming rules are mixed within a
 
472
    single function, which would be a serious detriment to readability.
 
473
  </p>
 
474
 
 
475
  <STYLEPOINT title="File Names">
 
476
    <SUMMARY>
 
477
      File names should reflect the name of the class implementation that
 
478
      they contain -- including case. Follow the convention that your
 
479
      
 
480
      project
 
481
      uses.
 
482
    </SUMMARY>
 
483
    <BODY>
 
484
      <p>
 
485
        File extensions should be as follows:
 
486
      </p>
 
487
      <table>
 
488
        <tr>
 
489
          <td><code>.h</code></td>
 
490
          <td>C/C++/Objective-C header file</td>
 
491
        </tr>
 
492
        <tr>
 
493
          <td><code>.m</code></td>
 
494
          <td>Objective-C implementation file</td>
 
495
        </tr>
 
496
        <tr>
 
497
          <td><code>.mm</code></td>
 
498
          <td>Objective-C++ implementation file</td>
 
499
        </tr>
 
500
        <tr>
 
501
          <td><code>.cc</code></td>
 
502
          <td>Pure C++ implementation file</td>
 
503
        </tr>
 
504
        <tr>
 
505
          <td><code>.c</code></td>
 
506
          <td>C implementation file</td>
 
507
        </tr>
 
508
      </table>
 
509
      <p>
 
510
        File names for categories should include the name of the class being
 
511
        extended, e.g. <code>GTMNSString+Utils.h</code> or
 
512
        <code>GTMNSTextView+Autocomplete.h</code>
 
513
      </p>
 
514
    </BODY>
 
515
  </STYLEPOINT>
 
516
 
 
517
  <STYLEPOINT title="Objective-C++">
 
518
    <SUMMARY>
 
519
      Within a source file, Objective-C++ follows the style of the
 
520
      function/method you're implementing.
 
521
    </SUMMARY>
 
522
    <BODY>
 
523
      <p>
 
524
        In order to minimize clashes between the differing naming styles when
 
525
        mixing Cocoa/Objective-C and C++, follow the style of the method being
 
526
        implemented. If you're in an <code>@implementation</code> block, use
 
527
        the Objective-C naming rules. If you're implementing a method for a
 
528
        C++ <code>class</code>, use the C++ naming rules.
 
529
      </p>
 
530
      <CODE_SNIPPET>
 
531
        // file: cross_platform_header.h
 
532
 
 
533
        class CrossPlatformAPI {
 
534
         public:
 
535
          ...
 
536
          int DoSomethingPlatformSpecific();  // impl on each platform
 
537
         private:
 
538
          int an_instance_var_;
 
539
        };
 
540
 
 
541
        // file: mac_implementation.mm
 
542
        #include "cross_platform_header.h"
 
543
 
 
544
        // A typical Objective-C class, using Objective-C naming.
 
545
        @interface MyDelegate : NSObject {
 
546
         @private
 
547
          int instanceVar_;
 
548
          CrossPlatformAPI* backEndObject_;
 
549
        }
 
550
        - (void)respondToSomething:(id)something;
 
551
        @end
 
552
        @implementation MyDelegate
 
553
        - (void)respondToSomething:(id)something {
 
554
          // bridge from Cocoa through our C++ backend
 
555
          instanceVar_ = backEndObject-&gt;DoSomethingPlatformSpecific();
 
556
          NSString* tempString = [NSString stringWithInt:instanceVar_];
 
557
          NSLog(@"%@", tempString);
 
558
        }
 
559
        @end
 
560
 
 
561
        // The platform-specific implementation of the C++ class, using
 
562
        // C++ naming.
 
563
        int CrossPlatformAPI::DoSomethingPlatformSpecific() {
 
564
          NSString* temp_string = [NSString stringWithInt:an_instance_var_];
 
565
          NSLog(@"%@", temp_string);
 
566
          return [temp_string intValue];
 
567
        }
 
568
      </CODE_SNIPPET>
 
569
    </BODY>
 
570
  </STYLEPOINT>
 
571
 
 
572
  <STYLEPOINT title="Class Names">
 
573
    <SUMMARY>
 
574
      Class names (along with category and protocol names) should start as
 
575
      uppercase and use mixed case to delimit words.
 
576
    </SUMMARY>
 
577
    <BODY>
 
578
      <p>
 
579
        In <em>application-level</em> code, prefixes on class names should
 
580
        generally be avoided. Having every single class with same prefix
 
581
        impairs readability for no benefit. When designing code to be shared
 
582
        across multiple applications, prefixes are acceptable and recommended
 
583
        (e.g. <code>GTMSendMessage</code>).
 
584
      </p>
 
585
      
 
586
    </BODY>
 
587
  </STYLEPOINT>
 
588
 
 
589
  <STYLEPOINT title="Category Names">
 
590
    <SUMMARY>
 
591
      Category names should start with a 2 or 3 character prefix
 
592
      identifying the category as part of a project or open for general
 
593
      use. The category name should incorporate the name of the class it's
 
594
      extending.
 
595
    </SUMMARY>
 
596
    <BODY>
 
597
      <p>
 
598
        For example, if we want to create a category on <code>NSString</code>
 
599
        for parsing, we would put the category in a file named
 
600
        <code>GTMNSString+Parsing.h</code>, and the category itself would be
 
601
        named <code>GTMStringParsingAdditions</code> (yes, we know the file
 
602
        name and the category name do not match, but this file could have many
 
603
        separate categories related to parsing). Methods in that category
 
604
        should share the prefix (<code>gtm_myCategoryMethodOnAString:</code>)
 
605
        in order to prevent collisions in Objective-C which only has a single
 
606
        namespace. If the code isn't meant to be shared and/or doesn't run in
 
607
        a different address-space, the method naming isn't quite as
 
608
        important.
 
609
      </p>
 
610
      <p>
 
611
        There should be a single space between the class name and the opening
 
612
        parenthesis of the category.
 
613
      </p>
 
614
    </BODY>
 
615
  </STYLEPOINT>
 
616
 
 
617
  <STYLEPOINT title="Objective-C Method Names">
 
618
    <SUMMARY>
 
619
      Method names should start as lowercase and then use mixed case.
 
620
      Each named parameter should also start as lowercase.
 
621
    </SUMMARY>
 
622
    <BODY>
 
623
      <p>
 
624
        The method name should read like a sentence if possible, meaning you
 
625
        should choose parameter names that flow with the method name. (e.g.
 
626
        <code>convertPoint:fromRect:</code> or
 
627
        <code>replaceCharactersInRange:withString:</code>). See <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingMethods.html#//apple_ref/doc/uid/20001282-BCIGIJJF">Apple's
 
628
        Guide to Naming Methods</a> for more details.
 
629
      </p>
 
630
      <p>
 
631
        Accessor methods should be named the same as the variable they're
 
632
        "getting", but they should <em>not</em> be prefixed with the word
 
633
        "get". For example:
 
634
        <BAD_CODE_SNIPPET>
 
635
          - (id)getDelegate;  // AVOID
 
636
        </BAD_CODE_SNIPPET>
 
637
        <CODE_SNIPPET>
 
638
          - (id)delegate;    // GOOD
 
639
        </CODE_SNIPPET>
 
640
      </p>
 
641
      <p>
 
642
        This is for Objective-C methods only. C++ method names and functions
 
643
        continue to follow the rules set in the C++ style guide.
 
644
      </p>
 
645
    </BODY>
 
646
  </STYLEPOINT>
 
647
 
 
648
  <STYLEPOINT title="Variable Names">
 
649
    <SUMMARY>
 
650
      Variables names start with a lowercase and use mixed case to delimit
 
651
      words. Class member variables have trailing underscores. For example:
 
652
      <var>myLocalVariable</var>, <var>myInstanceVariable_</var>. Members
 
653
      used for KVO/KVC bindings may begin with a leading underscore
 
654
      <i>iff</i> use of Objective-C 2.0's <code>@property</code> isn't
 
655
      allowed.
 
656
    </SUMMARY>
 
657
    <BODY>
 
658
      <SUBSECTION title="Common Variable Names">
 
659
        <p>
 
660
          Do <em>not</em> use Hungarian notation for syntactic attributes,
 
661
          such as the static type of a variable (int or pointer). Give as
 
662
          descriptive a name as possible, within reason. Don't worry about
 
663
          saving horizontal space as it is far more important to make your
 
664
          code immediately understandable by a new reader. For example:
 
665
        </p>
 
666
        <BAD_CODE_SNIPPET>
 
667
          int w;
 
668
          int nerr;
 
669
          int nCompConns;
 
670
          tix = [[NSMutableArray alloc] init];
 
671
          obj = [someObject object];
 
672
          p = [network port];
 
673
        </BAD_CODE_SNIPPET>
 
674
        <CODE_SNIPPET>
 
675
          int numErrors;
 
676
          int numCompletedConnections;
 
677
          tickets = [[NSMutableArray alloc] init];
 
678
          userInfo = [someObject object];
 
679
          port = [network port];
 
680
        </CODE_SNIPPET>
 
681
      </SUBSECTION>
 
682
 
 
683
      <SUBSECTION title="Instance Variables">
 
684
        <p>
 
685
          Instance variables are mixed case and should be suffixed with a
 
686
          trailing underscore, e.g. <var>usernameTextField_</var>. However,
 
687
          we permit an exception when binding to a member variable using
 
688
          KVO/KVC and Objective-C 2.0 cannot be used (due to OS release
 
689
          constraints). In this case, it is acceptable to prefix the variable
 
690
          with an underscore, per Apple's accepted practices for key/value
 
691
          naming. If Objective-C 2.0 can be used, <code>@property</code> and
 
692
          <code>@synthesize</code> provide a solution that conforms to the
 
693
          naming guidelines.
 
694
        </p>
 
695
      </SUBSECTION>
 
696
 
 
697
      <SUBSECTION title="Constants">
 
698
        <p>
 
699
          Constant names (#defines, enums, const local variables, etc.) should
 
700
          start with a lowercase <var>k</var> and then use mixed case to
 
701
          delimit words, i.e. <var>kInvalidHandle</var>,
 
702
          <var>kWritePerm</var>.
 
703
        </p>
 
704
      </SUBSECTION>
 
705
    </BODY>
 
706
  </STYLEPOINT>
 
707
 
 
708
</CATEGORY>
 
709
 
 
710
<CATEGORY title="Comments">
 
711
 
 
712
  <p>
 
713
    Though a pain to write, they are absolutely vital to keeping our code
 
714
    readable. The following rules describe what you should comment and where.
 
715
    But remember: while comments are very important, the best code is
 
716
    self-documenting. Giving sensible names to types and variables is much
 
717
    better than using obscure names and then trying to explain them through
 
718
    comments.
 
719
  </p>
 
720
  <p>
 
721
    When writing your comments, write for your audience: the next
 
722
    
 
723
    contributor
 
724
    who will need to understand your code.  Be generous &#8212; the next
 
725
    one may be you!
 
726
  </p>
 
727
  <p>
 
728
    Remember that all of the rules and conventions listed in the C++ Style
 
729
    Guide are in effect here, with a few additional points, below.
 
730
  </p>
 
731
 
 
732
  <STYLEPOINT title="File Comments">
 
733
    <SUMMARY>
 
734
      Start each file with a copyright notice, followed by a
 
735
      description of the contents of the file.
 
736
    </SUMMARY>
 
737
    <BODY>
 
738
      <SUBSECTION title="Legal Notice and Author Line">
 
739
        
 
740
        
 
741
        <p>
 
742
          Every file should contain the following items, in order:
 
743
          <ul>
 
744
            <li>a copyright statement (for example,
 
745
                <code>Copyright 2008 Google Inc.</code>)</li>
 
746
            <li>a license boilerplate.  Choose the appropriate boilerplate
 
747
                for the license used by the project (for example,
 
748
                Apache 2.0, BSD, LGPL, GPL)</li>
 
749
          </ul>
 
750
        </p>
 
751
        <p>
 
752
          If you make significant changes to a file that someone else
 
753
          originally wrote, add yourself to the author line. This can
 
754
          be very helpful when another
 
755
          
 
756
          contributor
 
757
          has questions about the file and needs to know whom to contact
 
758
          about it.
 
759
        </p>
 
760
      </SUBSECTION>
 
761
    </BODY>
 
762
  </STYLEPOINT>
 
763
 
 
764
  <STYLEPOINT title="Declaration Comments">
 
765
    <SUMMARY>
 
766
      Every interface, category, and protocol declaration should have an
 
767
      accompanying comment describing its purpose and how it fits into the
 
768
      larger picture.
 
769
    </SUMMARY>
 
770
    <BODY>
 
771
      <CODE_SNIPPET>
 
772
        // A delegate for NSApplication to handle notifications about app
 
773
        // launch and shutdown. Owned by the main app controller.
 
774
        @interface MyAppDelegate : NSObject {
 
775
          ...
 
776
        }
 
777
        @end
 
778
      </CODE_SNIPPET>
 
779
      <p>
 
780
        If you have already described an interface in detail in the
 
781
        comments at the top of your file feel free to simply state
 
782
        "See comment at top of file for a complete description", but
 
783
        be sure to have some sort of comment.
 
784
      </p>
 
785
      <p>
 
786
        Additionally, each method in the public interface should have a
 
787
        comment explaining its function, arguments, return value, and any
 
788
        side effects.
 
789
      </p>
 
790
      <p>
 
791
        Document the synchronization assumptions the class makes, if
 
792
        any. If an instance of the class can be accessed by multiple
 
793
        threads, take extra care to document the rules and invariants
 
794
        surrounding multithreaded use.
 
795
      </p>
 
796
    </BODY>
 
797
  </STYLEPOINT>
 
798
 
 
799
  <STYLEPOINT title="Implementation Comments">
 
800
    <SUMMARY>
 
801
      Use vertical bars to quote variable names and symbols in comments rather
 
802
      than quotes or naming the symbol inline.
 
803
    </SUMMARY>
 
804
    <BODY>
 
805
      <p>
 
806
        This helps eliminate ambiguity, especially when the symbol is a common
 
807
        word that might make the sentence read like it was poorly constructed.
 
808
        E.g. for a symbol "count":
 
809
      </p>
 
810
      <CODE_SNIPPET>
 
811
        // Sometimes we need |count| to be less than zero.
 
812
      </CODE_SNIPPET>
 
813
      <p>
 
814
        or when quoting something which already contains quotes
 
815
      </p>
 
816
      <CODE_SNIPPET>
 
817
        // Remember to call |StringWithoutSpaces("foo bar baz")|
 
818
      </CODE_SNIPPET>
 
819
    </BODY>
 
820
  </STYLEPOINT>
 
821
 
 
822
  <STYLEPOINT title="Object Ownership">
 
823
    <SUMMARY>
 
824
      Make the pointer ownership model as explicit as possible when it falls
 
825
      outside the most common Objective-C usage idioms.
 
826
    </SUMMARY>
 
827
    <BODY>
 
828
      <p>
 
829
        Instance variable pointers to objects derived from NSObject are
 
830
        presumed to be retained, and should be documented as <b>weak</b> if
 
831
        they are not retained by the class. However, instance variables which
 
832
        are labeled as IBOutlets are presumed to not be retained by the class,
 
833
        and should be documented as <b>strong</b> if the class does retain
 
834
        them.
 
835
      </p>
 
836
      <p>
 
837
        Where instance variables are pointers to CoreFoundation, C++, and
 
838
        other non-Objective-C objects, they should always be documented in
 
839
        comments as strong or weak. Be mindful that support for automatic C++
 
840
        objects encapsulated in Objective-C objects is disabled by default, as
 
841
        described <a href="http://chanson.livejournal.com/154253.html">here</a>.
 
842
      </p>
 
843
      <p>
 
844
        Examples of strong and weak documentation:
 
845
        <CODE_SNIPPET>
 
846
          @interface MyDelegate : NSObject {
 
847
           @private
 
848
            IBOutlet NSButton* okButton_;  // normal NSControl
 
849
            IBOutlet NSMenu* myContextMenu_;  // manually-loaded menu (strong)
 
850
 
 
851
            AnObjcObject* doohickey_;  // my doohickey
 
852
            MyController* controller_;  // so we can send msgs back (weak, owns me)
 
853
 
 
854
            // non-NSObject pointers...
 
855
            CWackyCPPClass* wacky_;  // some cross-platform object (strong)
 
856
            CFDictionaryRef* dict_;  // (strong)
 
857
          }
 
858
          @end
 
859
        </CODE_SNIPPET>
 
860
        <dl>
 
861
          <dt>strong</dt><dd>The object will be <code>retain</code>'d by this class</dd>
 
862
          <dt>weak</dt><dd>The object will be <b>not</b> be <code>retain</code>'d by this class
 
863
          (e.g. a delegate).</dd>
 
864
        </dl>
 
865
      </p>
 
866
    </BODY>
 
867
  </STYLEPOINT>
 
868
 
 
869
</CATEGORY>
 
870
 
 
871
<CATEGORY title="Cocoa and Objective-C Features">
 
872
 
 
873
  <STYLEPOINT title="Member Variables Should Be @private">
 
874
    <SUMMARY>
 
875
      Member variables should be declared <code>@private</code>.
 
876
    </SUMMARY>
 
877
    <BODY>
 
878
      <CODE_SNIPPET>
 
879
        @interface MyClass : NSObject {
 
880
         @private
 
881
          id myInstanceVariable_;
 
882
        }
 
883
        // public accessors, setter takes ownership
 
884
        - (id)myInstanceVariable;
 
885
        - (void)setMyInstanceVariable:(id)theVar;
 
886
        @end
 
887
      </CODE_SNIPPET>
 
888
    </BODY>
 
889
  </STYLEPOINT>
 
890
 
 
891
  <STYLEPOINT title="Identify Designated Initializer">
 
892
    <SUMMARY>
 
893
      Comment and clearly identify your designated initializer.
 
894
    </SUMMARY>
 
895
    <BODY>
 
896
      <p>
 
897
        It is important for those who might be subclassing your class that the
 
898
        designated initializer be clearly identified. That way, they only need
 
899
        to subclass a single initializer (of potentially several) to guarantee
 
900
        their subclass' initializer is called. It also helps those debugging
 
901
        your class in the future understand the flow of initialization code if
 
902
        they need to step through it.
 
903
      </p>
 
904
    </BODY>
 
905
  </STYLEPOINT>
 
906
 
 
907
  <STYLEPOINT title="Override Designated Initializer">
 
908
    <SUMMARY>
 
909
      When writing a subclass that requires an <code>init...</code> method,
 
910
      make <i>sure</i> you override the superclass' designated initializer.
 
911
    </SUMMARY>
 
912
    <BODY>
 
913
      <p>
 
914
        If you fail to override the superclass' designated initializer, your
 
915
        initializer may not be called in all cases, leading to subtle and
 
916
        very difficult to find bugs.
 
917
      </p>
 
918
    </BODY>
 
919
  </STYLEPOINT>
 
920
 
 
921
  <STYLEPOINT title="Initialization">
 
922
    <SUMMARY>
 
923
      Don't initialize variables to <code>0</code> or <code>nil</code> in the
 
924
      init method; it's redundant.
 
925
    </SUMMARY>
 
926
    <BODY>
 
927
      <p>
 
928
        All memory for a newly allocated object is initialized to 0 (except
 
929
        for <var>isa</var>), so don't clutter up the <code>init</code> method
 
930
        by re-initializing variables to 0 or <code>nil</code>.
 
931
      </p>
 
932
    </BODY>
 
933
  </STYLEPOINT>
 
934
 
 
935
  <STYLEPOINT title="Keep the Public API Simple">
 
936
    <SUMMARY>
 
937
      Keep your class simple; avoid "kitchen-sink" APIs. If a method doesn't
 
938
      need to be public, don't make it so. Use a private category to prevent
 
939
      cluttering the public header.
 
940
    </SUMMARY>
 
941
    <BODY>
 
942
      <p>
 
943
        Unlike C++, Objective-C doesn't have a way to differentiate between
 
944
        public and private methods &#8212; everything is public. As a result,
 
945
        avoid placing methods in the public API unless they are actually
 
946
        expected to be used by a consumer of the class. This helps reduce the
 
947
        likelihood they'll be called when you're not expecting it. This includes
 
948
        methods that are being overridden from the parent class. For internal
 
949
        implementation methods, use a category defined in the implementation
 
950
        file as opposed to adding them to the public header.
 
951
      </p>
 
952
      <CODE_SNIPPET>
 
953
        // GTMFoo.m
 
954
        #import "GTMFoo.h"
 
955
 
 
956
        @interface GTMFoo (PrivateDelegateHandling)
 
957
        - (NSString *)doSomethingWithDelegate;  // Declare private method
 
958
        @end
 
959
 
 
960
        @implementation GTMFoo(PrivateDelegateHandling)
 
961
        ...
 
962
        - (NSString *)doSomethingWithDelegate {
 
963
          // Implement this method
 
964
        }
 
965
        ...
 
966
        @end
 
967
      </CODE_SNIPPET>
 
968
      <p>
 
969
        Before Objective-C 2.0, if you declare a method in the private
 
970
        <code>@interface</code>, but forget to implement it in the main
 
971
        <code>@implementation</code>, the compiler will <i>not</i> object.
 
972
        (This is because you don't implement these private methods in a
 
973
        separate category.) The solution is to put the functions within
 
974
        an <code>@implementation</code> that specifies the category.
 
975
      </p>
 
976
      <p>
 
977
        If you are using Objective-C 2.0, you should instead declare your
 
978
        private category using a <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/Articles/chapter_4_section_5.html#">class
 
979
        extension</a>, for example:
 
980
      </p>
 
981
      <CODE_SNIPPET>
 
982
      @interface GMFoo () { ... }
 
983
      </CODE_SNIPPET>
 
984
      <p>
 
985
        which will guarantee that the declared methods are implemented in the
 
986
        <code>@implementation</code> section by issuing a compiler warning if
 
987
        they are not.
 
988
      </p>
 
989
      <p>
 
990
        Again, "private" methods are not really private. You could
 
991
        accidentally override a superclass's "private" method, thus making a
 
992
        very difficult bug to squash. In general, private methods should have
 
993
        a fairly unique name that will prevent subclasses from unintentionally
 
994
        overriding them.
 
995
      </p>
 
996
      <p>
 
997
        Finally, Objective-C categories are a great way to segment a large
 
998
        <code>@implementation</code> section into more understandable chunks
 
999
        and to add new, application-specific functionality to the most
 
1000
        appropriate class. For example, instead of adding "middle truncation"
 
1001
        code to a random object in your app, make a new category on
 
1002
        <code>NSString</code>).
 
1003
      </p>
 
1004
    </BODY>
 
1005
  </STYLEPOINT>
 
1006
 
 
1007
  <STYLEPOINT title="#import and #include">
 
1008
    <SUMMARY>
 
1009
      <code>#import</code> Objective-C/Objective-C++ headers, and
 
1010
      <code>#include</code> C/C++ headers.
 
1011
    </SUMMARY>
 
1012
    <BODY>
 
1013
      <p>
 
1014
        Choose between <code>#import</code> and <code>#include</code> based
 
1015
        on the language of the header that you are including.
 
1016
      </p>
 
1017
      <ul>
 
1018
        <li>When including a header that uses Objective-C or Objective-C++,
 
1019
            use <code>#import</code>.</li>
 
1020
        <li>When including a standard C or C++ header, use
 
1021
            <code>#include</code>.  The header should provide its own <a href="cppguide.xml?showone=The__define_Guard#The__define_Guard">#define
 
1022
            guard</a>.</li>
 
1023
      </ul>
 
1024
      <p>
 
1025
        Some Objective-C headers lack <code>#define</code> guards, and expect
 
1026
        to be included only by <code>#import</code>.  As Objective-C headers
 
1027
        may only be included in Objective-C source files and other Objective-C
 
1028
        headers, using <code>#import</code> across the board is appropriate.
 
1029
      </p>
 
1030
      <p>
 
1031
        Standard C and C++ headers without any Objective-C in them can expect
 
1032
        to be included by ordinary C and C++ files.  Since there is no
 
1033
        <code>#import</code> in standard C or C++, such files will be
 
1034
        included by <code>#include</code> in those cases.  Using
 
1035
        <code>#include</code> for them in Objective-C source files as well
 
1036
        means that these headers will always be included with the same
 
1037
        semantics.
 
1038
      </p>
 
1039
      <p>
 
1040
        This rule helps avoid inadvertent errors in cross-platform
 
1041
        projects.  A Mac developer introducing a new C or C++ header might
 
1042
        forget to add <code>#define</code> guards, which would not cause
 
1043
        problems on the Mac if the new header were included with
 
1044
        <code>#import</code>, but would break builds on other platforms
 
1045
        where <code>#include</code> is used.  Being consistent by using
 
1046
        <code>#include</code> on all platforms means that compilation is
 
1047
        more likely to succeed everywhere or fail everywhere, and avoids
 
1048
        the frustration of files working only on some platforms.
 
1049
      </p>
 
1050
      <CODE_SNIPPET>
 
1051
        #import &lt;Cocoa/Cocoa.h&gt;
 
1052
        #include &lt;CoreFoundation/CoreFoundation.h&gt;
 
1053
        #import "GTMFoo.h"
 
1054
        #include "base/basictypes.h"
 
1055
      </CODE_SNIPPET>
 
1056
    </BODY>
 
1057
  </STYLEPOINT>
 
1058
 
 
1059
  <STYLEPOINT title="Use Root Frameworks">
 
1060
    <SUMMARY>
 
1061
      Include root frameworks over individual files.
 
1062
    </SUMMARY>
 
1063
    <BODY>
 
1064
      <p>
 
1065
        While it may seem tempting to include individual system headers from a
 
1066
        framework such as Cocoa or Foundation, in fact it's less work on the
 
1067
        compiler if you include the top-level root framework. The root
 
1068
        framework is generally pre-compiled and can be loaded much more
 
1069
        quickly. In addition, remember to use <code>#import</code> rather than
 
1070
        <code>#include</code> for Objective-C frameworks.
 
1071
      </p>
 
1072
      <CODE_SNIPPET>
 
1073
        #import &lt;Foundation/Foundation.h&gt;     // good
 
1074
      </CODE_SNIPPET>
 
1075
      <BAD_CODE_SNIPPET>
 
1076
        #import &lt;Foundation/NSArray.h&gt;        // avoid
 
1077
        #import &lt;Foundation/NSString.h&gt;
 
1078
        ...
 
1079
      </BAD_CODE_SNIPPET>
 
1080
    </BODY>
 
1081
  </STYLEPOINT>
 
1082
 
 
1083
  <STYLEPOINT title="Prefer To autorelease At Time of Creation">
 
1084
    <SUMMARY>
 
1085
      When creating new temporary objects, <code>autorelease</code> them on
 
1086
      the same line as you create them rather than a separate
 
1087
      <code>release</code> later in the same method.
 
1088
    </SUMMARY>
 
1089
    <BODY>
 
1090
      <p>
 
1091
        While ever so slightly slower, this prevents someone from accidentally
 
1092
        removing the <code>release</code> or inserting a <code>return</code>
 
1093
        before it and introducing a memory leak. E.g.:
 
1094
      </p>
 
1095
      <BAD_CODE_SNIPPET>
 
1096
        // AVOID (unless you have a compelling performance reason)
 
1097
        MyController* controller = [[MyController alloc] init];
 
1098
        // ... code here that might return ...
 
1099
        [controller release];
 
1100
      </BAD_CODE_SNIPPET>
 
1101
      <CODE_SNIPPET>
 
1102
        // BETTER
 
1103
        MyController* controller = [[[MyController alloc] init] autorelease];
 
1104
      </CODE_SNIPPET>
 
1105
    </BODY>
 
1106
  </STYLEPOINT>
 
1107
 
 
1108
  <STYLEPOINT title="Autorelease Then Retain">
 
1109
    <SUMMARY>
 
1110
      Assignment of objects follows the <code>autorelease</code> then
 
1111
      <code>retain</code> pattern.
 
1112
    </SUMMARY>
 
1113
    <BODY>
 
1114
      <p>
 
1115
        When assigning a new object to a variable, one must first release the
 
1116
        old object to avoid a memory leak. There are several "correct" ways to
 
1117
        handle this. We've chosen the "autorelease then retain" approach
 
1118
        because it's less prone to error. Be aware in tight loops it can fill
 
1119
        up the autorelease pool, and may be slightly less efficient, but we
 
1120
        feel the tradeoffs are acceptable.
 
1121
      </p>
 
1122
      <CODE_SNIPPET>
 
1123
        - (void)setFoo:(GMFoo *)aFoo {
 
1124
          [foo_ autorelease];  // Won't dealloc if |foo_| == |aFoo|
 
1125
          foo_ = [aFoo retain];
 
1126
        }
 
1127
      </CODE_SNIPPET>
 
1128
    </BODY>
 
1129
  </STYLEPOINT>
 
1130
 
 
1131
  <STYLEPOINT title="dealloc should process instance variables in declaration                      order">
 
1132
    <SUMMARY>
 
1133
      <code>dealloc</code> should process instance variables in the same order
 
1134
      the <code>@interface</code> declares them, so it is easier for a reviewer
 
1135
      to verify.
 
1136
    </SUMMARY>
 
1137
    <BODY>
 
1138
      <p>
 
1139
        A code reviewer checking a new or revised <code>dealloc</code>
 
1140
        implementation needs to make sure that every retained instance
 
1141
        variable gets released.
 
1142
      </p>
 
1143
      <p>
 
1144
        To simplify reviewing <code>dealloc</code>, order the code so that
 
1145
        the retained instance variables get released in the same order that
 
1146
        they are declared in the <code>@interface</code>. If
 
1147
        <code>dealloc</code> invokes other methods that release instance
 
1148
        variables, add comments describing what instance variables those
 
1149
        methods handle.
 
1150
      </p>
 
1151
    </BODY>
 
1152
  </STYLEPOINT>
 
1153
 
 
1154
  <STYLEPOINT title="Setters copy NSStrings">
 
1155
    <SUMMARY>
 
1156
      Setters taking an <code>NSString</code>, should always <code>copy</code>
 
1157
      the string it accepts.
 
1158
    </SUMMARY>
 
1159
    <BODY>
 
1160
      <p>
 
1161
        Never just <code>retain</code> the string. This avoids the caller
 
1162
        changing it under you without your knowledge. Don't assume that
 
1163
        because you're accepting an <code>NSString</code> that it's not
 
1164
        actually an <code>NSMutableString</code>.
 
1165
      </p>
 
1166
      <CODE_SNIPPET>
 
1167
        - (void)setFoo:(NSString *)aFoo {
 
1168
          [foo_ autorelease];
 
1169
          foo_ = [aFoo copy];
 
1170
        }
 
1171
      </CODE_SNIPPET>
 
1172
    </BODY>
 
1173
  </STYLEPOINT>
 
1174
 
 
1175
  <STYLEPOINT title="Avoid Throwing Exceptions">
 
1176
    <SUMMARY>
 
1177
      Don't <code>@throw</code> Objective-C exceptions, but you should be
 
1178
      prepared to catch them from third-party or OS calls.
 
1179
    </SUMMARY>
 
1180
    <BODY>
 
1181
      <p>
 
1182
        We do compile with <code>-fobjc-exceptions</code> (mainly so we get
 
1183
        <code>@synchronized</code>), but we don't <code>@throw</code>. Use of
 
1184
        <code>@try</code>, <code>@catch</code>, and <code>@finally</code> are
 
1185
        allowed when required to properly use 3rd party code or libraries. If
 
1186
        you do use them please document exactly which methods you expect to
 
1187
        throw.
 
1188
      </p>
 
1189
      <p>
 
1190
        Do not use the <code>NS_DURING</code>, <code>NS_HANDLER</code>,
 
1191
        <code>NS_ENDHANDLER</code>, <code>NS_VALUERETURN</code> and
 
1192
        <code>NS_VOIDRETURN</code> macros unless you are writing code that
 
1193
        needs to run on Mac OS X 10.2 or before.
 
1194
      </p>
 
1195
      <p>
 
1196
        Also be aware when writing Objective-C++ code that stack based objects
 
1197
        are <b>not</b> cleaned up when you throw an Objective-C exception.
 
1198
        Example:
 
1199
      </p>
 
1200
      <CODE_SNIPPET>
 
1201
        class exceptiontest {
 
1202
         public:
 
1203
          exceptiontest() { NSLog(@"Created"); }
 
1204
          ~exceptiontest() { NSLog(@"Destroyed"); }
 
1205
        };
 
1206
 
 
1207
        void foo() {
 
1208
          exceptiontest a;
 
1209
          NSException *exception = [NSException exceptionWithName:@"foo"
 
1210
                                                           reason:@"bar"
 
1211
                                                         userInfo:nil];
 
1212
          @throw exception;
 
1213
        }
 
1214
 
 
1215
        int main(int argc, char *argv[]) {
 
1216
          GMAutoreleasePool pool;
 
1217
          @try {
 
1218
            foo();
 
1219
          }
 
1220
          @catch(NSException *ex) {
 
1221
            NSLog(@"exception raised");
 
1222
          }
 
1223
          return 0;
 
1224
        }
 
1225
      </CODE_SNIPPET>
 
1226
      <p>
 
1227
        will give you:
 
1228
      </p>
 
1229
      <CODE_SNIPPET>
 
1230
        2006-09-28 12:34:29.244 exceptiontest[23661] Created
 
1231
        2006-09-28 12:34:29.244 exceptiontest[23661] exception raised
 
1232
      </CODE_SNIPPET>
 
1233
      <p>
 
1234
        Note that the destructor for <i>a</i> never got called. This is a
 
1235
        major concern for stack based smartptrs such as
 
1236
        <code>shared_ptr</code> and <code>linked_ptr</code>, as well as any
 
1237
        STL objects that you may want to use. Therefore it pains us to say
 
1238
        that if you must use exceptions in your Objective-C++ code, use C++
 
1239
        exceptions whenever possible. You should never re-throw an Objective-C
 
1240
        exception, nor are stack based C++ objects (such as
 
1241
        <code>std::string</code>, <code>std::vector</code> etc.) allowed in
 
1242
        the body of any <code>@try</code>, <code>@catch</code>, or
 
1243
        <code>@finally</code> blocks.
 
1244
      </p>
 
1245
    </BODY>
 
1246
  </STYLEPOINT>
 
1247
 
 
1248
 
 
1249
  <STYLEPOINT title="nil Checks">
 
1250
    <SUMMARY>
 
1251
      Use <code>nil</code> checks for logic flow only.
 
1252
    </SUMMARY>
 
1253
    <BODY>
 
1254
      <p>
 
1255
        Use <code>nil</code> checks for logic flow of the application, not for
 
1256
        crash prevention. Sending a message to a <code>nil</code> object is
 
1257
        handled by the Objective-C runtime. If the method has no return
 
1258
        result, you're good to go. However if there is one, there may be
 
1259
        differences based on runtime architecture, return size, and OS X
 
1260
        version (see <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/Articles/chapter_2_section_3.html#//apple_ref/doc/uid/TP30001163-CH11-SW7">Apple's
 
1261
        documentation</a> for specifics).
 
1262
      </p>
 
1263
      <p>
 
1264
        Note that this is very different from checking C/C++ pointers against
 
1265
        <code>NULL</code>, which the runtime does not handle and will cause
 
1266
        your application to crash. You still need to make sure you do not
 
1267
        dereference a <code>NULL</code> pointer.
 
1268
      </p>
 
1269
    </BODY>
 
1270
  </STYLEPOINT>
 
1271
 
 
1272
  <STYLEPOINT title="BOOL Pitfalls">
 
1273
    <SUMMARY>
 
1274
      Be careful when converting general integral values to <code>BOOL</code>.
 
1275
      Avoid comparing directly with <code>YES</code>.
 
1276
    </SUMMARY>
 
1277
    <BODY>
 
1278
      <p>
 
1279
        <code>BOOL</code> is defined as an unsigned char in Objective-C which
 
1280
        means that it can have values other than <code>YES</code> (1) and
 
1281
        <code>NO</code> (0). Do not cast or convert general integral values
 
1282
        directly to <code>BOOL</code>. Common mistakes include casting or
 
1283
        converting an array's size, a pointer value, or the result of a bitwise
 
1284
        logic operation to a <code>BOOL</code> which, depending on the value of
 
1285
        the last byte of the integral result, could still result in a
 
1286
        <code>NO</code> value. When converting a general integral value to a
 
1287
        <code>BOOL</code> use ternery operators to return a <code>YES</code>
 
1288
        or <code>NO</code> value.
 
1289
      </p>
 
1290
      <p>
 
1291
        You can safely interchange and convert <code>BOOL</code>,
 
1292
        <code>_Bool</code> and <code>bool</code> (see C++ Std 4.7.4, 4.12 and
 
1293
        C99 Std 6.3.1.2). You cannot safely interchange <code>BOOL</code> and
 
1294
        <code>Boolean</code> so treat <code>Booleans</code> as a general
 
1295
        integral value as discussed above. Only use <code>BOOL</code> in
 
1296
        Objective C method signatures.
 
1297
      </p>
 
1298
      <p>
 
1299
        Using logical operators (<code>&amp;&amp;</code>, <code>||</code> and
 
1300
        <code>!</code>) with <code>BOOL</code> is also valid and will return
 
1301
        values that can be safely converted to <code>BOOL</code> without the
 
1302
        need for a ternery operator.
 
1303
      </p>
 
1304
      <BAD_CODE_SNIPPET>
 
1305
        - (BOOL)isBold {
 
1306
          return [self fontTraits] &amp; NSFontBoldTrait;
 
1307
        }
 
1308
        - (BOOL)isValid {
 
1309
          return [self stringValue];
 
1310
        }
 
1311
      </BAD_CODE_SNIPPET>
 
1312
      <CODE_SNIPPET>
 
1313
        - (BOOL)isBold {
 
1314
          return ([self fontTraits] &amp; NSFontBoldTrait) ? YES : NO;
 
1315
        }
 
1316
        - (BOOL)isValid {
 
1317
          return [self stringValue] != nil;
 
1318
        }
 
1319
        - (BOOL)isEnabled {
 
1320
          return [self isValid] &amp;&amp; [self isBold];
 
1321
        }
 
1322
      </CODE_SNIPPET>
 
1323
      <p>
 
1324
        Also, don't directly compare <code>BOOL</code> variables directly
 
1325
        with <code>YES</code>. Not only is it harder to read for those
 
1326
        well-versed in C, the first point above demonstrates that return
 
1327
        values may not always be what you expect.
 
1328
      </p>
 
1329
      <BAD_CODE_SNIPPET>
 
1330
        BOOL great = [foo isGreat];
 
1331
        if (great == YES)
 
1332
          // ...be great!
 
1333
      </BAD_CODE_SNIPPET>
 
1334
      <CODE_SNIPPET>
 
1335
        BOOL great = [foo isGreat];
 
1336
        if (great)
 
1337
          // ...be great!
 
1338
      </CODE_SNIPPET>
 
1339
 
 
1340
    </BODY>
 
1341
  </STYLEPOINT>
 
1342
 
 
1343
  <STYLEPOINT title="Properties">
 
1344
    <SUMMARY>
 
1345
      Properties in general are allowed with the following caveat: properties
 
1346
      are an Objective-C 2.0 feature which will limit your code to running
 
1347
      on the iPhone and Mac OS X 10.5 (Leopard) and higher. Dot notation
 
1348
      is allowed only for access to a declared <code>@property</code>.
 
1349
    </SUMMARY>
 
1350
    <BODY>
 
1351
      <SUBSECTION title="Naming">
 
1352
        <p>
 
1353
          A property's associated instance variable's name must conform to the
 
1354
          trailing _ requirement. The property's name should be the same as its
 
1355
          associated instance variable without the trailing _.
 
1356
        </p>
 
1357
        <p>
 
1358
          Use the @synthesize directive to rename the property correctly.
 
1359
        </p>
 
1360
 
 
1361
        <CODE_SNIPPET>
 
1362
          @interface MyClass : NSObject {
 
1363
           @private
 
1364
            NSString *name_;
 
1365
          }
 
1366
          @property(copy, nonatomic) NSString *name;
 
1367
          @end
 
1368
 
 
1369
          @implementation MyClass
 
1370
          @synthesize name = name_;
 
1371
          @end
 
1372
        </CODE_SNIPPET>
 
1373
      </SUBSECTION>
 
1374
      <SUBSECTION title="Location">
 
1375
        <p>
 
1376
          A property's declaration must come immediately after the instance
 
1377
          variable block of a class interface. A property's definition must
 
1378
          come immediately after the <code>@implementation</code> block in a
 
1379
          class definition. They are indented at the same level as the
 
1380
          <code>@interface</code> or <code>@implementation</code> statements
 
1381
          that they are enclosed in.
 
1382
        </p>
 
1383
        <CODE_SNIPPET>
 
1384
          @interface MyClass : NSObject {
 
1385
           @private
 
1386
            NSString *name_;
 
1387
          }
 
1388
          @property(copy, nonatomic) NSString *name;
 
1389
          @end
 
1390
 
 
1391
          @implementation MyClass
 
1392
          @synthesize name = name_;
 
1393
          - (id)init {
 
1394
          ...
 
1395
          }
 
1396
          @end
 
1397
        </CODE_SNIPPET>
 
1398
      </SUBSECTION>
 
1399
      <SUBSECTION title="Use Copy Attribute For Strings">
 
1400
        <p>
 
1401
          NSString properties should always be declared with the
 
1402
          <code>copy</code> attribute.
 
1403
        </p>
 
1404
        <p>
 
1405
          This logically follows from the requirement that setters for
 
1406
          NSStrings always must use <code>copy</code> instead of
 
1407
          <code>retain</code>.
 
1408
        </p>
 
1409
      </SUBSECTION>
 
1410
      <SUBSECTION title="Never synthesize CFType properties">
 
1411
        <p>
 
1412
          CFTypes should always have the <code>@dynamic</code> implementation
 
1413
          directive.
 
1414
        </p>
 
1415
        <p>
 
1416
          Since CFTypes can't have the <code>retain</code> property
 
1417
          attribute, the developer must handle retaining and releasing the
 
1418
          value themselves. In the rare case that you do actually want
 
1419
          assignment it is better to make that completely clear by actually
 
1420
          implementing the setter and getter and commenting why that is the
 
1421
          case.
 
1422
        </p>
 
1423
      </SUBSECTION>
 
1424
      <SUBSECTION title="List out all implementation directives">
 
1425
        <p>
 
1426
          Use implementation directives for all properties even if they are
 
1427
          <code>@dynamic</code> by default.
 
1428
        </p>
 
1429
        <p>
 
1430
          Even though <code>@dynamic</code> is default, explicitly list it out
 
1431
          with all of the other property implementation directives making it
 
1432
          clear how every property in a class is handled at a single glance.
 
1433
        </p>
 
1434
        <BAD_CODE_SNIPPET>
 
1435
          @interface MyClass : NSObject
 
1436
          @property(readonly) NSString *name;
 
1437
          @end
 
1438
 
 
1439
          @implementation MyClass
 
1440
          .
 
1441
          .
 
1442
          .
 
1443
          - (NSString*)name {
 
1444
            return @"foo";
 
1445
          }
 
1446
          @end
 
1447
        </BAD_CODE_SNIPPET>
 
1448
        <CODE_SNIPPET>
 
1449
          @interface MyClass : NSObject
 
1450
          @property(readonly) NSString *name;
 
1451
          @end
 
1452
 
 
1453
          @implementation MyClass
 
1454
          @dynamic name;
 
1455
          .
 
1456
          .
 
1457
          .
 
1458
          - (NSString*)name {
 
1459
            return @"foo";
 
1460
          }
 
1461
          @end
 
1462
        </CODE_SNIPPET>
 
1463
      </SUBSECTION>
 
1464
      <SUBSECTION title="Atomicity">
 
1465
        <p>
 
1466
          Be aware of the overhead of properties. By default, all synthesized
 
1467
          setters and getters are atomic. This gives each set and get calls a
 
1468
          substantial amount of synchronization overhead. Declare your
 
1469
          properties <code>nonatomic</code> unless you require atomicity.
 
1470
        </p>
 
1471
      </SUBSECTION>
 
1472
      <SUBSECTION title="Dot notation">
 
1473
        <p>
 
1474
          Dot notation is idiomatic style for Objective-C 2.0. It may be used
 
1475
          when doing simple operations to get and set a <code>@property</code>
 
1476
          of an object, but should not be used to invoke other object behavior.
 
1477
        </p>
 
1478
        <CODE_SNIPPET>
 
1479
          NSString *oldName = myObject.name;
 
1480
          myObject.name = @"Alice";
 
1481
        </CODE_SNIPPET>
 
1482
        <BAD_CODE_SNIPPET>
 
1483
          NSArray *array = [[NSArray arrayWithObject:@"hello"] retain];
 
1484
 
 
1485
          NSUInteger numberOfItems = array.count;  // not a property
 
1486
          array.release;                           // not a property
 
1487
        </BAD_CODE_SNIPPET>
 
1488
      </SUBSECTION>
 
1489
    </BODY>
 
1490
  </STYLEPOINT>
 
1491
</CATEGORY>
 
1492
 
 
1493
 
 
1494
<CATEGORY title="Cocoa Patterns">
 
1495
 
 
1496
  <STYLEPOINT title="Delegate Pattern">
 
1497
    <SUMMARY>
 
1498
      Delegate objects should not be retained.
 
1499
    </SUMMARY>
 
1500
    <BODY>
 
1501
      <p>
 
1502
        A class that implements the delegate pattern should:
 
1503
        <ol>
 
1504
          <li>
 
1505
            Have an instance variable named <var>delegate_</var> to reference
 
1506
            the delegate.
 
1507
          </li>
 
1508
          <li>
 
1509
            Thus, the accessor methods should be named <code>delegate</code>
 
1510
            and <code>setDelegate:</code>.
 
1511
          </li>
 
1512
          <li>
 
1513
            The <var>delegate_</var> object should <b>not</b> be retained.
 
1514
          </li>
 
1515
        </ol>
 
1516
      </p>
 
1517
    </BODY>
 
1518
  </STYLEPOINT>
 
1519
 
 
1520
  <STYLEPOINT title="Model/View/Controller">
 
1521
    <SUMMARY>
 
1522
      Separate the model from the view. Separate the controller from the
 
1523
      view and the model. Use <code>@protocol</code>s for callback APIs.
 
1524
    </SUMMARY>
 
1525
    <BODY>
 
1526
      <p>
 
1527
        <ul>
 
1528
          <li>
 
1529
            Separate model from view: don't build assumptions about the
 
1530
            presentation into the model or data source. Keep the interface
 
1531
            between the data source and the presentation abstract. Don't give
 
1532
            the model knowledge of its view. (A good rule of thumb is to ask
 
1533
            yourself if it's possible to have multiple presentations, with
 
1534
            different states, on a single instance of your data source.)
 
1535
          </li>
 
1536
          <li>
 
1537
            Separate controller from view and model: don't put all of the
 
1538
            "business logic" into view-related classes; this makes the code
 
1539
            very unusable. Make controller classes to host this code, but
 
1540
            ensure that the controller classes don't make too many assumptions
 
1541
            about the presentation.
 
1542
          </li>
 
1543
          <li>
 
1544
            Define callback APIs with <code>@protocol</code>, using
 
1545
            <code>@optional</code> if not all the methods are required.
 
1546
            (Exception: when using Objective-C 1.0, <code>@optional</code> isn't
 
1547
            available, so use a category to define an "informal protocol".)
 
1548
          </li>
 
1549
        </ul>
 
1550
      </p>
 
1551
    </BODY>
 
1552
  </STYLEPOINT>
 
1553
 
 
1554
</CATEGORY>
 
1555
 
 
1556
<HR/>
 
1557
 
 
1558
<p align="right">
 
1559
Revision 2.20
 
1560
</p>
 
1561
 
 
1562
 
 
1563
 
 
1564
<address>
 
1565
Mike Pinkerton <br/>
 
1566
Greg Miller <br/>
 
1567
Dave MacLachlan <br/>
 
1568
</address>
 
1569
</GUIDE>