What are your naming conventions for Objective-C "private" methods? - objective-c

Inheriting code from other developers has made me a firm believer in keeping as many messages as possible out of a class' public interface by means of a Class Extension. I'm also a firm believer in adopting special naming conventions for private, implementation-specific members of a class. I really like being able to tell at a glance what messages being sent and what members being referenced within the implementation context are not ever intended for public use and vice versa. If nothing else, it makes the overall semantics of a class easier for me grasp more quickly, and that's worth it.
Justification aside, I've written boatloads of classes with boatloads2 of private methods, but I've never really come up with a pattern for naming that I really love (like I do the controversial ivar_ convention for ivars). Notable examples:
#interface myClass()
// I like this, but as we all know, Apple has dibs on this one,
// and method name collisions are nasty.
- (void)_myPrivateMessage;
// The suffix version promoted by Google for ivars doesn't really translate
// well to method names in Objective-C, because of the way the method
// signature can be broken into several parts.
- (void)doWork_; // That's okay...
- (void)doWork_:(id)work with_:(id)something; // That's just ugly and tedious...
- (void)doWork_:(id)work with_:(id)something and_:(id)another; // My eyes...
// This version is suggested by Apple, and has the benefit of being officially
// recommended. Alas, I don't like it: The capital letter is ugly. I don't like
// underscores in the middle of the name. Worst of all, I have to type three characters
// before code-sense does anything more useful than inform me that I am typing.
- (void)BF_doWork;
#end
At this point, there are a kajillion different means by which I could mangle my private method names, but instead of making something up, I figured I would first take a poll for any popular conventions I may not be aware of. So, what have you used?

I don't distinguish private methods by name. Instead, I keep them out of the public interface by declaring them in the class extension portion of the .m file, thus:
#interface MyClass ()
- (void)doWork;
#end

I use double underscore for my private methods:
- (void)__doSomethingPrivate;
It almost looks like the single underscore-syntax (good readable) and at the same time confirms to the Apple guides.

I use a prefix, no underscore. The prefix is generally related to the name of the project in question. If you do use underscores, there's no need to have more than one.

I use two levels of private methods: slightly private and very private. Slightly private methods are methods which could become public, but currently aren't. They are usually convenience methods that I use internally, and I usually don't put in as much protection unless I decide to make it public. For very private methods, I ignore apple and use an underscore prefix. Since 99% of my code is in classes I create and I usually have prefixes on my class names, the chances of running into naming problems is small. When adding code to classes I didn't make, I rarely make private methods, but add a short prefix on the rare occasion that I do.

I prefix private methods with a 'p':
(void) pDoWork;
(void) pDoWork:(id)work with:(id)something;
Similarly, I use 's' for static (or class) methods:
(Universe*)sGet; // used to return singleton Universe object.
Beyond naming conventions, I declare private methods in .m files instead of .h files.

