Kevin Lindkvist | c5197bf | 2017-07-25 19:21:16 -0700 | [diff] [blame] | 1 | # Google Objective-C Style Guide |
| 2 | |
Stephane Moore | 4264801 | 2017-10-16 18:11:48 -0700 | [diff] [blame] | 3 | |
Kevin Lindkvist | c5197bf | 2017-07-25 19:21:16 -0700 | [diff] [blame] | 4 | > Objective-C is a dynamic, object-oriented extension of C. It's designed to be |
| 5 | > easy to use and read, while enabling sophisticated object-oriented design. It |
| 6 | > is the primary development language for applications on OS X and on iOS. |
| 7 | > |
| 8 | > Apple has already written a very good, and widely accepted, [Cocoa Coding |
| 9 | > Guidelines](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html) |
| 10 | > for Objective-C. Please read it in addition to this guide. |
| 11 | > |
| 12 | > |
| 13 | > The purpose of this document is to describe the Objective-C (and |
| 14 | > Objective-C++) coding guidelines and practices that should be used for iOS and |
| 15 | > OS X code. These guidelines have evolved and been proven over time on other |
| 16 | > projects and teams. |
| 17 | > Open-source projects developed by Google conform to the requirements in this guide. |
| 18 | > |
| 19 | > Note that this guide is not an Objective-C tutorial. We assume that the reader |
| 20 | > is familiar with the language. If you are new to Objective-C or need a |
| 21 | > refresher, please read [Programming with |
| 22 | > Objective-C](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html). |
| 23 | |
| 24 | |
Stephane Moore | 4264801 | 2017-10-16 18:11:48 -0700 | [diff] [blame] | 25 | ## Principles |
| 26 | |
| 27 | ### Optimize for the reader, not the writer |
| 28 | |
| 29 | Codebases often have extended lifetimes and more time is spent reading the code |
| 30 | than writing it. We explicitly choose to optimize for the experience of our |
| 31 | average software engineer reading, maintaining, and debugging code in our |
| 32 | codebase rather than the ease of writing said code. For example, when something |
| 33 | surprising or unusual is happening in a snippet of code, leaving textual hints |
| 34 | for the reader is valuable. |
| 35 | |
| 36 | ### Be consistent |
| 37 | |
| 38 | When the style guide allows multiple options it is preferable to pick one option |
| 39 | over mixed usage of multiple options. Using one style consistently throughout a |
| 40 | codebase lets engineers focus on other (more important) issues. Consistency also |
| 41 | enables better automation because consistent code allows more efficient |
| 42 | development and operation of tools that format or refactor code. In many cases, |
| 43 | rules that are attributed to "Be Consistent" boil down to "Just pick one and |
| 44 | stop worrying about it"; the potential value of allowing flexibility on these |
| 45 | points is outweighed by the cost of having people argue over them. |
| 46 | |
| 47 | ### Be consistent with Apple SDKs |
| 48 | |
| 49 | Consistency with the way Apple SDKs use Objective-C has value for the same |
| 50 | reasons as consistency within our code base. If an Objective-C feature solves a |
| 51 | problem that's an argument for using it. However, sometimes language features |
| 52 | and idioms are flawed, or were just designed with assumptions that are not |
| 53 | universal. In those cases it is appropriate to constrain or ban language |
| 54 | features or idioms. |
| 55 | |
| 56 | ### Style rules should pull their weight |
| 57 | |
| 58 | The benefit of a style rule must be large enough to justify asking engineers to |
| 59 | remember it. The benefit is measured relative to the codebase we would get |
| 60 | without the rule, so a rule against a very harmful practice may still have a |
| 61 | small benefit if people are unlikely to do it anyway. This principle mostly |
| 62 | explains the rules we don’t have, rather than the rules we do: for example, goto |
| 63 | contravenes many of the following principles, but is not discussed due to its |
| 64 | extreme rarity. |
| 65 | |
Kevin Lindkvist | c5197bf | 2017-07-25 19:21:16 -0700 | [diff] [blame] | 66 | ## Example |
| 67 | |
| 68 | They say an example is worth a thousand words, so let's start off with an |
| 69 | example that should give you a feel for the style, spacing, naming, and so on. |
| 70 | |
| 71 | Here is an example header file, demonstrating the correct commenting and spacing |
| 72 | for an `@interface` declaration. |
| 73 | |
Kevin Lindkvist | c5197bf | 2017-07-25 19:21:16 -0700 | [diff] [blame] | 74 | ```objectivec |
| 75 | // GOOD: |
| 76 | |
| 77 | #import <Foundation/Foundation.h> |
| 78 | |
| 79 | @class Bar; |
| 80 | |
| 81 | /** |
| 82 | * A sample class demonstrating good Objective-C style. All interfaces, |
| 83 | * categories, and protocols (read: all non-trivial top-level declarations |
| 84 | * in a header) MUST be commented. Comments must also be adjacent to the |
| 85 | * object they're documenting. |
| 86 | */ |
| 87 | @interface Foo : NSObject |
| 88 | |
| 89 | /** The retained Bar. */ |
| 90 | @property(nonatomic) Bar *bar; |
| 91 | |
| 92 | /** The current drawing attributes. */ |
| 93 | @property(nonatomic, copy) NSDictionary<NSString *, NSNumber *> *attributes; |
| 94 | |
| 95 | /** |
| 96 | * Convenience creation method. |
| 97 | * See -initWithBar: for details about @c bar. |
| 98 | * |
| 99 | * @param bar The string for fooing. |
| 100 | * @return An instance of Foo. |
| 101 | */ |
| 102 | + (instancetype)fooWithBar:(Bar *)bar; |
| 103 | |
| 104 | /** |
| 105 | * Designated initializer. |
| 106 | * |
| 107 | * @param bar A string that represents a thing that does a thing. |
| 108 | */ |
| 109 | - (instancetype)initWithBar:(Bar *)bar; |
| 110 | |
| 111 | /** |
| 112 | * Does some work with @c blah. |
| 113 | * |
| 114 | * @param blah |
| 115 | * @return YES if the work was completed; NO otherwise. |
| 116 | */ |
| 117 | - (BOOL)doWorkWithBlah:(NSString *)blah; |
| 118 | |
| 119 | @end |
| 120 | ``` |
| 121 | |
| 122 | An example source file, demonstrating the correct commenting and spacing for the |
| 123 | `@implementation` of an interface. |
| 124 | |
| 125 | ```objectivec |
| 126 | // GOOD: |
| 127 | |
| 128 | #import "Shared/Util/Foo.h" |
| 129 | |
| 130 | @implementation Foo { |
Stephane Moore | 82d0af2 | 2017-08-23 14:59:52 -0700 | [diff] [blame] | 131 | /** The string used for displaying "hi". */ |
Kevin Lindkvist | c5197bf | 2017-07-25 19:21:16 -0700 | [diff] [blame] | 132 | NSString *_string; |
| 133 | } |
| 134 | |
| 135 | + (instancetype)fooWithBar:(Bar *)bar { |
| 136 | return [[self alloc] initWithBar:bar]; |
| 137 | } |
| 138 | |
| 139 | - (instancetype)init { |
| 140 | // Classes with a custom designated initializer should always override |
| 141 | // the superclass's designated initializer. |
| 142 | return [self initWithBar:nil]; |
| 143 | } |
| 144 | |
| 145 | - (instancetype)initWithBar:(Bar *)bar { |
| 146 | self = [super init]; |
| 147 | if (self) { |
| 148 | _bar = [bar copy]; |
| 149 | _string = [[NSString alloc] initWithFormat:@"hi %d", 3]; |
| 150 | _attributes = @{ |
| 151 | @"color" : [UIColor blueColor], |
| 152 | @"hidden" : @NO |
| 153 | }; |
| 154 | } |
| 155 | return self; |
| 156 | } |
| 157 | |
| 158 | - (BOOL)doWorkWithBlah:(NSString *)blah { |
| 159 | // Work should be done here. |
| 160 | return NO; |
| 161 | } |
| 162 | |
| 163 | @end |
| 164 | ``` |
| 165 | |
| 166 | ## Spacing and Formatting |
| 167 | |
| 168 | ### Spaces vs. Tabs |
| 169 | |
| 170 | Use only spaces, and indent 2 spaces at a time. We use spaces for indentation. |
| 171 | Do not use tabs in your code. |
| 172 | |
| 173 | You should set your editor to emit spaces when you hit the tab key, and to trim |
| 174 | trailing spaces on lines. |
| 175 | |
| 176 | ### Line Length |
| 177 | |
| 178 | The maximum line length for Objective-C files is 100 columns. |
| 179 | |
| 180 | You can make violations easier to spot by enabling *Preferences > Text Editing > |
| 181 | Page guide at column: 100* in Xcode. |
| 182 | |
| 183 | ### Method Declarations and Definitions |
| 184 | |
| 185 | One space should be used between the `-` or `+` and the return type, and no |
| 186 | spacing in the parameter list except between parameters. |
| 187 | |
| 188 | Methods should look like this: |
| 189 | |
| 190 | ```objectivec |
| 191 | // GOOD: |
| 192 | |
| 193 | - (void)doSomethingWithString:(NSString *)theString { |
| 194 | ... |
| 195 | } |
| 196 | ``` |
| 197 | |
| 198 | The spacing before the asterisk is optional. When adding new code, be consistent |
| 199 | with the surrounding file's style. |
| 200 | |
| 201 | If you have too many parameters to fit on one line, giving each its own line is |
| 202 | preferred. If multiple lines are used, align each using the colon before the |
| 203 | parameter. |
| 204 | |
| 205 | ```objectivec |
| 206 | // GOOD: |
| 207 | |
| 208 | - (void)doSomethingWithFoo:(GTMFoo *)theFoo |
| 209 | rect:(NSRect)theRect |
| 210 | interval:(float)theInterval { |
| 211 | ... |
| 212 | } |
| 213 | ``` |
| 214 | |
| 215 | When the second or later parameter name is longer than the first, indent the |
| 216 | second and later lines by at least four spaces, maintaining colon alignment: |
| 217 | |
| 218 | ```objectivec |
| 219 | // GOOD: |
| 220 | |
| 221 | - (void)short:(GTMFoo *)theFoo |
| 222 | longKeyword:(NSRect)theRect |
| 223 | evenLongerKeyword:(float)theInterval |
| 224 | error:(NSError **)theError { |
| 225 | ... |
| 226 | } |
| 227 | ``` |
| 228 | |
| 229 | ### Conditionals |
| 230 | |
| 231 | Include a space after `if`, `while`, `for`, and `switch`, and around comparison |
| 232 | operators. |
| 233 | |
| 234 | ```objectivec |
| 235 | // GOOD: |
| 236 | |
| 237 | for (int i = 0; i < 5; ++i) { |
| 238 | } |
| 239 | |
| 240 | while (test) {}; |
| 241 | ``` |
| 242 | |
| 243 | Braces may be omitted when a loop body or conditional statement fits on a single |
| 244 | line. |
| 245 | |
| 246 | ```objectivec |
| 247 | // GOOD: |
| 248 | |
| 249 | if (hasSillyName) LaughOutLoud(); |
| 250 | |
| 251 | for (int i = 0; i < 10; i++) { |
| 252 | BlowTheHorn(); |
| 253 | } |
| 254 | ``` |
| 255 | |
| 256 | ```objectivec |
| 257 | // AVOID: |
| 258 | |
| 259 | if (hasSillyName) |
| 260 | LaughOutLoud(); // AVOID. |
| 261 | |
| 262 | for (int i = 0; i < 10; i++) |
| 263 | BlowTheHorn(); // AVOID. |
| 264 | ``` |
| 265 | |
| 266 | If an `if` clause has an `else` clause, both clauses should use braces. |
| 267 | |
| 268 | ```objectivec |
| 269 | // GOOD: |
| 270 | |
| 271 | if (hasBaz) { |
| 272 | foo(); |
| 273 | } else { |
| 274 | bar(); |
| 275 | } |
| 276 | ``` |
| 277 | |
| 278 | ```objectivec |
| 279 | // AVOID: |
| 280 | |
| 281 | if (hasBaz) foo(); |
| 282 | else bar(); // AVOID. |
| 283 | |
| 284 | if (hasBaz) { |
| 285 | foo(); |
| 286 | } else bar(); // AVOID. |
| 287 | ``` |
| 288 | |
| 289 | Intentional fall-through to the next case should be documented with a comment |
| 290 | unless the case has no intervening code before the next case. |
| 291 | |
| 292 | ```objectivec |
| 293 | // GOOD: |
| 294 | |
| 295 | switch (i) { |
| 296 | case 1: |
| 297 | ... |
| 298 | break; |
| 299 | case 2: |
| 300 | j++; |
| 301 | // Falls through. |
| 302 | case 3: { |
| 303 | int k; |
| 304 | ... |
| 305 | break; |
| 306 | } |
| 307 | case 4: |
| 308 | case 5: |
| 309 | case 6: break; |
| 310 | } |
| 311 | ``` |
| 312 | |
| 313 | ### Expressions |
| 314 | |
| 315 | Use a space around binary operators and assignments. Omit a space for a unary |
| 316 | operator. Do not add spaces inside parentheses. |
| 317 | |
| 318 | ```objectivec |
| 319 | // GOOD: |
| 320 | |
| 321 | x = 0; |
| 322 | v = w * x + y / z; |
| 323 | v = -y * (x + z); |
| 324 | ``` |
| 325 | |
| 326 | Factors in an expression may omit spaces. |
| 327 | |
| 328 | ```objectivec |
| 329 | // GOOD: |
| 330 | |
| 331 | v = w*x + y/z; |
| 332 | ``` |
| 333 | |
| 334 | ### Method Invocations |
| 335 | |
| 336 | Method invocations should be formatted much like method declarations. |
| 337 | |
| 338 | When there's a choice of formatting styles, follow the convention already used |
| 339 | in a given source file. Invocations should have all arguments on one line: |
| 340 | |
| 341 | ```objectivec |
| 342 | // GOOD: |
| 343 | |
| 344 | [myObject doFooWith:arg1 name:arg2 error:arg3]; |
| 345 | ``` |
| 346 | |
| 347 | or have one argument per line, with colons aligned: |
| 348 | |
| 349 | ```objectivec |
| 350 | // GOOD: |
| 351 | |
| 352 | [myObject doFooWith:arg1 |
| 353 | name:arg2 |
| 354 | error:arg3]; |
| 355 | ``` |
| 356 | |
| 357 | Don't use any of these styles: |
| 358 | |
| 359 | ```objectivec |
| 360 | // AVOID: |
| 361 | |
| 362 | [myObject doFooWith:arg1 name:arg2 // some lines with >1 arg |
| 363 | error:arg3]; |
| 364 | |
| 365 | [myObject doFooWith:arg1 |
| 366 | name:arg2 error:arg3]; |
| 367 | |
| 368 | [myObject doFooWith:arg1 |
| 369 | name:arg2 // aligning keywords instead of colons |
| 370 | error:arg3]; |
| 371 | ``` |
| 372 | |
| 373 | As with declarations and definitions, when the first keyword is shorter than the |
| 374 | others, indent the later lines by at least four spaces, maintaining colon |
| 375 | alignment: |
| 376 | |
| 377 | ```objectivec |
| 378 | // GOOD: |
| 379 | |
| 380 | [myObj short:arg1 |
| 381 | longKeyword:arg2 |
| 382 | evenLongerKeyword:arg3 |
| 383 | error:arg4]; |
| 384 | ``` |
| 385 | |
| 386 | Invocations containing multiple inlined blocks may have their parameter names |
| 387 | left-aligned at a four space indent. |
| 388 | |
| 389 | ### Function Calls |
| 390 | |
| 391 | Function calls should include as many parameters as fit on each line, except |
| 392 | where shorter lines are needed for clarity or documentation of the parameters. |
| 393 | |
| 394 | Continuation lines for function parameters may be indented to align with the |
| 395 | opening parenthesis, or may have a four-space indent. |
| 396 | |
| 397 | ```objectivec |
| 398 | // GOOD: |
| 399 | |
| 400 | CFArrayRef array = CFArrayCreate(kCFAllocatorDefault, objects, numberOfObjects, |
| 401 | &kCFTypeArrayCallBacks); |
| 402 | |
| 403 | NSString *string = NSLocalizedStringWithDefaultValue(@"FEET", @"DistanceTable", |
| 404 | resourceBundle, @"%@ feet", @"Distance for multiple feet"); |
| 405 | |
| 406 | UpdateTally(scores[x] * y + bases[x], // Score heuristic. |
| 407 | x, y, z); |
| 408 | |
| 409 | TransformImage(image, |
| 410 | x1, x2, x3, |
| 411 | y1, y2, y3, |
| 412 | z1, z2, z3); |
| 413 | ``` |
| 414 | |
| 415 | Use local variables with descriptive names to shorten function calls and reduce |
| 416 | nesting of calls. |
| 417 | |
| 418 | ```objectivec |
| 419 | // GOOD: |
| 420 | |
| 421 | double scoreHeuristic = scores[x] * y + bases[x]; |
| 422 | UpdateTally(scoreHeuristic, x, y, z); |
| 423 | ``` |
| 424 | |
| 425 | ### Exceptions |
| 426 | |
| 427 | Format exceptions with `@catch` and `@finally` labels on the same line as the |
| 428 | preceding `}`. Add a space between the `@` label and the opening brace (`{`), as |
| 429 | well as between the `@catch` and the caught object declaration. If you must use |
| 430 | Objective-C exceptions, format them as follows. However, see Avoid Throwing |
| 431 | Exceptions for reasons why you should not be using exceptions. |
| 432 | |
| 433 | ```objectivec |
| 434 | // GOOD: |
| 435 | |
| 436 | @try { |
| 437 | foo(); |
| 438 | } @catch (NSException *ex) { |
| 439 | bar(ex); |
| 440 | } @finally { |
| 441 | baz(); |
| 442 | } |
| 443 | ``` |
| 444 | |
| 445 | ### Function Length |
| 446 | |
| 447 | Prefer small and focused functions. |
| 448 | |
| 449 | Long functions and methods are occasionally appropriate, so no hard limit is |
| 450 | placed on function length. If a function exceeds about 40 lines, think about |
| 451 | whether it can be broken up without harming the structure of the program. |
| 452 | |
| 453 | Even if your long function works perfectly now, someone modifying it in a few |
| 454 | months may add new behavior. This could result in bugs that are hard to find. |
| 455 | Keeping your functions short and simple makes it easier for other people to read |
| 456 | and modify your code. |
| 457 | |
| 458 | When updating legacy code, consider also breaking long functions into smaller |
| 459 | and more manageable pieces. |
| 460 | |
| 461 | ### Vertical Whitespace |
| 462 | |
| 463 | Use vertical whitespace sparingly. |
| 464 | |
| 465 | To allow more code to be easily viewed on a screen, avoid putting blank lines |
| 466 | just inside the braces of functions. |
| 467 | |
| 468 | Limit blank lines to one or two between functions and between logical groups of |
| 469 | code. |
| 470 | |
| 471 | ## Naming |
| 472 | |
| 473 | Names should be as descriptive as possible, within reason. Follow standard |
| 474 | [Objective-C naming |
| 475 | rules](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html). |
| 476 | |
| 477 | Avoid non-standard abbreviations. Don't worry about saving horizontal space as |
| 478 | it is far more important to make your code immediately understandable by a new |
| 479 | reader. For example: |
| 480 | |
| 481 | ```objectivec |
| 482 | // GOOD: |
| 483 | |
| 484 | // Good names. |
| 485 | int numberOfErrors = 0; |
| 486 | int completedConnectionsCount = 0; |
| 487 | tickets = [[NSMutableArray alloc] init]; |
| 488 | userInfo = [someObject object]; |
| 489 | port = [network port]; |
| 490 | NSDate *gAppLaunchDate; |
| 491 | ``` |
| 492 | |
| 493 | ```objectivec |
| 494 | // AVOID: |
| 495 | |
| 496 | // Names to avoid. |
| 497 | int w; |
| 498 | int nerr; |
| 499 | int nCompConns; |
| 500 | tix = [[NSMutableArray alloc] init]; |
| 501 | obj = [someObject object]; |
| 502 | p = [network port]; |
| 503 | ``` |
| 504 | |
| 505 | Any class, category, method, function, or variable name should use all capitals |
| 506 | for acronyms and |
| 507 | [initialisms](https://en.wikipedia.org/wiki/Initialism) |
| 508 | within the name. This follows Apple's standard of using all capitals within a |
| 509 | name for acronyms such as URL, ID, TIFF, and EXIF. |
| 510 | |
| 511 | Names of C functions and typedefs should be capitalized and use camel case as |
| 512 | appropriate for the surrounding code. |
| 513 | |
| 514 | ### File Names |
| 515 | |
| 516 | File names should reflect the name of the class implementation that they |
| 517 | contain—including case. |
| 518 | |
| 519 | Follow the convention that your project uses. |
| 520 | File extensions should be as follows: |
| 521 | |
| 522 | Extension | Type |
| 523 | --------- | --------------------------------- |
| 524 | .h | C/C++/Objective-C header file |
| 525 | .m | Objective-C implementation file |
| 526 | .mm | Objective-C++ implementation file |
| 527 | .cc | Pure C++ implementation file |
| 528 | .c | C implementation file |
| 529 | |
| 530 | Files containing code that may be shared across projects or used in a large |
| 531 | project should have a clearly unique name, typically including the project or |
| 532 | class prefix. |
| 533 | |
| 534 | File names for categories should include the name of the class being extended, |
| 535 | like GTMNSString+Utils.h or NSTextView+GTMAutocomplete.h |
| 536 | |
| 537 | ### Class Names |
| 538 | |
| 539 | Class names (along with category and protocol names) should start as uppercase |
| 540 | and use mixed case to delimit words. |
| 541 | |
| 542 | When designing code to be shared across multiple applications, prefixes are |
| 543 | acceptable and recommended (e.g. GTMSendMessage). Prefixes are also recommended |
| 544 | for classes of large applications that depend on external libraries. |
| 545 | |
| 546 | ### Category Names |
| 547 | |
| 548 | Category names should start with a 3 character prefix identifying the category |
| 549 | as part of a project or open for general use. |
| 550 | |
| 551 | The category name should incorporate the name of the class it's extending. For |
| 552 | example, if we want to create a category on `NSString` for parsing, we would put |
| 553 | the category in a file named `NSString+GTMParsing.h`, and the category itself |
| 554 | would be named `GTMNSStringParsingAdditions`. The file name and the category may |
| 555 | not match, as this file could have many separate categories related to parsing. |
| 556 | Methods in that category should share the prefix |
| 557 | (`gtm_myCategoryMethodOnAString:`) in order to prevent collisions in |
| 558 | Objective-C's global namespace. |
| 559 | |
| 560 | There should be a single space between the class name and the opening |
| 561 | parenthesis of the category. |
| 562 | |
| 563 | ```objectivec |
| 564 | // GOOD: |
| 565 | |
Stephane Moore | 4264801 | 2017-10-16 18:11:48 -0700 | [diff] [blame] | 566 | /** A category that adds parsing functionality to NSString. */ |
Kevin Lindkvist | c5197bf | 2017-07-25 19:21:16 -0700 | [diff] [blame] | 567 | @interface NSString (GTMNSStringParsingAdditions) |
| 568 | - (NSString *)gtm_parsedString; |
| 569 | @end |
| 570 | ``` |
| 571 | |
| 572 | ### Objective-C Method Names |
| 573 | |
| 574 | Method and parameter names typically start as lowercase and then use mixed case. |
| 575 | |
| 576 | Proper capitalization should be respected, including at the beginning of names. |
| 577 | |
| 578 | ```objectivec |
| 579 | // GOOD: |
| 580 | |
Stephane Moore | 4264801 | 2017-10-16 18:11:48 -0700 | [diff] [blame] | 581 | + (NSURL *)URLWithString:(NSString *)URLString; |
Kevin Lindkvist | c5197bf | 2017-07-25 19:21:16 -0700 | [diff] [blame] | 582 | ``` |
| 583 | |
| 584 | The method name should read like a sentence if possible, meaning you should |
| 585 | choose parameter names that flow with the method name. Objective-C method names |
| 586 | tend to be very long, but this has the benefit that a block of code can almost |
| 587 | read like prose, thus rendering many implementation comments unnecessary. |
| 588 | |
| 589 | Use prepositions and conjunctions like "with", "from", and "to" in the second |
| 590 | and later parameter names only where necessary to clarify the meaning or |
| 591 | behavior of the method. |
| 592 | |
| 593 | ```objectivec |
| 594 | // GOOD: |
| 595 | |
| 596 | - (void)addTarget:(id)target action:(SEL)action; // GOOD; no conjunction needed |
| 597 | - (CGPoint)convertPoint:(CGPoint)point fromView:(UIView *)view; // GOOD; conjunction clarifies parameter |
| 598 | - (void)replaceCharactersInRange:(NSRange)aRange |
| 599 | withAttributedString:(NSAttributedString *)attributedString; // GOOD. |
| 600 | ``` |
| 601 | |
| 602 | A method that returns an object should have a name beginning with a noun |
| 603 | identifying the object returned: |
| 604 | |
| 605 | ```objectivec |
| 606 | // GOOD: |
| 607 | |
| 608 | - (Sandwich *)sandwich; // GOOD. |
| 609 | ``` |
| 610 | |
| 611 | ```objectivec |
| 612 | // AVOID: |
| 613 | |
| 614 | - (Sandwich *)makeSandwich; // AVOID. |
| 615 | ``` |
| 616 | |
| 617 | An accessor method should be named the same as the object it's getting, but it |
| 618 | should not be prefixed with the word `get`. For example: |
| 619 | |
| 620 | ```objectivec |
| 621 | // GOOD: |
| 622 | |
| 623 | - (id)delegate; // GOOD. |
| 624 | ``` |
| 625 | |
| 626 | ```objectivec |
| 627 | // AVOID: |
| 628 | |
| 629 | - (id)getDelegate; // AVOID. |
| 630 | ``` |
| 631 | |
| 632 | Accessors that return the value of boolean adjectives have method names |
| 633 | beginning with `is`, but property names for those methods omit the `is`. |
| 634 | |
| 635 | Dot notation is used only with property names, not with method names. |
| 636 | |
| 637 | ```objectivec |
| 638 | // GOOD: |
| 639 | |
| 640 | @property(nonatomic, getter=isGlorious) BOOL glorious; |
| 641 | - (BOOL)isGlorious; |
| 642 | |
| 643 | BOOL isGood = object.glorious; // GOOD. |
| 644 | BOOL isGood = [object isGlorious]; // GOOD. |
| 645 | ``` |
| 646 | |
| 647 | ```objectivec |
| 648 | // AVOID: |
| 649 | |
| 650 | BOOL isGood = object.isGlorious; // AVOID. |
| 651 | ``` |
| 652 | |
| 653 | ```objectivec |
| 654 | // GOOD: |
| 655 | |
| 656 | NSArray<Frog *> *frogs = [NSArray<Frog *> arrayWithObject:frog]; |
| 657 | NSEnumerator *enumerator = [frogs reverseObjectEnumerator]; // GOOD. |
| 658 | ``` |
| 659 | |
| 660 | ```objectivec |
| 661 | // AVOID: |
| 662 | |
| 663 | NSEnumerator *enumerator = frogs.reverseObjectEnumerator; // AVOID. |
| 664 | ``` |
| 665 | |
| 666 | See [Apple's Guide to Naming |
| 667 | Methods](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingMethods.html#//apple_ref/doc/uid/20001282-BCIGIJJF) |
| 668 | for more details on Objective-C naming. |
| 669 | |
| 670 | These guidelines are for Objective-C methods only. C++ method names continue to |
| 671 | follow the rules set in the C++ style guide. |
| 672 | |
| 673 | ### Function Names |
| 674 | |
| 675 | Regular functions have mixed case. |
| 676 | |
| 677 | Ordinarily, functions should start with a capital letter and have a capital |
| 678 | letter for each new word (a.k.a. "[Camel |
| 679 | Case](https://en.wikipedia.org/wiki/Camel_case)" or "Pascal case"). |
| 680 | |
| 681 | ```objectivec |
| 682 | // GOOD: |
| 683 | |
| 684 | static void AddTableEntry(NSString *tableEntry); |
| 685 | static BOOL DeleteFile(char *filename); |
| 686 | ``` |
| 687 | |
| 688 | Because Objective-C does not provide namespacing, non-static functions should |
| 689 | have a prefix that minimizes the chance of a name collision. |
| 690 | |
| 691 | ```objectivec |
| 692 | // GOOD: |
| 693 | |
| 694 | extern NSTimeZone *GTMGetDefaultTimeZone(); |
| 695 | extern NSString *GTMGetURLScheme(NSURL *URL); |
| 696 | ``` |
| 697 | |
| 698 | ### Variable Names |
| 699 | |
| 700 | Variable names typically start with a lowercase and use mixed case to delimit |
| 701 | words. |
| 702 | |
| 703 | Instance variables have leading underscores. File scope or global variables have |
| 704 | a prefix `g`. For example: `myLocalVariable`, `_myInstanceVariable`, |
| 705 | `gMyGlobalVariable`. |
| 706 | |
| 707 | #### Common Variable Names |
| 708 | |
| 709 | Readers should be able to infer the variable type from the name, but do not use |
| 710 | Hungarian notation for syntactic attributes, such as the static type of a |
| 711 | variable (int or pointer). |
| 712 | |
| 713 | File scope or global variables (as opposed to constants) declared outside the |
| 714 | scope of a method or function should be rare, and should have the prefix g. |
| 715 | |
| 716 | ```objectivec |
| 717 | // GOOD: |
| 718 | |
| 719 | static int gGlobalCounter; |
| 720 | ``` |
| 721 | |
| 722 | #### Instance Variables |
| 723 | |
| 724 | Instance variable names are mixed case and should be prefixed with an |
| 725 | underscore, like `_usernameTextField`. |
| 726 | |
| 727 | NOTE: Google's previous convention for Objective-C ivars was a trailing |
| 728 | underscore. Existing projects may opt to continue using trailing underscores in |
| 729 | new code in order to maintain consistency within the project codebase. |
| 730 | Consistency of prefix or suffix underscores should be maintained within each |
| 731 | class. |
| 732 | |
| 733 | #### Constants |
| 734 | |
| 735 | Constant symbols (const global and static variables and constants created |
| 736 | with #define) should use mixed case to delimit words. |
| 737 | |
Stephane Moore | 4264801 | 2017-10-16 18:11:48 -0700 | [diff] [blame] | 738 | Global and file scope constants should have an appropriate prefix. |
Kevin Lindkvist | c5197bf | 2017-07-25 19:21:16 -0700 | [diff] [blame] | 739 | |
| 740 | ```objectivec |
| 741 | // GOOD: |
| 742 | |
| 743 | extern NSString *const GTLServiceErrorDomain; |
| 744 | |
| 745 | typedef NS_ENUM(NSInteger, GTLServiceError) { |
| 746 | GTLServiceErrorQueryResultMissing = -3000, |
| 747 | GTLServiceErrorWaitTimedOut = -3001, |
| 748 | }; |
| 749 | ``` |
| 750 | |
| 751 | Because Objective-C does not provide namespacing, constants with external |
| 752 | linkage should have a prefix that minimizes the chance of a name collision, |
| 753 | typically like `ClassNameConstantName` or `ClassNameEnumName`. |
| 754 | |
| 755 | For interoperability with Swift code, enumerated values should have names that |
| 756 | extend the typedef name: |
| 757 | |
| 758 | ```objectivec |
| 759 | // GOOD: |
| 760 | |
| 761 | typedef NS_ENUM(NSInteger, DisplayTinge) { |
| 762 | DisplayTingeGreen = 1, |
| 763 | DisplayTingeBlue = 2, |
| 764 | }; |
| 765 | ``` |
| 766 | |
| 767 | Constants may use a lowercase k prefix when appropriate: |
| 768 | |
| 769 | ```objectivec |
| 770 | // GOOD: |
| 771 | |
| 772 | static const int kFileCount = 12; |
| 773 | static NSString *const kUserKey = @"kUserKey"; |
| 774 | ``` |
| 775 | |
| 776 | ## Types and Declarations |
| 777 | |
| 778 | ### Local Variables |
| 779 | |
| 780 | Declare variables in the narrowest practical scopes, and close to their use. |
| 781 | Initialize variables in their declarations. |
| 782 | |
| 783 | ```objectivec |
| 784 | // GOOD: |
| 785 | |
| 786 | CLLocation *location = [self lastKnownLocation]; |
| 787 | for (int meters = 1; meters < 10; meters++) { |
| 788 | reportFrogsWithinRadius(location, meters); |
| 789 | } |
| 790 | ``` |
| 791 | |
| 792 | Occasionally, efficiency will make it more appropriate to declare a variable |
| 793 | outside the scope of its use. This example declares meters separate from |
| 794 | initialization, and needlessly sends the lastKnownLocation message each time |
| 795 | through the loop: |
| 796 | |
| 797 | ```objectivec |
| 798 | // AVOID: |
| 799 | |
| 800 | int meters; // AVOID. |
| 801 | for (meters = 1; meters < 10; meters++) { |
| 802 | CLLocation *location = [self lastKnownLocation]; // AVOID. |
| 803 | reportFrogsWithinRadius(location, meters); |
| 804 | } |
| 805 | ``` |
| 806 | |
| 807 | Under Automatic Reference Counting, pointers to Objective-C objects are by |
| 808 | default initialized to `nil`, so explicit initialization to `nil` is not |
| 809 | required. |
| 810 | |
| 811 | ### Unsigned Integers |
| 812 | |
| 813 | Avoid unsigned integers except when matching types used by system interfaces. |
| 814 | |
| 815 | Subtle errors crop up when doing math or counting down to zero using unsigned |
| 816 | integers. Rely only on signed integers in math expressions except when matching |
| 817 | NSUInteger in system interfaces. |
| 818 | |
| 819 | ```objectivec |
| 820 | // GOOD: |
| 821 | |
| 822 | NSUInteger numberOfObjects = array.count; |
| 823 | for (NSInteger counter = numberOfObjects - 1; counter > 0; --counter) |
| 824 | ``` |
| 825 | |
| 826 | ```objectivec |
| 827 | // AVOID: |
| 828 | |
| 829 | for (NSUInteger counter = numberOfObjects - 1; counter > 0; --counter) // AVOID. |
| 830 | ``` |
| 831 | |
| 832 | Unsigned integers may be used for flags and bitmasks, though often NS_OPTIONS or |
| 833 | NS_ENUM will be more appropriate. |
| 834 | |
| 835 | ### Types with Inconsistent Sizes |
| 836 | |
| 837 | Due to sizes that differ in 32- and 64-bit builds, avoid types long, NSInteger, |
| 838 | NSUInteger, and CGFloat except when matching system interfaces. |
| 839 | |
| 840 | Types long, NSInteger, NSUInteger, and CGFloat vary in size between 32- and |
| 841 | 64-bit builds. Use of these types is appropriate when handling values exposed by |
| 842 | system interfaces, but they should be avoided for most other computations. |
| 843 | |
| 844 | ```objectivec |
| 845 | // GOOD: |
| 846 | |
| 847 | int32_t scalar1 = proto.intValue; |
| 848 | |
| 849 | int64_t scalar2 = proto.longValue; |
| 850 | |
| 851 | NSUInteger numberOfObjects = array.count; |
| 852 | |
| 853 | CGFloat offset = view.bounds.origin.x; |
| 854 | ``` |
| 855 | |
| 856 | ```objectivec |
| 857 | // AVOID: |
| 858 | |
| 859 | NSInteger scalar2 = proto.longValue; // AVOID. |
| 860 | ``` |
| 861 | |
| 862 | File and buffer sizes often exceed 32-bit limits, so they should be declared |
| 863 | using `int64_t`, not with `long`, `NSInteger`, or `NSUInteger`. |
| 864 | |
| 865 | ## Comments |
| 866 | |
| 867 | Comments are absolutely vital to keeping our code readable. The following rules |
| 868 | describe what you should comment and where. But remember: while comments are |
| 869 | important, the best code is self-documenting. Giving sensible names to types and |
| 870 | variables is much better than using obscure names and then trying to explain |
| 871 | them through comments. |
| 872 | |
| 873 | Pay attention to punctuation, spelling, and grammar; it is easier to read |
| 874 | well-written comments than badly written ones. |
| 875 | |
| 876 | Comments should be as readable as narrative text, with proper capitalization and |
| 877 | punctuation. In many cases, complete sentences are more readable than sentence |
| 878 | fragments. Shorter comments, such as comments at the end of a line of code, can |
| 879 | sometimes be less formal, but use a consistent style. |
| 880 | When writing your comments, write for your audience: the next contributor who will need to understand your code. Be generous—the next one may be you! |
| 881 | |
| 882 | ### File Comments |
| 883 | |
| 884 | A file may optionally start with a description of its contents. |
| 885 | Every file may contain the following items, in order: |
| 886 | * License boilerplate if necessary. Choose the appropriate boilerplate for the license used by the project. |
| 887 | * A basic description of the contents of the file if necessary. |
| 888 | |
| 889 | If you make significant changes to a file with an author line, consider deleting |
| 890 | the author line since revision history already provides a more detailed and |
| 891 | accurate record of authorship. |
| 892 | |
| 893 | |
| 894 | ### Declaration Comments |
| 895 | |
| 896 | Every non-trivial interface, public and private, should have an accompanying |
| 897 | comment describing its purpose and how it fits into the larger picture. |
| 898 | |
| 899 | Comments should be used to document classes, properties, ivars, functions, |
| 900 | categories, protocol declarations, and enums. |
| 901 | |
| 902 | ```objectivec |
| 903 | // GOOD: |
| 904 | |
| 905 | /** |
| 906 | * A delegate for NSApplication to handle notifications about app |
| 907 | * launch and shutdown. Owned by the main app controller. |
| 908 | */ |
| 909 | @interface MyAppDelegate : NSObject { |
| 910 | /** |
| 911 | * The background task in progress, if any. This is initialized |
| 912 | * to the value UIBackgroundTaskInvalid. |
| 913 | */ |
| 914 | UIBackgroundTaskIdentifier _backgroundTaskID; |
| 915 | } |
| 916 | |
| 917 | /** The factory that creates and manages fetchers for the app. */ |
| 918 | @property(nonatomic) GTMSessionFetcherService *fetcherService; |
| 919 | |
| 920 | @end |
| 921 | ``` |
| 922 | |
Stephane Moore | 82d0af2 | 2017-08-23 14:59:52 -0700 | [diff] [blame] | 923 | Doxygen-style comments are encouraged for interfaces as they are parsed by Xcode |
| 924 | to display formatted documentation. There is a wide variety of Doxygen commands; |
| 925 | use them consistently within a project. |
| 926 | |
Kevin Lindkvist | c5197bf | 2017-07-25 19:21:16 -0700 | [diff] [blame] | 927 | If you have already described an interface in detail in the comments at the top |
| 928 | of your file, feel free to simply state, "See comment at top of file for a |
| 929 | complete description", but be sure to have some sort of comment. |
| 930 | |
| 931 | Additionally, each method should have a comment explaining its function, |
| 932 | arguments, return value, thread or queue assumptions, and any side effects. |
| 933 | Documentation comments should be in the header for public methods, or |
| 934 | immediately preceding the method for non-trivial private methods. |
| 935 | |
| 936 | Use descriptive form ("Opens the file") rather than imperative form ("Open the |
| 937 | file") for method and function comments. The comment describes the function; it |
| 938 | does not tell the function what to do. |
| 939 | |
| 940 | Document the thread usage assumptions the class, properties, or methods make, if |
| 941 | any. If an instance of the class can be accessed by multiple threads, take extra |
| 942 | care to document the rules and invariants surrounding multithreaded use. |
| 943 | |
| 944 | Any sentinel values for properties and ivars, such as `NULL` or `-1`, should be |
| 945 | documented in comments. |
| 946 | |
| 947 | Declaration comments explain how a method or function is used. Comments |
| 948 | explaining how a method or function is implemented should be with the |
| 949 | implementation rather than with the declaration. |
| 950 | |
| 951 | ### Implementation Comments |
| 952 | |
| 953 | Provide comments explaining tricky, subtle, or complicated sections of code. |
| 954 | |
| 955 | ```objectivec |
| 956 | // GOOD: |
| 957 | |
| 958 | // Set the property to nil before invoking the completion handler to |
| 959 | // avoid the risk of reentrancy leading to the callback being |
| 960 | // invoked again. |
| 961 | CompletionHandler handler = self.completionHandler; |
| 962 | self.completionHandler = nil; |
| 963 | handler(); |
| 964 | ``` |
| 965 | |
| 966 | When useful, also provide comments about implementation approaches that were |
| 967 | considered or abandoned. |
| 968 | |
| 969 | End-of-line comments should be separated from the code by at least 2 spaces. If |
| 970 | you have several comments on subsequent lines, it can often be more readable to |
| 971 | line them up. |
| 972 | |
| 973 | ```objectivec |
| 974 | // GOOD: |
| 975 | |
| 976 | [self doSomethingWithALongName]; // Two spaces before the comment. |
| 977 | [self doSomethingShort]; // More spacing to align the comment. |
| 978 | ``` |
| 979 | |
| 980 | ### Disambiguating Symbols |
| 981 | |
| 982 | Where needed to avoid ambiguity, use backticks or vertical bars to quote |
| 983 | variable names and symbols in comments in preference to using quotation marks |
| 984 | or naming the symbols inline. |
| 985 | |
| 986 | In Doxygen-style comments, prefer demarcating symbols with a monospace text |
| 987 | command, such as `@c`. |
| 988 | |
| 989 | Demarcation helps provide clarity when a symbol is a common word that might make |
| 990 | the sentence read like it was poorly constructed. A common example is the symbol |
| 991 | `count`: |
| 992 | |
| 993 | ```objectivec |
| 994 | // GOOD: |
| 995 | |
| 996 | // Sometimes `count` will be less than zero. |
| 997 | ``` |
| 998 | |
| 999 | or when quoting something which already contains quotes |
| 1000 | |
| 1001 | ```objectivec |
| 1002 | // GOOD: |
| 1003 | |
| 1004 | // Remember to call `StringWithoutSpaces("foo bar baz")` |
| 1005 | ``` |
| 1006 | |
| 1007 | Backticks or vertical bars are not needed when a symbol is self-apparent. |
| 1008 | |
| 1009 | ```objectivec |
| 1010 | // GOOD: |
| 1011 | |
| 1012 | // This class serves as a delegate to GTMDepthCharge. |
| 1013 | ``` |
| 1014 | |
| 1015 | Doxygen formatting is also suitable for identifying symbols. |
| 1016 | |
| 1017 | ```objectivec |
| 1018 | // GOOD: |
| 1019 | |
| 1020 | /** @param maximum The highest value for @c count. */ |
| 1021 | ``` |
| 1022 | |
| 1023 | ### Object Ownership |
| 1024 | |
| 1025 | For objects not managed by ARC, make the pointer ownership model as explicit as |
| 1026 | possible when it falls outside the most common Objective-C usage idioms. |
| 1027 | |
| 1028 | #### Manual Reference Counting |
| 1029 | |
| 1030 | Instance variables for NSObject-derived objects are presumed to be retained; if |
| 1031 | they are not retained, they should be either commented as weak or declared with |
| 1032 | the `__weak` lifetime qualifier. |
| 1033 | |
| 1034 | An exception is in Mac software for instance variables labeled as `@IBOutlets`, |
| 1035 | which are presumed to not be retained. |
| 1036 | |
| 1037 | Where instance variables are pointers to Core Foundation, C++, and other |
| 1038 | non-Objective-C objects, they should always be declared with strong and weak |
| 1039 | comments to indicate which pointers are and are not retained. Core Foundation |
| 1040 | and other non-Objective-C object pointers require explicit memory management, |
| 1041 | even when building for automatic reference counting. |
| 1042 | |
| 1043 | Examples of strong and weak declarations: |
| 1044 | |
| 1045 | ```objectivec |
| 1046 | // GOOD: |
| 1047 | |
| 1048 | @interface MyDelegate : NSObject |
| 1049 | |
| 1050 | @property(nonatomic) NSString *doohickey; |
| 1051 | @property(nonatomic, weak) NSString *parent; |
| 1052 | |
| 1053 | @end |
| 1054 | |
| 1055 | |
| 1056 | @implementation MyDelegate { |
| 1057 | IBOutlet NSButton *_okButton; // Normal NSControl; implicitly weak on Mac only |
| 1058 | |
| 1059 | AnObjcObject *_doohickey; // My doohickey |
Stephane Moore | 82d0af2 | 2017-08-23 14:59:52 -0700 | [diff] [blame] | 1060 | __weak MyObjcParent *_parent; // To send messages back (owns this instance) |
Kevin Lindkvist | c5197bf | 2017-07-25 19:21:16 -0700 | [diff] [blame] | 1061 | |
| 1062 | // non-NSObject pointers... |
| 1063 | CWackyCPPClass *_wacky; // Strong, some cross-platform object |
| 1064 | CFDictionaryRef *_dict; // Strong |
| 1065 | } |
| 1066 | @end |
| 1067 | ``` |
| 1068 | |
| 1069 | #### Automatic Reference Counting |
| 1070 | |
| 1071 | Object ownership and lifetime are explicit when using ARC, so no additional |
| 1072 | comments are required for automatically retained objects. |
| 1073 | |
| 1074 | ## C Language Features |
| 1075 | |
| 1076 | ### Macros |
| 1077 | |
| 1078 | Avoid macros, especially where `const` variables, enums, XCode snippets, or C |
| 1079 | functions may be used instead. |
| 1080 | |
| 1081 | Macros make the code you see different from the code the compiler sees. Modern C |
| 1082 | renders traditional uses of macros for constants and utility functions |
| 1083 | unnecessary. Macros should only be used when there is no other solution |
| 1084 | available. |
| 1085 | |
| 1086 | Where a macro is needed, use a unique name to avoid the risk of a symbol |
| 1087 | collision in the compilation unit. If practical, keep the scope limited by |
| 1088 | `#undefining` the macro after its use. |
| 1089 | |
| 1090 | Macro names should use `SHOUTY_SNAKE_CASE`—all uppercase letters with |
| 1091 | underscores between words. Function-like macros may use C function naming |
| 1092 | practices. Do not define macros that appear to be C or Objective-C keywords. |
| 1093 | |
| 1094 | ```objectivec |
| 1095 | // GOOD: |
| 1096 | |
| 1097 | #define GTM_EXPERIMENTAL_BUILD ... // GOOD |
| 1098 | |
| 1099 | // Assert unless X > Y |
| 1100 | #define GTM_ASSERT_GT(X, Y) ... // GOOD, macro style. |
| 1101 | |
| 1102 | // Assert unless X > Y |
| 1103 | #define GTMAssertGreaterThan(X, Y) ... // GOOD, function style. |
| 1104 | ``` |
| 1105 | |
| 1106 | ```objectivec |
| 1107 | // AVOID: |
| 1108 | |
| 1109 | #define kIsExperimentalBuild ... // AVOID |
| 1110 | |
| 1111 | #define unless(X) if(!(X)) // AVOID |
| 1112 | ``` |
| 1113 | |
| 1114 | Avoid macros that expand to unbalanced C or Objective-C constructs. Avoid macros |
| 1115 | that introduce scope, or may obscure the capturing of values in blocks. |
| 1116 | |
| 1117 | Avoid macros that generate class, property, or method definitions in |
| 1118 | headers to be used as public API. These only make the code hard to |
| 1119 | understand, and the language already has better ways of doing this. |
| 1120 | |
| 1121 | Avoid macros that generate method implementations, or that generate declarations |
| 1122 | of variables that are later used outside of the macro. Macros shouldn't make |
| 1123 | code hard to understand by hiding where and how a variable is declared. |
| 1124 | |
| 1125 | ```objectivec |
| 1126 | // AVOID: |
| 1127 | |
| 1128 | #define ARRAY_ADDER(CLASS) \ |
| 1129 | -(void)add ## CLASS ## :(CLASS *)obj toArray:(NSMutableArray *)array |
| 1130 | |
| 1131 | ARRAY_ADDER(NSString) { |
| 1132 | if (array.count > 5) { // AVOID -- where is 'array' defined? |
| 1133 | ... |
| 1134 | } |
| 1135 | } |
| 1136 | ``` |
| 1137 | |
| 1138 | Examples of acceptable macro use include assertion and debug logging macros |
| 1139 | that are conditionally compiled based on build settings—often, these are |
| 1140 | not compiled into release builds. |
| 1141 | |
| 1142 | ### Nonstandard Extensions |
| 1143 | |
| 1144 | Nonstandard extensions to C/Objective-C may not be used unless otherwise |
| 1145 | specified. |
| 1146 | |
| 1147 | Compilers support various extensions that are not part of standard C. Examples |
| 1148 | include compound statement expressions (e.g. `foo = ({ int x; Bar(&x); x }))` |
| 1149 | and variable-length arrays. |
| 1150 | |
| 1151 | `__attribute__` is an approved exception, as it is used in Objective-C API |
| 1152 | specifications. |
| 1153 | |
| 1154 | The binary form of the conditional operator, `A ?: B`, is an approved exception. |
| 1155 | |
| 1156 | ## Cocoa and Objective-C Features |
| 1157 | |
| 1158 | ### Identify Designated Initializer |
| 1159 | |
| 1160 | Clearly identify your designated initializer. |
| 1161 | |
| 1162 | It is important for those who might be subclassing your class that the |
| 1163 | designated initializer be clearly identified. That way, they only need to |
| 1164 | override a single initializer (of potentially several) to guarantee the |
| 1165 | initializer of their subclass is called. It also helps those debugging your |
| 1166 | class in the future understand the flow of initialization code if they need to |
| 1167 | step through it. Identify the designated initializer using comments or the |
| 1168 | `NS_DESIGNATED_INITIALIZER` macro. If you use `NS_DESIGNATED_INITIALIZER`, mark |
| 1169 | unsupported initializers with `NS_UNAVAILABLE`. |
| 1170 | |
| 1171 | ### Override Designated Initializer |
| 1172 | |
| 1173 | When writing a subclass that requires an `init...` method, make sure you |
| 1174 | override the designated initializer of the superclass. |
| 1175 | |
| 1176 | If you fail to override the designated initializer of the superclass, your |
| 1177 | initializer may not be called in all cases, leading to subtle and very difficult |
| 1178 | to find bugs. |
| 1179 | |
| 1180 | ### Overridden NSObject Method Placement |
| 1181 | |
| 1182 | Put overridden methods of NSObject at the top of an `@implementation`. |
| 1183 | |
| 1184 | This commonly applies to (but is not limited to) the `init...`, `copyWithZone:`, |
| 1185 | and `dealloc` methods. The `init...` methods should be grouped together, |
| 1186 | followed by other typical `NSObject` methods such as `description`, `isEqual:`, |
| 1187 | and `hash`. |
| 1188 | |
| 1189 | Convenience class factory methods for creating instances may precede the |
| 1190 | `NSObject` methods. |
| 1191 | |
| 1192 | ### Initialization |
| 1193 | |
| 1194 | Don't initialize instance variables to `0` or `nil` in the `init` method; doing |
| 1195 | so is redundant. |
| 1196 | |
| 1197 | All instance variables for a newly allocated object are [initialized |
| 1198 | to](https://developer.apple.com/library/mac/documentation/General/Conceptual/CocoaEncyclopedia/ObjectAllocation/ObjectAllocation.html) |
| 1199 | `0` (except for isa), so don't clutter up the init method by re-initializing |
| 1200 | variables to `0` or `nil`. |
| 1201 | |
| 1202 | ### Instance Variables In Headers Should Be @protected or @private |
| 1203 | |
| 1204 | Instance variables should typically be declared in implementation files or |
| 1205 | auto-synthesized by properties. When ivars are declared in a header file, they |
| 1206 | should be marked `@protected` or `@private`. |
| 1207 | |
| 1208 | ```objectivec |
| 1209 | // GOOD: |
| 1210 | |
| 1211 | @interface MyClass : NSObject { |
| 1212 | @protected |
| 1213 | id _myInstanceVariable; |
| 1214 | } |
| 1215 | @end |
| 1216 | ``` |
| 1217 | |
| 1218 | ### Avoid +new |
| 1219 | |
| 1220 | Do not invoke the `NSObject` class method `new`, nor override it in a subclass. |
| 1221 | Instead, use `alloc` and `init` methods to instantiate retained objects. |
| 1222 | |
| 1223 | Modern Objective-C code explicitly calls `alloc` and an `init` method to create |
| 1224 | and retain an object. As the `new` class method is rarely used, it makes |
| 1225 | reviewing code for correct memory management more difficult. |
| 1226 | |
| 1227 | ### Keep the Public API Simple |
| 1228 | |
| 1229 | Keep your class simple; avoid "kitchen-sink" APIs. If a method doesn't need to |
| 1230 | be public, keep it out of the public interface. |
| 1231 | |
| 1232 | Unlike C++, Objective-C doesn't differentiate between public and private |
| 1233 | methods; any message may be sent to an object. As a result, avoid placing |
| 1234 | methods in the public API unless they are actually expected to be used by a |
| 1235 | consumer of the class. This helps reduce the likelihood they'll be called when |
| 1236 | you're not expecting it. This includes methods that are being overridden from |
| 1237 | the parent class. |
| 1238 | |
| 1239 | Since internal methods are not really private, it's easy to accidentally |
| 1240 | override a superclass's "private" method, thus making a very difficult bug to |
| 1241 | squash. In general, private methods should have a fairly unique name that will |
| 1242 | prevent subclasses from unintentionally overriding them. |
| 1243 | |
| 1244 | ### #import and #include |
| 1245 | |
| 1246 | `#import` Objective-C and Objective-C++ headers, and `#include` C/C++ headers. |
| 1247 | |
| 1248 | Choose between `#import` and `#include` based on the language of the header that |
| 1249 | you are including. |
| 1250 | |
| 1251 | |
| 1252 | When including a header that uses Objective-C or Objective-C++, use `#import`. |
| 1253 | When including a standard C or C++ header, use `#include`. |
| 1254 | The header should provide its own `#define` guard. |
| 1255 | |
| 1256 | ### Order of Includes |
| 1257 | |
| 1258 | The standard order for header inclusion is the related header, operating system |
| 1259 | headers, language library headers, and finally groups of headers for other |
| 1260 | dependencies. |
| 1261 | |
| 1262 | The related header precedes others to ensure it has no hidden dependencies. |
| 1263 | For implementation files the related header is the header file. |
| 1264 | For test files the related header is the header containing the tested interface. |
| 1265 | |
| 1266 | A blank line may separate logically distinct groups of included headers. |
| 1267 | |
| 1268 | Import headers using their path relative to the project's source directory. |
| 1269 | |
| 1270 | ```objectivec |
| 1271 | // GOOD: |
| 1272 | |
| 1273 | #import "ProjectX/BazViewController.h" |
| 1274 | |
| 1275 | #import <Foundation/Foundation.h> |
| 1276 | |
| 1277 | #include <unistd.h> |
| 1278 | #include <vector> |
| 1279 | |
| 1280 | #include "base/basictypes.h" |
| 1281 | #include "base/integral_types.h" |
| 1282 | #include "util/math/mathutil.h" |
| 1283 | |
| 1284 | #import "ProjectX/BazModel.h" |
| 1285 | #import "Shared/Util/Foo.h" |
| 1286 | ``` |
| 1287 | |
| 1288 | ### Use Umbrella Headers for System Frameworks |
| 1289 | |
| 1290 | Import umbrella headers for system frameworks and system libraries rather than |
| 1291 | include individual files. |
| 1292 | |
| 1293 | While it may seem tempting to include individual system headers from a framework |
| 1294 | such as Cocoa or Foundation, in fact it's less work on the compiler if you |
| 1295 | include the top-level root framework. The root framework is generally |
| 1296 | pre-compiled and can be loaded much more quickly. In addition, remember to use |
| 1297 | `@import` or `#import` rather than `#include` for Objective-C frameworks. |
| 1298 | |
| 1299 | ```objectivec |
| 1300 | // GOOD: |
| 1301 | |
| 1302 | @import UIKit; // GOOD. |
| 1303 | #import <Foundation/Foundation.h> // GOOD. |
| 1304 | ``` |
| 1305 | |
| 1306 | ```objectivec |
| 1307 | // AVOID: |
| 1308 | |
| 1309 | #import <Foundation/NSArray.h> // AVOID. |
| 1310 | #import <Foundation/NSString.h> |
| 1311 | ... |
| 1312 | ``` |
| 1313 | |
Stephane Moore | 4264801 | 2017-10-16 18:11:48 -0700 | [diff] [blame] | 1314 | ### Avoid Messaging the Current Object Within Initializers and `-dealloc` |
Kevin Lindkvist | c5197bf | 2017-07-25 19:21:16 -0700 | [diff] [blame] | 1315 | |
Stephane Moore | 4264801 | 2017-10-16 18:11:48 -0700 | [diff] [blame] | 1316 | Code in initializers and `-dealloc` should avoid invoking instance methods. |
Kevin Lindkvist | c5197bf | 2017-07-25 19:21:16 -0700 | [diff] [blame] | 1317 | |
Stephane Moore | 4264801 | 2017-10-16 18:11:48 -0700 | [diff] [blame] | 1318 | Superclass initialization completes before subclass initialization. Until all |
| 1319 | classes have had a chance to initialize their instance state any method |
| 1320 | invocation on self may lead to a subclass operating on uninitialized instance |
| 1321 | state. |
| 1322 | |
| 1323 | A similar issue exists for `-dealloc`, where a method invocation may cause a |
| 1324 | class to operate on state that has been deallocated. |
| 1325 | |
| 1326 | One case where this is less obvious is property accessors. These can be |
| 1327 | overridden just like any other selector. Whenever practical, directly assign to |
| 1328 | and release ivars in initializers and `-dealloc`, rather than rely on accessors. |
Kevin Lindkvist | c5197bf | 2017-07-25 19:21:16 -0700 | [diff] [blame] | 1329 | |
| 1330 | ```objectivec |
| 1331 | // GOOD: |
| 1332 | |
| 1333 | - (instancetype)init { |
| 1334 | self = [super init]; |
| 1335 | if (self) { |
| 1336 | _bar = 23; // GOOD. |
| 1337 | } |
| 1338 | return self; |
| 1339 | } |
| 1340 | ``` |
| 1341 | |
Stephane Moore | 4264801 | 2017-10-16 18:11:48 -0700 | [diff] [blame] | 1342 | Beware of factoring common initialization code into helper methods: |
| 1343 | |
| 1344 | - Methods can be overridden in subclasses, either deliberately, or |
| 1345 | accidentally due to naming collisions. |
| 1346 | - When editing a helper method, it may not be obvious that the code is being |
| 1347 | run from an initializer. |
| 1348 | |
Kevin Lindkvist | c5197bf | 2017-07-25 19:21:16 -0700 | [diff] [blame] | 1349 | ```objectivec |
| 1350 | // AVOID: |
| 1351 | |
| 1352 | - (instancetype)init { |
| 1353 | self = [super init]; |
| 1354 | if (self) { |
| 1355 | self.bar = 23; // AVOID. |
Stephane Moore | 4264801 | 2017-10-16 18:11:48 -0700 | [diff] [blame] | 1356 | [self sharedMethod]; // AVOID. Fragile to subclassing or future extension. |
Kevin Lindkvist | c5197bf | 2017-07-25 19:21:16 -0700 | [diff] [blame] | 1357 | } |
| 1358 | return self; |
| 1359 | } |
| 1360 | ``` |
| 1361 | |
| 1362 | ```objectivec |
| 1363 | // GOOD: |
| 1364 | |
| 1365 | - (void)dealloc { |
| 1366 | [_notifier removeObserver:self]; // GOOD. |
| 1367 | } |
| 1368 | ``` |
| 1369 | |
| 1370 | ```objectivec |
| 1371 | // AVOID: |
| 1372 | |
| 1373 | - (void)dealloc { |
| 1374 | [self removeNotifications]; // AVOID. |
| 1375 | } |
| 1376 | ``` |
| 1377 | |
| 1378 | ### Setters copy NSStrings |
| 1379 | |
| 1380 | Setters taking an `NSString` should always copy the string it accepts. This is |
| 1381 | often also appropriate for collections like `NSArray` and `NSDictionary`. |
| 1382 | |
| 1383 | Never just retain the string, as it may be a `NSMutableString`. This avoids the |
| 1384 | caller changing it under you without your knowledge. |
| 1385 | |
| 1386 | Code receiving and holding collection objects should also consider that the |
| 1387 | passed collection may be mutable, and thus the collection could be more safely |
| 1388 | held as a copy or mutable copy of the original. |
| 1389 | |
| 1390 | ```objectivec |
| 1391 | // GOOD: |
| 1392 | |
| 1393 | @property(nonatomic, copy) NSString *name; |
| 1394 | |
| 1395 | - (void)setZigfoos:(NSArray<Zigfoo *> *)zigfoos { |
| 1396 | // Ensure that we're holding an immutable collection. |
| 1397 | _zigfoos = [zigfoos copy]; |
| 1398 | } |
| 1399 | ``` |
| 1400 | |
| 1401 | ### Use Lightweight Generics to Document Contained Types |
| 1402 | |
| 1403 | All projects compiling on Xcode 7 or newer versions should make use of the |
| 1404 | Objective-C lightweight generics notation to type contained objects. |
| 1405 | |
| 1406 | Every `NSArray`, `NSDictionary`, or `NSSet` reference should be declared using |
| 1407 | lightweight generics for improved type safety and to explicitly document usage. |
| 1408 | |
| 1409 | ```objectivec |
| 1410 | // GOOD: |
| 1411 | |
| 1412 | @property(nonatomic, copy) NSArray<Location *> *locations; |
| 1413 | @property(nonatomic, copy, readonly) NSSet<NSString *> *identifiers; |
| 1414 | |
| 1415 | NSMutableArray<MyLocation *> *mutableLocations = [otherObject.locations mutableCopy]; |
| 1416 | ``` |
| 1417 | |
| 1418 | If the fully-annotated types become complex, consider using a typedef to |
| 1419 | preserve readability. |
| 1420 | |
| 1421 | ```objectivec |
| 1422 | // GOOD: |
| 1423 | |
| 1424 | typedef NSSet<NSDictionary<NSString *, NSDate *> *> TimeZoneMappingSet; |
| 1425 | TimeZoneMappingSet *timeZoneMappings = [TimeZoneMappingSet setWithObjects:...]; |
| 1426 | ``` |
| 1427 | |
| 1428 | Use the most descriptive common superclass or protocol available. In the most |
| 1429 | generic case when nothing else is known, declare the collection to be explicitly |
| 1430 | heterogenous using id. |
| 1431 | |
| 1432 | ```objectivec |
| 1433 | // GOOD: |
| 1434 | |
| 1435 | @property(nonatomic, copy) NSArray<id> *unknowns; |
| 1436 | ``` |
| 1437 | |
| 1438 | ### Avoid Throwing Exceptions |
| 1439 | |
| 1440 | Don't `@throw` Objective-C exceptions, but you should be prepared to catch them |
| 1441 | from third-party or OS calls. |
| 1442 | |
| 1443 | This follows the recommendation to use error objects for error delivery in |
| 1444 | [Apple's Introduction to Exception Programming Topics for |
| 1445 | Cocoa](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Exceptions/Exceptions.html). |
| 1446 | |
| 1447 | We do compile with `-fobjc-exceptions` (mainly so we get `@synchronized`), but |
| 1448 | we don't `@throw`. Use of `@try`, `@catch`, and `@finally` are allowed when |
| 1449 | required to properly use 3rd party code or libraries. If you do use them, please |
| 1450 | document exactly which methods you expect to throw. |
| 1451 | |
| 1452 | ### `nil` Checks |
| 1453 | |
| 1454 | Use `nil` checks for logic flow only. |
| 1455 | |
| 1456 | Use `nil` pointer checks for logic flow of the application, not for preventing |
| 1457 | crashes when sending messages. Sending a message to `nil` [reliably |
| 1458 | returns](http://www.sealiesoftware.com/blog/archive/2012/2/29/objc_explain_return_value_of_message_to_nil.html) |
| 1459 | `nil` as a pointer, zero as an integer or floating-point value, structs |
| 1460 | initialized to `0`, and `_Complex` values equal to `{0, 0}`. |
| 1461 | |
| 1462 | Note that this applies to `nil` as a message target, not as a parameter value. |
| 1463 | Individual methods may or may not safely handle `nil` parameter values. |
| 1464 | |
| 1465 | Note too that this is distinct from checking C/C++ pointers and block pointers |
| 1466 | against `NULL`, which the runtime does not handle and will cause your |
| 1467 | application to crash. You still need to make sure you do not dereference a |
| 1468 | `NULL` pointer. |
| 1469 | |
| 1470 | ### BOOL Pitfalls |
| 1471 | |
| 1472 | Be careful when converting general integral values to `BOOL`. Avoid comparing |
| 1473 | directly with `YES`. |
| 1474 | |
| 1475 | `BOOL` in OS X and in 32-bit iOS builds is defined as a signed `char`, so it may |
| 1476 | have values other than `YES` (`1`) and `NO` (`0`). Do not cast or convert |
| 1477 | general integral values directly to `BOOL`. |
| 1478 | |
| 1479 | Common mistakes include casting or converting an array's size, a pointer value, |
| 1480 | or the result of a bitwise logic operation to a `BOOL` that could, depending on |
| 1481 | the value of the last byte of the integer value, still result in a `NO` value. |
| 1482 | When converting a general integral value to a `BOOL` use ternary operators to |
| 1483 | return a `YES` or `NO` value. |
| 1484 | |
| 1485 | You can safely interchange and convert `BOOL`, `_Bool` and `bool` (see C++ Std |
Stephane Moore | 4264801 | 2017-10-16 18:11:48 -0700 | [diff] [blame] | 1486 | 4.7.4, 4.12 and C99 Std 6.3.1.2). Use `BOOL` in Objective-C method signatures. |
Kevin Lindkvist | c5197bf | 2017-07-25 19:21:16 -0700 | [diff] [blame] | 1487 | |
| 1488 | Using logical operators (`&&`, `||` and `!`) with `BOOL` is also valid and will |
| 1489 | return values that can be safely converted to `BOOL` without the need for a |
| 1490 | ternary operator. |
| 1491 | |
| 1492 | ```objectivec |
| 1493 | // AVOID: |
| 1494 | |
| 1495 | - (BOOL)isBold { |
| 1496 | return [self fontTraits] & NSFontBoldTrait; // AVOID. |
| 1497 | } |
| 1498 | - (BOOL)isValid { |
| 1499 | return [self stringValue]; // AVOID. |
| 1500 | } |
| 1501 | ``` |
| 1502 | |
| 1503 | ```objectivec |
| 1504 | // GOOD: |
| 1505 | |
| 1506 | - (BOOL)isBold { |
| 1507 | return ([self fontTraits] & NSFontBoldTrait) ? YES : NO; |
| 1508 | } |
| 1509 | - (BOOL)isValid { |
| 1510 | return [self stringValue] != nil; |
| 1511 | } |
| 1512 | - (BOOL)isEnabled { |
| 1513 | return [self isValid] && [self isBold]; |
| 1514 | } |
| 1515 | ``` |
| 1516 | |
| 1517 | Also, don't directly compare `BOOL` variables directly with `YES`. Not only is |
| 1518 | it harder to read for those well-versed in C, but the first point above |
| 1519 | demonstrates that return values may not always be what you expect. |
| 1520 | |
| 1521 | ```objectivec |
| 1522 | // AVOID: |
| 1523 | |
| 1524 | BOOL great = [foo isGreat]; |
| 1525 | if (great == YES) { // AVOID. |
| 1526 | // ...be great! |
| 1527 | } |
| 1528 | ``` |
| 1529 | |
| 1530 | ```objectivec |
| 1531 | // GOOD: |
| 1532 | |
| 1533 | BOOL great = [foo isGreat]; |
| 1534 | if (great) { // GOOD. |
| 1535 | // ...be great! |
| 1536 | } |
| 1537 | ``` |
| 1538 | |
| 1539 | ### Interfaces Without Instance Variables |
| 1540 | |
| 1541 | Omit the empty set of braces on interfaces that do not declare any instance |
| 1542 | variables. |
| 1543 | |
| 1544 | ```objectivec |
| 1545 | // GOOD: |
| 1546 | |
| 1547 | @interface MyClass : NSObject |
| 1548 | // Does a lot of stuff. |
| 1549 | - (void)fooBarBam; |
| 1550 | @end |
| 1551 | ``` |
| 1552 | |
| 1553 | ```objectivec |
| 1554 | // AVOID: |
| 1555 | |
| 1556 | @interface MyClass : NSObject { |
| 1557 | } |
| 1558 | // Does a lot of stuff. |
| 1559 | - (void)fooBarBam; |
| 1560 | @end |
| 1561 | ``` |
| 1562 | |
| 1563 | ## Cocoa Patterns |
| 1564 | |
| 1565 | ### Delegate Pattern |
| 1566 | |
| 1567 | Delegates, target objects, and block pointers should not be retained when doing |
| 1568 | so would create a retain cycle. |
| 1569 | |
| 1570 | To avoid causing a retain cycle, a delegate or target pointer should be released |
| 1571 | as soon as it is clear there will no longer be a need to message the object. |
| 1572 | |
| 1573 | If there is no clear time at which the delegate or target pointer is no longer |
| 1574 | needed, the pointer should only be retained weakly. |
| 1575 | |
| 1576 | Block pointers cannot be retained weakly. To avoid causing retain cycles in the |
| 1577 | client code, block pointers should be used for callbacks only where they can be |
| 1578 | explicitly released after they have been called or once they are no longer |
| 1579 | needed. Otherwise, callbacks should be done via weak delegate or target |
| 1580 | pointers. |
| 1581 | |
| 1582 | ## Objective-C++ |
| 1583 | |
| 1584 | ### Style Matches the Language |
| 1585 | |
| 1586 | Within an Objective-C++ source file, follow the style for the language of the |
| 1587 | function or method you're implementing. In order to minimize clashes between the |
| 1588 | differing naming styles when mixing Cocoa/Objective-C and C++, follow the style |
| 1589 | of the method being implemented. |
| 1590 | |
| 1591 | For code in an `@implementation` block, use the Objective-C naming rules. For |
| 1592 | code in a method of a C++ class, use the C++ naming rules. |
| 1593 | |
| 1594 | For code in an Objective-C++ file outside of a class implementation, be |
| 1595 | consistent within the file. |
| 1596 | |
| 1597 | ```objectivec++ |
| 1598 | // GOOD: |
| 1599 | |
| 1600 | // file: cross_platform_header.h |
| 1601 | |
| 1602 | class CrossPlatformAPI { |
| 1603 | public: |
| 1604 | ... |
| 1605 | int DoSomethingPlatformSpecific(); // impl on each platform |
| 1606 | private: |
| 1607 | int an_instance_var_; |
| 1608 | }; |
| 1609 | |
| 1610 | // file: mac_implementation.mm |
| 1611 | #include "cross_platform_header.h" |
| 1612 | |
| 1613 | // A typical Objective-C class, using Objective-C naming. |
| 1614 | @interface MyDelegate : NSObject { |
| 1615 | @private |
| 1616 | int _instanceVar; |
| 1617 | CrossPlatformAPI* _backEndObject; |
| 1618 | } |
| 1619 | |
| 1620 | - (void)respondToSomething:(id)something; |
| 1621 | |
| 1622 | @end |
| 1623 | |
| 1624 | @implementation MyDelegate |
| 1625 | |
| 1626 | - (void)respondToSomething:(id)something { |
| 1627 | // bridge from Cocoa through our C++ backend |
| 1628 | _instanceVar = _backEndObject->DoSomethingPlatformSpecific(); |
| 1629 | NSString* tempString = [NSString stringWithFormat:@"%d", _instanceVar]; |
| 1630 | NSLog(@"%@", tempString); |
| 1631 | } |
| 1632 | |
| 1633 | @end |
| 1634 | |
| 1635 | // The platform-specific implementation of the C++ class, using |
| 1636 | // C++ naming. |
| 1637 | int CrossPlatformAPI::DoSomethingPlatformSpecific() { |
| 1638 | NSString* temp_string = [NSString stringWithFormat:@"%d", an_instance_var_]; |
| 1639 | NSLog(@"%@", temp_string); |
| 1640 | return [temp_string intValue]; |
| 1641 | } |
| 1642 | ``` |
| 1643 | |
| 1644 | Projects may opt to use an 80 column line length limit for consistency with |
| 1645 | Google's C++ style guide. |
| 1646 | |
| 1647 | ## Objective-C Style Exceptions |
| 1648 | |
| 1649 | ### Indicating style exceptions |
| 1650 | |
| 1651 | Lines of code that are not expected to adhere to these style recommendations |
| 1652 | require `// NOLINT` at the end of the line or `// NOLINTNEXTLINE` at the end of |
| 1653 | the previous line. Sometimes it is required that parts of Objective-C code must |
| 1654 | ignore these style recommendations (for example code may be machine generated or |
| 1655 | code constructs are such that its not possible to style correctly). |
| 1656 | |
| 1657 | A `// NOLINT` comment on that line or `// NOLINTNEXTLINE` on the previous line |
| 1658 | can be used to indicate to the reader that code is intentionally ignoring style |
| 1659 | guidelines. In addition these annotations can also be picked up by automated |
| 1660 | tools such as linters and handle code correctly. Note that there is a single |
| 1661 | space between `//` and `NOLINT*`. |