Naming convention in Objective C /C , start with "_"? - c

Something I see ppl define the variable like this:
b2World *_world;
b2Body *_body;
CCSprite *_ball;
instead of
b2World *world;
b2Body *body;
CCSprite *ball;
I familiar with the second one, but not the first one. So, I checked the Wikipedia about naming convention:
Names beginning with double underscore
or an underscore and a capital letter
are reserved for implementation
(compiler, standard library) and
should not be used (e.g. __reserved or
_Reserved).
So, is that any special meaning which is start with "_"?
The code I saw which using "_" to begin is here:
http://www.raywenderlich.com/457/intro-to-box2d-with-cocos2d-tutorial-bouncing-balls
The wiki page.

There's a long-standing convention among some Objective-C developers to prefix instance variables with an underscore. It can be helpful in several ways: one, it makes it easier to spot instance variables in a .m file; two, it relieves developers of having to come up with creative names for method parameters to avoid colliding with instance variable names; and three, as others have noted, it indicates that the instance variables are private, and therefore shouldn't be accessed willy nilly throughout the code.
In fact, I'd argue for avoiding accessing instance variables directly in methods other than accessors (getters and setters), -dealloc, and -init.... Not that you should never, ever use them anywhere else, but you should at least give it some thought before using an instance variable directly in other methods.

It's really really helpful, but most people don't know why, and that's a shame.
Apple uses underscores to separate the way other objects access a particular object's variables, and the way a particular object access its own variables.
Now this may sound a little bit strange, but imagine the following: You probably all recognize the following compiler warning
.h
#property (nonatomic, retain, readonly) UITableView *tableView;
.m
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [self loadSomethingElseForTableView:tableView];
}
This will result in a compiler warning, because it does not know wether you reference to the local variable "tableView", or the instance variable.
Therefore, Apple recommends you to add the following to the top of your #implementation.
#synthesize tableView = _tableView;
Now, when you reference to _tableView, the compiler knows that you mean the instance variable, and not the local one.
Also, this makes it a lot easier to understand the Garbage Collection in Obj-C, and to prevent making common mistakes.
For example, when doing the following:
#property (nonatomic, retain, readonly) NSString *title;
- (id)initWithTitle:(NSString *)title {
if ((self = [super init])) {
self.title = title; // Is not possible, since it's read only.
title = title; // Is not possible, since it's the same (local) variable.
// Changing the method to initWithTitle:(NSString *)aTitle;
title = aTitle;
}
return self;
}
Now, since you do not use the default setter (actually, you can't, because it's read-only) you need to retain the variable yourself.
This is a lot easier to remember when you give every instance variable a prefix (so you know you need to retain it yourself).
So, basically, it's important to understand the difference between self.variable and (_)variable. (that is: self.variable maps to [self setVariable:...] and variable maps directly to your pointer.
Furthermore, when you add it as a private variable, like this:
#interface TSSomeObject : NSObject {
#private
NSString *_privateTitle;
}
#end
The underscore prefix isn't really necessary, unless you may encounter local variables that have the same name. Besides that, again, it's also an easy way to remind you that it's a local pointer and that you need to retain (and release) the variable when you assign it to your object.
What is wrong is to create a property with a underscore prefix, like this:
#property (nonatomic, retain) NSString *_title;
That's really wrong, and I'm not even gonna explain why ;)
So yes! You should really use underscore prefixes, it makes your code a lot easier to read, and to interpret by the compiler! In Xcode 4, Apple even added these #synthesizes to the default templates.

Usually they're used for variables that shouldn't be accessed outside the current file/module/namespace/whatever, in languages that don't support restricting access with something like a private keyword

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingIvarsAndTypes.html#//apple_ref/doc/uid/20001284-1001757
Both by convention and recommendation in the above document, you should prefix ivars with an underscore.
Admittedly, it is in reference to explicitly set ivars for properties.
But the usage is the same, to indicate the usage of an ivar wherever it is seen.
I am however open to the possibility, that in that context, the use of an underscore prefixed ivar could signal to the user that they are doing something wrong. Meanwhile a postfixed underscore could be used for pure ivars that are meant to be accessed directly.
This blog has some good thoughts from an experienced practitioner and it recommends using prefixed underscores.
http://blog.bignerdranch.com/463-a-motivation-for-ivar-decorations/
Wether you choose to use prefixed underscores to decorate your own ivars, there is at least some evidence that some kind of decoration will help you avoid bugs. And prefix'd underscores are the most common decoration.

