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

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.

Related

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

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.

Can I create C functions that are only visible to my class which is broken into multiple files?

Using a static function, I can limit the linkage of my function to the file at hand and that is perfect in many cases. But I have a class that is unwieldy as one file, but breaking it up is made more frustrating because there are functions that I would like to keep 'private' but are needed throughout.
One part of the answer must be counter-questions, such as:
Why is your class so big that it must be split up?
Are you sure your class is so big that it must be split up? (How big is 'big'?)
Are you sure you have your class properly abstracted?
Can you make the common functions into a new class that can be used by the main class you are working with? That will hide the functions behind a class interface barrier.
On the whole, if you can avoid it, do not split the class file up arbitrarily because of size constraints; keep together that which belongs together.
A Gruesome Possibility
Assuming that a split is necessary and an orthodox split (into various classes that work together) is not possible, the question becomes: how gruesome will you accept your code being? (It's already a bit gruesome since there's an awful lot of functionality in a single file; can you stand it becoming more gruesome?)
Assume your class is in 4 (or more) files.
class.h
class.c
class1.c
class2.c
The header, class.h, is orthodox - self-contained and idempotent. It is used by the outside world (meaning outside this collection of source code) to access the facilities provided by the class.
The files class1.c and class2.c contain implementations of the functions in the class. They could be given a separate, distinctive file suffix - there might be some advantages to doing so. The files are not designed to be compiled standalone; they are strictly a convenience that splits the source up because the class got too big.
The file class.c is what you compile. It contains:
#include "class.h"
Other definitions needed by the class internals.
#include "class1.c"
#include "class2.c"
Thus, although the source is split up, you actually compile a single file, class.c.
In your makefile or equivalent, you specify that class.o depends on the header and all three source files; if any of those changes, then you need to recompile the whole lot. One advantage of changing the suffix of the implementation files (class1.c and class2.c) is that they will not compile separately because the suffix is not recognized by the C (Objective-C) compiler. One downside of changing the suffix is that your syntax-aware editor won't be aware of the correct syntax highlighting for the separate files unless you tell it the file type. If you use an IDE, it may also be less than amused at this trickery.
If you work on a machine where the size of the source means it cannot all be compiled at once like this, then you are snookered. This technique does not help at all; you have to split the files up and compile them separately. In that case, really look hard at whether you can split the code cleanly into several classes which can be managed in an orthodox way.
By request, my comment on the OP as an answer:
There's no language support for this that I'm aware of... You could put all the support functions in a separate c file and only #import its header from the class implementation files? If they don't have to be C functions (for passing as callbacks to C APIs, for example) I'd reimplement them as methods on the class and declare the private interface in a separate header—each implementation file would then #import both the "public" and "private" header.
Prefix their names with output of a cryptographic RNG. Now you don't have to worry about unintentional name collisions. Problem solved. You can hide the renaming in preprocessor macros if you really like.

Can we have member variables in Interface?

