8

In Google's Objective-C Style guide which is follow by many people , Google says

Class member variables have trailing underscores

Why? Is there any good reason for doing this? I found apple usually name an ivar when beginning underscore.

Jimmy
  • 1,094
  • 10
  • 22
  • One possible reasoning is that instance variable names won’t ever collide with Apple’s. I don’t find this much of a problem since the compiler will give an error in that case, and refactoring tools make it easy to rename instance variables if that happens. –  Apr 12 '11 at 01:44
  • +1 because I didn't know Google had an Objective-C style guide. – Eric Brotto Sep 09 '11 at 09:13

4 Answers4

26

I prefer trailing underscores because if I have:

int test_;

I can type 't' and it will appear in the code completion immediately.

With

int _test;

I have to type '_t' to get to the T's in code completion.

Whether that's true or not, not sure, but that's what I've convinced myself of.

MarkPowell
  • 16,482
  • 7
  • 61
  • 77
  • 11
    I like the complete opposite, with an underscore as the first character I can type "_" and get a completion list for all private variables – drewag Apr 12 '11 at 04:44
  • I prefer the underscore at the beginning also but it's nice to have an understanding of why some developers have chosen a trailing underscore instead. – Matt Browne Apr 04 '13 at 18:55
  • 1
    I also prefer prefixed underscoring my ivars. The reason is, that you should prefer using a property instead of the actual underlaying ivar. It has lots of advantages such as KVO out of the box and atomic synchronization. The compiler will know when to optimize and access the ivar directly. Prefixing ivars prevent me from accidentally use the ivar instead of the property. – Trenskow Jan 20 '15 at 13:38
5

Heavy users of Core Data will have also noticed that Core Data attributes cannot begin with non-alpha characters. If you want to name ivars consistently across your app and various projects, this is another reason to append, rather than prepend, your ivars with an underscore.

If you're not using Core Data a lot, or you don't have OCD tendencies towards consistency in naming conventions, then whatever works best for you is probably the right answer.

prairiedogg
  • 6,323
  • 8
  • 44
  • 52
2

This could be a carry-over of from their C++ style guide. In C++, leading underscores are reserved.

Their naming convention for objective-c ivars is consistent with c++ private member variables.

Community
  • 1
  • 1
Emile Cormier
  • 28,391
  • 15
  • 94
  • 122
1

It's simply their preferred style. The underscore, whether prefixed or suffixed, represents that it is a private ivar and not a property or public ivar.

FreeAsInBeer
  • 12,937
  • 5
  • 50
  • 82