Apple reserves names beginning with underscore for its own private ivars and methods. In Objective-C on any Apple platform, it is recommended that you do not prefix your identifiers with an underscore.
http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingMethods.html

Related

Adding an optional "global" keyword to lua 5.2 source

I'd like to modify the lua 5.2 source code to allow for an optional "global" keyword to precede global variable declarations. Has any done this or does anyone know how to do this (safely)? And yes I am aware that variables are global by default and that this would be purely syntactic sugar.
To be clear, adding custom keywords of existing types is straight forward. The part I'm at a loss for is how to safely edit the parser (via the 5.2 C source code) so that it discards or ignores the new "global" keyword.
Figured it out. First I appended a new token TK_GLOBAL to the end of the RESERVED enum.
Then in luaX_init() I added...
ts = luaS_new(L, "global");
luaS_fix(ts);
ts->tsv.reserved = cast_byte(TK_GLOBAL+1-FIRST_RESERVED);
And finally in the statement() function I added...
case TK_GLOBAL:
luaX_next(ls);
break;
As far as I can tell it works. Hopefully it's safe.
See this discussion for details and a proposed patch (against 5.3): http://lua-users.org/lists/lua-l/2018-07/msg00422.html. It uses a different (non-keyword based) approach, but should be a good starting point.

Whys is it a bad idea to have an Object[] array?

I was explaining to a friend a few days ago the concept or inheritance and containers.
He has very little programming knowledge so it was really just a friendly chat.
During the conversation he came to me with a question that i just couldn't answer.
"Why cant you just have an array of the top level class, and add anything to it"
I know this is a bad idea having being told so before by someone far smarter but for the life of me i couldn't remember why.
I mean we do it all the time with inheritance.
Say we have class animal which is parent of cat and dog. If we need a container of both of these we make the array of type animal.
So lets say we didn't have that inheritance link, couldn't we just use the base object class and have everything in the one container.
No specific programming language.
Syntactically, there is no problem with this. By declaring an array of a specific type, you are giving implicit information about the contents of that array. You could well declare a contain of Object instances, but it means you lose all the type information of the original class at compile-time.
It also means that each time you get an object out of the array at runtime, the only field instances and methods you know exist are the fields/methods of Object (which arguably is a compile time problem). To use any of the fields and methods of more specific subclasses of the object, you'd have to cast.
Alternatively, to find out the specific class at runtime you'd have to use features like reflection which are overkill for the majority of cases.
When you take elements out of the container you want to have some guarantees as to what can be done with them. If all elements of the container are returned as instances of Animal (remember here that instances of Dog are also instances of Animal) then you know that they can do all the things that Animals can do (which is more things than what all Objects can do).
Maybe, we do it in programming for the same reason as in Biology? Reptiles and Whales are animals, but they are quite different.
It depends on the situation, but without context, it's definitely okay in most (if not all) object-oriented languages to have an array of a base type (that is, as long as they follow all the substitution principles) containing various instances of different derived types.
Object arrays exist in certain cases in most languages. The problem is that whenever you want to use them, you need to remember what type they were, and stay casting them or whatever.
It also makes the code very horrible to follow and even more horrible to extend, not to mention error prone.
Plant myplant = new Plant();
listOfAnimals.Add(myplant);
would work if the list is object, but you'd get a compile time error if it was Animal.

Define private function in a mathematica package