I read somewhere that interfaces can have member variables.
Static final constants only, can use
them without qualification in classes
that implement the interface. On the
other paw, these unqualified names
pollute the namespace. You can use
them and it is not obvious where they
are coming from since the
qualification is optional.
I am not quite understood by what they meant? Any help?
What you read is incorrect. Interfaces cannot have member variables.
In VB.Net the only allowable definitions inside an interface are
Properties
Methods
Events
Type Definitions (not legal in C#)
I'm not entirely sure what the above paragraph is referring to. Based on the text though it sounds like it's refering to Java. They phrase static and final is most often associated with Java code and not .Net (static and readonly).
Can you give us some more context on it?
If you define a constant like this inside a class MyClass:
public static final int MY_CONSTANT = 1;
you can refer to it from other classes as MyClass.MY_CONSTANT, using the MyClass qualifier. This hints the location of the constant definition.
If you define such a constant in an interface MyInterface, you still can refer to it using MyInterface.MY_CONSTANT. However in the classes implementing MyInsterface you can simply use MY_CONSTANT without "MyInterface" prefix.
It may look convenient (less key strokes), but may lead to confusion because without qualifier (prefix) it is not clear where the constant was originally defined.
Adding member variables to interfaces would be bringing in MI through the back door.
Not available in .NET, sorry.
I wish it were there though.

What's the rationale behind the Qt way of naming classes?

I am wondering why Qt uses Q before every class name rather than putting everything in a namespace. Is there any particular reason, such as making the names easy to search for, or is it just about brand names?
I believe it is historical. Namespaces were introduced into C++ around 1995. Qt development started in 1991 so namespaces could not be used, obviously.
It may be a portability issue. Namespaces weren't / aren't supported by every compiler, so the naming convention helps to cut down on naming clashes.
The documentation for Qt refers to namespaces, although I didn't check the code to see if they are truly c++ namespaces or a hack with public declarations inside a class. I would guess that the rest is trying to avoid causing everybody to need to rename everything, although they could provide a migration path if they wanted to, like so:
namespace Qt
{
class Object { ... };
}
#ifndef NO_OLD_DECLS
typedef Qt::Object QObject;
#endif
Qt is very conservative on the C++ language features it uses. No namespaces, exceptions or RTTI. See also this article detailing why templates are not used in signal/slot handling.
Seeing as there's not a single C++ compiler left that doesn't implement namespaces, nowadays there's only one reason: Branding :)
Qt uses a Q prefix as part of their coding style. It usually serves the purpose of making it easier to read the code and spot what is what.
An identifier that:
is prefixed with "Q" and suffixed with "Private" is a private class used for implementation details and is not part of the API (e.g. QPainterPrivate)
is prefixed with "Q" and not suffixed with "Private" is a public class (e.g. QWidget)
is prefixed with "q" (lowercase) is a public global function (e.g. qRgb)
Adopting a coding style and using it uniformly makes it much easier for other people to understand code they didn't write.
Ref.: Qt Coding Style

Objective-C equivalent of Java packages?

What is the Objective-C equivalent of Java packages? How do you group and organize your classes in Objective-C?
Question 1: Objective-C equivalent of Java packages?
Objective-C doesn't have an equivalent to Java packages or C++ namespaces. Part of the reason for this is that Objective-C was originally a very thin runtime layer on top of C, and added objects to C with minimum fuss. Unfortunately for us now, naming conflicts are something we have to deal with when using Objective-C. You win some, you lose some...
One small clarification (although it's not much for consolation) is that Objective-C actually has two flat namespaces — one for classes and one for protocols (like Java's interfaces). This doesn't solve any class naming conflicts, but it does mean you can have a protocol and class with the same name (like <NSObject> and NSObject) where the latter usually adopts ("implements") the former. This feature can prevent "Foo / FooImpl" pattern rampant in Java, but sadly doesn't help with class conflicts.
Question 2: How to [name] and organize Objective-C classes?
Naming
The following rules are subjective, but they are decent guidelines for naming Objective-C classes.
If your code can't be run by other code (it's not a framework, plugin, etc. but an end-user application or tool) you only need to avoid conflicts with code you link against. Often, this means you can get away with no prefix at all, so long as the frameworks/plugins/bundles you use have proper namespaces.
If you're developing "componentized" code (like a framework, plugin, etc.) you should choose a prefix (hopefully one that's unique) and document your use of it someplace visible so others know to avoid potential conflicts. For example, the CocoaDev wiki "registry" is a de facto public forum for calling "dibs" on a prefix. However, if your code is something like a company-internal framework, you may be able to use a prefix that someone else already does, so long as you aren't using anything with that prefix.
Organization
Organizing source files on disk is something that many Cocoa developers unfortunately gloss over. When you create a new file in Xcode, the default location is the project directory, right beside your project file, etc. Personally, I put application source in source/, test code (OCUnit, etc.) in test/, all the resources (NIB/XIB files, Info.plist, images, etc.) in resources/, and so on. If you're developing a complex project, grouping source code in a hierarchy of directories based on functionality can be a good solution, too. In any case, a well-organized project directory makes it easier to find what you need.
Xcode really doesn't care where your files are located. The organization in the project sidebar is completely independent of disk location — it is a logical (not physical) grouping. You can organize however you like in the sidebar without affecting disk location, which is nice when your source is stored in version control. On the other hand, if you move the files around on disk, patching up Xcode references is manual and tedious, but can be done. It's easiest to create your organization from the get-go, and create files in the directory where they belong.
My Opinion
Although it could be nice to have a package/namespace mechanism, don't hold your breath for it to happen. Class conflicts are quite rare in practice, and are generally glaringly obvious when they happen. Namespaces are really a solution for a non-problem in Objective-C. (In addition, adding namespaces would obviate the need for workarounds like prefixes, but could introduce a lot more complexity in method invocation, etc.)
The more subtle and devious bugs come from method conflicts when methods are added and/or overridden, not only by subclasses, but also be categories, which can cause nasty errors, since the load order of categories is undefined (nondeterministic). Implementing categories is one of the sharpest edges of Objective-C, and should only be attempted if you know what you're doing, particularly for third-party code, and especially for Cocoa framework classes.
They use long names...
Article on coding style & naming in Cocoa / Objective-C
Discussion whether Obj-C needs namespaces (deleted, archive here)
See
What is the best way to solve an Objective-C namespace collision?
for a discussion of how Objective-C has no namespaces, and the painful hacks this necessitates.
Unfortuantely objective c doesn't have any equivalent to namespace of C#,c++ and package of java....
The naming collisions could be solved by giving contextual name for example if u gonna give a name to method it should imply the class and module that it comes in so that...these problems could be avoided.
Go through the following url to know more on naming convention as advised by apple
http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/ProgrammingWithObjectiveC/Conventions/Conventions.html
What about something like this (inside a directory)?
#define PruebaPaquete ar_com_oxenstudio_paq1_PruebaPaquete
#interface ar_com_oxenstudio_paq1_PruebaPaquete : NSObject {
and importing it like this:
#import "ar/com/oxenstudio/paq1/PruebaPaquete.h"
PruebaPaquete *p = [[PruebaPaquete alloc] init];
and when you have name collision:
#import "ar/com/oxenstudio/paq1/PruebaPaquete.h"
#import "ar/com/oxenstudio/paq2/PruebaPaquete.h"
ar_com_oxenstudio_paq1_PruebaPaquete *p = [[ar_com_oxenstudio_paq1_PruebaPaquete alloc] init];
ar_com_oxenstudio_paq2_PruebaPaquete *p2 = [[ar_com_oxenstudio_paq2_PruebaPaquete alloc] init];
Well, I think all the other answers here seem to focus on naming collisions, but missed at least one important feature, package private access control that java package provides.
When I design a class, I find it is quite often that I just want some specific class(es) to call its methods, b/c they work together to achieve a task, but I don't want all the other unrelated classes to call those methods. That is where java package access control comes in handy, so I can group the related classes into a packaged and make those methods package private access control. But there is no way to do that in objective c.
Without package private access control I find it is very hard to avoid people writing code like this, [[[[[a m1] m2] m3] m4] m5] or [a.b.c.d m1].
Update: Xcode 4.4 introduced "An Objective-C class extension header", in my opinion, that is in some way to provide "package private access control", so if you include the extension header, you can call my "package private" methods; if you only include my public header, you can only call my public API.