_iVar vs. iVar_ for variable naming [closed]

久未见 提交于 2019-12-11 02:42:37

问题


I used to use prefix underscore for instance variable naming, to distinguish from local variables.

I happend to see the "Google Objective-C Style Guide", and found that it suggests to use trailing underscores(refer it HERE), but without any detail explanation about why.

I know it is a coding style issue, but I do wonder is there any advantages of using trailing underscores?


回答1:


Related: Question about @synthesize (see the blockquotes at the bottom of the answer)
The advantage is: _var is a convention (C99, Cocoa guidelines) for private, but it is so common (even on Apple templates) that Apple uses double underscore __var. Google solves it by using trailing underscore instead.

I updated the other answer with a couple more reasons...

Leading underscore is also discouraged in C++ (see What are the rules about using an underscore in a C++ identifier?) and Core Data properties (try adding a leading underscore in the model and you'll get "Name must begin with a letter").

Trailing underscore seems the sensible choice, but if you like something else, collisions are unlikely to happen, and if they do, you'll get a warning from the compiler.




回答2:


The prefix underscore usually is used in system / SDK libraries. So using prefix underscore may cause overridden of variable in super class and a bug like this is not so easy to found. Take a look at any class provided by system, like NSView, and you will find that.




回答3:


Apple uses single leading underscore for ivars so that their variable names won't collide with ours. When you name your ivars, use anything but a single leading underscore.




回答4:


There is no advantage as such using trailing underscores. We follow the coding style so that it eases the code readability. Underscore, in this case helps us differentiate between iVars and local variables. As far as i know, _iVar is more prominent than iVar_




回答5:


Almost all programming languages based on english, where we write and read from left to right.
Using leading underscores makes easier finding iVars, and recognition that a variable is iVar.



来源:https://stackoverflow.com/questions/8832091/ivar-vs-ivar-for-variable-naming

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!