I'm not sure I got how to define private functions right.
When I'm writing a package mathematica, I just do this:
BeginPackage["myPackage`"]
myPublicFunction::usage="myPublicFunction blahblahblah";
Begin["Private"]
myPrivateFunction[input_]:= ... ;
myPublicFunction[input_]:= ... ;
End[]
EndPackage[]
Is this the correct way or am I missing something?
Yep, that's a correct way. It may pay off to understand some of the internal package mechanics. Mathematica contexts are similar to namespaces in other languages. They can be nested. Every symbol belongs to some context. At any given moment, some context is "current". Whenever a new symbol is created, the system must decide to which context the symbol will belong. This happens at parse-time. The fundamental quantity (variable) here is $ContextPath. It is basically the search path for symbols. It is a list of contexts, and whenever the system sees a new symbol, it tests if the symbol with the same short name (that is, the name of the symbol proper, without the context) exists in some context on the $ContextPath. If it does exist, then the given occurrence of the symbol will be associated with that existing one. If it does not, then the symbol is created in a current context. Note that this is a dynamic thing - if you change the $ContextPath at any moment, the next symbol occurrence can be associated with a different symbol.
Anyways, what BeginPackage does is that it simply replaces the current value of $ContextPath with just {youPublicPackageContext, "System'"}, plus possibly additional contexts that you publicly import through the second optional argument of BeginPackage. Therefore, all symbols that are in the "public" section, are parsed into the public context, if they are not in "System'" or other contexts that you import. And what EndPackage does is to restore the value of the $ContextPath to what it was before you started loading the package. So, technically the usage message is not the only way to make a symbol public in your main context - you could just as well simply type a symbol with a semicolon, like myFunction; (this practice is discouraged, I just mentioned it to clarify the mechanism). Now, what happens when you enter Begin["'Private'"] is that the current context becomes YourContext'Private' (a sub-context). The $ContextPath is not changed. Therefore, any symbol entered there, which does not exist in your public package or other imported packages (that is, contexts currently on the $ContextPath), automatically is parsed into the 'Private' subcontext.
What really makes these symbols private is that whenever you import your package into some other context (package), only the main package is added to the $ContextPath, but not its sub-packages. Technically, you can break encapsulation by manually adding YourPackage'Private' to the $ContextPath (say, PrependTo[$ContextPath, YourPackage'Private']), and then all your private functions and other symbols will become public in that particular context where you do the import. Again, this practice is discouraged, but it explains the mechanics. The bottom line is that the notion of private or public can be entirely understood when we know how symbols are parsed, and what are the manipulations with $ContextPath and $Context (another system variable giving the value of the current context), that are performed by commands such as Begin and BeginPackage. To put it another way, one could, in principle, emulate the actions of BeginPackage,Begin, End and EndPackage with a user-defined code. There are just a few principles operating here (which I tried to outline above), and the mechanism itself is in fact very much exposed to the user, so that if, in some rare cases, one may want some other behavior, one can make some "custom" manipulations with $ContextPath and Context, to ensure some non-standard way of symbol parsing and therefore, control package-scale encapsulation in some "non-standard" way. I am not encouraging this, just mentioning to emphasize that the mechanism is in fact much simpler and much more controllable than it may seem on the surface.

A std::tr1::shared_ptr for Objective C++ on iPhone?

