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