Using a fixed prefix will help to "hide" the method from the outside world but it won't prevent a method from being accidentally overridden. E.g. I once extended a class and I made a method:
- (void)private_close
{
// ...
}
The result was that the behavior of the class broke in horrible ways. But why? It turned out, the super class also had a method name private_close and I was accidentally overriding it without calling super! How should I know? No compiler warning!
No matter if your prefix is _ or __ or p or private_, if it is always the same, you will end up with problems like this one.
So I prefix private methods (and properties!) with a prefix that resembles the class name. Therefor I take the upper case letters of the class name to form the "private prefix":
ComplexFileParser -> CFP
URLDownloadTask -> URLDT
SessionController -> SC
This is still not perfectly safe, yet it is very unlikely that a subclass with a different name has the same still the same private prefix.
Also when you do frameworks, you should prefix all classes and other symbols with a framework prefix (as Apple does with NS..., CF..., CA..., SC..., UI..., etc.) and thus this class prefix is part of the private prefix as well making collisions even less likely:
Framework DecodingUtils.framework -> DU
Class ComplexFileDecoder in framework -> DUComplexFileDecoder
Private Prefix -> DUCFD
Private Method close -> - (void)DUCFD_close
Alternatively append the prefix at the end of the fist method argument name, to get better auto-completion:
- (void)doSomethingWith:(Type1)var1 parameters:(Type2)var2
will become
- (void)doSomethingWith_DUCFD:(Type1)var1 parameters:(Type2)var2
or always only append it to the last parameter name:
- (void)doSomethingWith:(Type1)var1 parameters_DUCFD:(Type2)var2
or (now it gets really crazy) - add a fake dummy parameter just for naming:
- (void)doSomethingWith:(Type1)var1 parameters:(Type2)var2 DUCFD:(id)x
where x is actually never used in the method and you pass nil for it:
[self doSomethingWith:var1 parameters:var2 DUCFD:nil];
and as it will always be the same at the end, use a pre-processor macro:
#define priv DUCFD:nil
#define PRIVATE DUCFD:nil
// ...
[self doSomethingWith:var1 parameters:var2 priv];
[self doSomethingWith:var1 parameters:var2 PRIVATE];
Prefix and suffixing works also with properties (and thus their ivar, getter/setter methods), the preproessor trick above won't, of course.

Regarding Apple recommendations. You might be interested in how Apple writes it's own code.
If you check private APIs you will see that they use underscores for private methods everywhere. Every peace of Obj-C code in iOS uses them. And in many cases those methods go through multiple iOS versions without refactoring or renaming which means it's not a temporary solution for them but rather a convention. In fact, there're three levels of private methods they use extensively - no underscore, single and double underscore.
As for other solutions like "private", class or project name prefixes - they don't use them at all. Just underscores.

Related

What is the naming convention for methods you know will appear in a later SDK?