I am mostly a C++ developer, recently I am writing iPhone applications.
The memory management on iPhone is OK to me, due to resource limitation, it's encouraged to use reference counters rather than deep copy.
One annoying thing is I have to manage the reference counters by myself: alloc means counter = 1; retain means counter++, release means counter--
I wish to write a shared_ptr like class for Cocoa Touch, so I rarely have to manually manipulate the reference counters by myself.
I doubt if there's any existing code for that, and I'd like to hear some advices, today is the 5th day since I started to learn objective c
Thanks.
As long as you learn the memory management rules first, there is no real problem with shared_ptr - it can help you in C++ contexts but doesn't let the ownership questions magically disappear.
shared_ptr supports a custom deallocator so the following:
#interface A : NSObject
- (void)f;
#end
#implementation A
- (void)dealloc { NSLog(#"bye"); [super dealloc]; }
- (void)f { NSLog(#"moo"); }
#end
void my_dealloc(id p) {
[p release];
}
// ...
{
shared_ptr<A> p([[A alloc] init], my_dealloc);
[p.get() f];
}
... outputs:
moo
bye
... as expected.
If you want you can hide the deallocator from the user using a helper function, e.g.:
template<class T> shared_ptr<T> make_objc_ptr(T* t) {
return shared_ptr<T>(t, my_dealloc);
}
shared_ptr<A> p = make_objc_ptr<A>([[A alloc] init]);
You forgot case 4
[4] you need to pass a pointer to an object out of a method as the return value.
This is where you need -autorelease.
I suggest you read the memory management rules and write some real code before you attempt this little project so that you can get a feel of how memory management is supposed to work.
Automatic reference counting, coming in iOS 5, will effectively make any pointer to an objective-c object act like a smart pointer. Retain/release calls will be synthesized by the compiler on assign and deallocation, unless you explicitly declare a reference to be weak, in which case they'll be automatically zeroed out when the object is deallocated.
My advice is to wait a couple of months for that. You might be able to put together something similar in the meantime, but I'd recommend against it. For one thing, it'll be ugly. Example:
smart_ptr<id> array = make_smart_ptr( [NSMutableArray array] );
NSUInteger count = [array count]; // won't work.
count = [array.get() count]; // works, but yuck.
[array.get() setArray: anotherArray.get()]; // even more yuck.
Also, if your headers are full of c++ classes, you'll have to compile your entire project in objective-c++, which may cause you problems as objective-c++ isn't 100% compatible with objective-c code, and not all third-party frameworks will work properly with it. And forget about sharing your code with anyone else.
It might be an interesting excercise to make something like this work, but you won't want to actually use it. And watch out for the temptation to recreate your favourite bits of C++ in Objective-C. The languages are very different, and you could spend a lot of time doing that, which is time not spent learning all the great stuff you can do in Objective-C that you can't do in C++.
Resource management in Cocoa can be tricky: some API calls automatically retain a reference and some don't, some return an autoreleased object, some a retained object. By shielding this in a shared_ptr class, you'll more likely to make mistakes. My advice is to first take the "normal" Cocoa route until you're fairly experienced.
Have you looked into [object autorelease]? Perhaps that would make things a bit easier.

How to name variables which are structs

i often work on private projects using the WinApi, and as you might know, it has thousands of named and typedefed structs like MEMORY_BASIC_INFORMATION.
I will stick to this one in my question, what still is preferred, or better when you want to name a variable of this type. Is there some kind of style guide for this case?
For example if i need that variable for the VirtualQueryEx function.
Some ideas:
MEMORY_BASIC_INFORMATION memoryBasicInformation;
MEMORY_BASIC_INFORMATION memory_basic_information;
Just use the name of the struct non capitalized and with or without the underlines.
MEMORY_BASIC_INFORMATION basicInformation;
MEMORY_BASIC_INFORMATION information;
Short form?
MEMORY_BASIC_INFORMATION mbi;
I often see this style, using the abbreviation of the struct name.
MEMORY_BASIC_INFORMATION buffer;
VirtualQueryEx defines the third parameter lpBuffer (where you pass the pointer to the struct), so using this name might be an idea, too.
Cheers
In general, it's discouraged to name variables based on their type. Instead, try to provide additional information about the specific context and purpose of the usage.
Using the MEMORY_BASIC_INFORMATION example, consider what the context is of the structure. Are you using the information to iterate over a number of such information structures? Then maybe
MEMORY_BASIC_INFORMATION currentFrame;
Or if you're performing a test on the memory info for some status, maybe it's a candidate.
MEMORY_BASIC_INFORMATION candidate;
Now you can write documentation like "test candidate structure for ...".
You may find that you still want to include type information using the type prefix location. If this is the case, you might call it mbiCurrentFrame or mbiCandidate.
If the purpose or context is truly abstract, such as is the case with the API functions themselves, I would chose something simple and direct, such as info or buffer, except in the case where those names could somehow be misinterpreted in the context.
I think it depends upon a number of issues, and you just have to find the best balance when striving for readability.
Window width
Variables/types of similar names used in the routine.
That being said, if I can get away with it, I would probably use ...
MEMORY_BASIC_INFORMATION info;
If there were other similar types or variable names, then I would add some sort of descriptive modifier such as ...
MEMORY_BASIC_INFORMATION memBasicInfo;
Or, if window real-estate was limited (some projects I have worked on have insisted upon 80 char line maximum), I could go for ...
MEMORY_BASIC_INFORMATION mbi;
But to make it as readable as possible, I try to be consistent--and that I think is one of the most important things to keep in mind.
A little all over the place, but I hope it helps.
Try and keep the case and acronym of the typedef, e.g.
MEMORY_BASIC_INFORMATION MBI_temp
I deal with a lot of code that is and must remain portable across Linux and Windows, this was also a problem for us.
You could also do it in camel case:
MEMORY_BASIC_INFORMATION MBITemp
.. but that doesn't seem as self explanatory.
The point is, anyone familiar with those structures should recognize them as what they are rather quickly. Just be sure not to tromp on another namespace.
The key is, just be consistent in each tree that you work on. Its really only a noticeable issue in two cases:
Globals
Mile long functions
If you have functions so long that you have to scroll up five pages to the declarations just to see what a variable is, there's larger problems to deal with than variable nomenclature :)
Annoyingly, this might introduce some weirdness due to syntax highlighting picking it up as a constant, but that's also the case for the underlying typedef.

Resources