I realize that there is some subjectivity in the question, but considering that Apple development is pretty opinionated about naming conventions I want to do this in the way that others will understand what my coding is doing. I am trying to ask the question in the most generic way, But I'll add some of my specific details in the comments in case it affects your answer.
Let's say that I am supporting both iOS 6 and iOS 7. There is a new method on an existing class that only exists in the iOS 7 SDK. Assume that implementing the functionality in a way that is "good enough" for my app is fairly straightforward. But, of course, I'd rather use the SDK version as it is likely to be better supported, more efficient, and better handle edge cases.
As documented in this Q&A it is straightforward to handle this situation.
if ([myInstance respondsToSelector:#selector(newSelector)]) {
//Use the SDK method
} else {
//Use my "good enough" implementation.
}
But I don't want to litter my code with a whole bunch of conditional invocations. It seems that it would be better to encapsulate this dynamic method selection. (Especially in my case, where the method hasn't actually shipped yet and the name/signature might change.)
My instinct is to add a class category that implements both my functionality as well as a wrapper method that implements this dynamic selection of method.
Is this the right approach? If so, what naming conventions should I use? (I obviously can't name my method the same as the iOS7 method or there would be naming collisions.)
My gut reaction is to call my wrapper method safeNewSelector and my implementation a private method called lwNewSelector (where lw is my standard class prefix). But I'd much rather use something that would be considered a standard naming convention.
My instinct is to add a class category that implements both my functionality as well as a wrapper method that implements this dynamic selection of method.
That sounds right. The naming convention for category methods is a lowercase prefix, plus underscore. So, if you are shadowing a method called doSomething:withAwesome:, you would name your category method ogr_doSomething:withAwesome: (assuming you use OGR as your common prefix).
You really must prefix category methods. If two categories implement the same method, it is undefined behavior which will be run. You will not get a compile-time or runtime error. You'll just get undefined behavior. (And Apple can, and does, implement "core" functionality in categories, and you cannot easily detect that they've done so.)
Go for a category and chose a name that is pretty unique, for example prefixed by some company/project specific prefix. Let's say the method in iOS 7 is going to be called funky and you chose the prefix foo. Then you'd do:
#implementation SomeClass(FooCategory)
- (void)foo_funky
{
if ([self respondsToSelector:#selector(funky)]) {
[self funky];
} else {
// Implementation of workaround.
}
}
#end
Now, every time you'd call foo_funky that decision needs to be made. Pretty inefficient. It just occurred to me that Objective-C can make that more efficient by messing with the runtime, kind of like method-swizzling (following code is untested):
#implementation SomeClass(FooCategory)
- (void)foo_funky
{
// Empty implementation, it will be replaced.
}
- (void)foo_myFunkyImplementation
{
// Workaround implementation in case the iOS 7 version is missing.
}
+ (void)load
{
Method realMethod, dummyMethod;
realMethod = class_getInstanceMethod(self, #selector(funky));
if (!realMethod) {
// iOS7 method not available, use my version.
realMethod = class_getInstanceMethod(self, #selector(foo_myFunkyImplementation));
}
// Get the method that should be replaced.
dummyMethod = class_getInstanceMethod(self, #selector(foo_funky));
// Overwrite the dummy implementation with the real implementation.
method_setImplementation(dummyMethod, method_getImplementation(realMethod));
}
#end
This way every time you call foo_funky the correct method is called without the overhead of responds-to-selector-and-then-call-other-method.
You could also use the runtime class modifications to add your implementation using the official name when it's not available, but I don't recommend that. It's better when you can tell by the method name that it might not be the version you're expecting.
It is a fair question indeed and I think many Objective-C debs have run into this situation.
I have used the approach that you suggest, using a class category, in several places myself. As for the naming, in most cases I put a little extra functionality into my category method, so my method names most of the time take another argument – in most cases a simple animated:(BOOL)animated added to the end of the "official" method name.
Yes, there's a risk of clashing with future SDK releases, but I wouldn't worry too much about it, Xcode's refactoring works reasonably well and you'll get a linker warning when category methods conflict.
Edit:
As Rob points out, using that naming convention is probably a good idea.

Is there any way to mark up a c function or obj-c method to identify it at runtime?

I'm looking for something similar to attributes in Java, to use in an objective-c environment.
Suppose I have an implementation file with a bunch of methods defined. Is there any way I can mark them up such that I could find them with introspection at runtime? Something like;
##special_method
- (void)foo
{
}
##special_method
- (void)bar
{
}
// Not special
- (void)baz
{
}
As far as I know, nothing exists, and so the best idea I have is to prefix the method name with something common:
- (void)_special_foo
{
}
- (void)_special_bar
{
}
// Not special
- (void)baz
{
}
any other interesting ideas?
I'm not sure if I understand your question correctly, but as an "interesting" possible solution, you can use a global variable that is set to a unique value identifying a specific function on entry (and optionally resetting on exit), or you can use a stack to trace these values that you can inspect at any time.
Apple's suggestion to identify private methods is to give a unique prefix:
Names of most private methods in the Cocoa frameworks have an
underscore prefix (for example, _fooData) to mark them as private.
From this fact follow two recommendations.
Don’t use the underscore character as a prefix for your private
methods. Apple reserves this convention.
If you are subclassing a
large Cocoa framework class (such as NSView or UIView) and you want to
be absolutely sure that your private methods have names different from
those in the superclass, you can add your own prefix to your private
methods. The prefix should be as unique as possible, perhaps one based
on your company or project and of the form "XX_". So if your project
is called Byte Flogger, the prefix might be BF_addObject:
I suppose you could use a similar scheme to mark certain methods as special for some sort of runtime manipulation.
DO NOT start any method names with a single leading underscore. That's an Apple internal coding convention to keep their method names from colliding with yours. If you want to differentiate your method names, just use a common prefix.
Since you are implementing the class, why not just define a method that returns a list of the special methods in that class? If you need to do subclasses, have them get the parent's list and add to it.

How do I create a file-scope class in objective-c?

I left the original, so people can understand the context for the comments. Hopefully, this example will better help explain what I am after.
Can I create a class in Obj-C that has file-scope visibility?
For example, I have written a method-sqizzling category on NSNotificationCenter which will automatically remove any observer when it deallocs.
I use a helper class in the implementation, and to prevent name collision, I have devised a naming scheme. The category is NSNotificationCenter (WJHAutoRemoval), so the private helper class that is used in this code is named...
WJH_NSNotification_WJHAutoRemoval__Private__BlockObserver
That's a mouthful, and currently I just do this...
#define BlockObserver WJH_NSNotification_WJHAutoRemoval__Private__BlockObserver
and just use BlockObserver in the code.
However, I don't like that solution.
I want to tell the compiler, "Hey, this class is named Bar. My code will access it as Bar, but I'm really the only one that needs to know. Generate a funky name yourself, or better yet, don't even export the symbol since I'm the only one who should care."
For plain C, I would is "static" and for C++ "namespace { }"
What is the preferred/best/only way to do this in Obj-C?
Original Question
I want to use a helper class inside the implementation of another. However, I do not want external linkage. Right now, I'm just making the helper class name painfully unique so I will not get duplicate linker symbols.
I can use static C functions, but I want to write a helper class, with linker visibility only inside the compilation unit.
For example, I'd like to have something like the following in multiple .m files, with each "Helper" unique to that file, and no other compilation unit having linker access. If I had this in 10 different files, I'd have 10 separate classes.
#interface Helper : NSObject
...
#end
#implementation Helper : NSObject
...
#end
I have been unable to find even a hint of this anywhere, and my feeble attempts at prepending "static" to the interface/implementation were wrought with errors.
Thanks!
I don't believe you will be able to do what you want because of the Objective-C Runtime. All of your classes are loaded into the runtime and multiple classes with the same name will conflict with each other.
Objective-C is a dynamic language. Unlike other languages which bind method calls at compile time, Objective-C does method resolution at invocation (every invocation). The runtime finds the class in the runtime and then finds the method in the class. The runtime can't support distinct classes with the same name and Objective-C doesn't support namespaces to seperate your classes.
If your Helper classes are different in each case they will need distinct class names (multiple classes with the same name sounds like a bad idea to me, in any language). If they are the same then why do you want to declare them separately.
I think you need to rethink your strategy as what you are trying to do doesn't sound very Objective-C or Cocoa.
There's no way to make a class "hidden." As mttrb notes, classes are accessible by name through the runtime. This isn't like C and C++ where class are just symbols that are resolved to addresses by the linker. Every class is injected into the class hierarchy.
But I'm unclear why you need this anyway. If you have a private class WJHAutoRemovalHelper or whatever, it seems very unlikely to collide with anyone else any more than private Apple classes or private 3rdparty framework classes collide. There's no reason to go to heroic lengths to make it obscure; prefixing with WJHAutoRemoval should be plenty to make it unique. Is there some deeper problem you're trying to fix?
BTW as an aside: How are you implementing the rest of this? Are you ISA-swizzling the observer to override its dealloc? This seems a lot of tricky code to make a very small thing slightly more convenient.
Regarding the question of "private" classes, what you're suggesting is possible if you do it by hand, but there really is no reason for it. You can generate a random, unique classname, call objc_allocateClassPair() and objc_registerClassPair on it, and then assign that to a Class variable at runtime. (And then call class_addMethod and class_addIvar to build it up. You can then always refer to it by that variable when you need it. It's still accessible of course at runtime by calling objc_getClassList, but there won't be a symbol for the classname in the system.
But this is a lot of work and complexity for no benefit. ObjC does not spend much time worrying about protecting the program from itself the way C++ does. It uses naming conventions and compiler warning to tell you when you're doing things wrong, and expects that as a good programmer you're going to avoid doing things wrong.

Private and protected methods in Objective-C

What is the recommended way to define private and protected methods in Objective-C? One website suggested using categories in the implementation file for private methods, another suggested trailing underscores, or XX_ where XX is some project-specific code. What does Apple itself use?
And what about protected methods? One solution I read was to use categories in separate files, for example CLASS_protected.h and CLASS_protected.m but this seems like it could get very bloated. What should I do?
There are three issues:
Hiding from compiler.
That is, making it impossible for someone else to #import something and see your method declarations. For that, put your private API into a separate header file, mark that header's role as "Private" in Xcode, and then import it in your project where you need access to said private API.
Use a category or class extension to declare the additional methods.
Preventing collisions
If you are implementing lots of internal goop, do so with a common prefix or something that makes a collision with Apple provided (or third party) provided methods exceedingly unlikely. This is especially critical for categories and not nearly as critical for your leaf node subclasses of existing classes.
Post the link for the site suggesting leading underscores, as they are wrong, wrong, wrong. Leading underscores are used by the system to mark private API and you can run into collisions easily enough.
Hiding from the runtime.
Don't bother. It just makes debugging / crash analysis harder and anyone determined enough to muck around at the runtime will be able to hack your app anyway.
There are no "real" private methods in Objective C, as the run-time will allow, via documented public APIs, access any method in any class by using their string names.
I never do separate interface files for "private" methods, and let the compiler complain if I try to use these any of these methods outside of file scope.
The XX_ seems to be the ad hoc means to create a pseudo namespace. The idea is to read Apple's docs and the docs of any frameworks you might use at any time in the future, and pick an XX prefix that none of these others is ever likely to use.

Are there any useful naming conventions for *your* constant/static variable in Cocoa?

I know that constants start with the k prefix, but does anyone have their own constant prefix, so they can easily get completion on their constants, instead of Apple's?
I use a three letter prefix for my classes because of my company name, let's pretend it's OMG. I tried prefixing my constants with omgkConstantName but that isn't very satisfying. I was also toying with either kk or ok (the o is from the OMG.) Or maybe I should do kOMGConstantName, that seems more Cocoa-ish?
It seems really useful to quickly get to your own constants, the same way you might want to get to your own classes. Does anyone do this? Is it terrible Cocoa style?
Also, is there a good naming convention for static variables you would only use in one class, like keys for a JSON dictionary? Should they have the k? Should they start uppercase, or do they follow normal case conventions?
// Static Variables
static NSString *searchTextKey = #"searchText";
static NSString *searchResultsKey = #"searchResults";
(more)
I try to consistently use kJAFoo (or kXXFoo where XX is a project prefix) for my public constants – especially actual consts which are exported symbols – but generally use kFoo for enums or static consts inside an implementation file. Similarly, I use sFoo for static variables and gJAFoo in the rare cases where I use exported globals.
None of these cases are as important as namespacing classes (and methods in categories on imported classes), though, since most types of conflicts will emerge at compile or link time rather than runtime.
Apple's Coding Guidelines for Cocoa recommends to use the same naming conventions for enumerations as for functions. Following this advice, OMGConstantName would be correct.
I normally make constants Pascal case.
If you choose to follow the 'namespacing convention' of putting a prefix on everything then you'd use that as well.
So I'd normally do
static NSString *SearchTextKey = #"searchText";
you may choose to namespace it though which would have it be (assuming your prefix is ZK)
static NSString *ZKSearchTextKey = #"searchText";
In general I only namespace things that are used in multiple projects, following the google recommendation (or at least it was when I was settling upon my naming convention).
The most important thing though is that whatever convention you settle on. Stick to it and be consistent (at least within a given project). At a certain point second guessing yourself is just going to waste time.
I usually follow the same prefix/capitalisation convention as classes, so where Cocoa has NSTouchPhaseBegan I might have GLTuneNameKey.