Magic Numbers
Magic Numbers
- Subject: Magic Numbers
- From: James Hober <email@hidden>
- Date: Thu, 07 Nov 2002 09:55:41 -0800
What is the best way to handle magic numbers in Objective-C?
Using #define seems common. However, its lack of type checking and its use of the
entire app's namespace seem to be drawbacks.
Using an enum is common and useful for ints. You can stick it between @interface
and @end and its scope is limited to the .h and .m file. But its use is limited to
ints. Also it is public, so enum changes may break client code that depends on a
particular enum value.
Another way is:
static inline int MY_CONSTANT {return 4;}
which goes outside of the @interface and @end, and allows the compiler check the
type.
Use of the keyword "const" is possible but doesn't seem nearly as useful in
Objective-C as it is in C++.
Particularly difficult are constants that you would like to define at the top of an
implementation file but that depend on the dynamic nature of Cocoa, for example
defining a particular NSFont. Code like:
NSFont *resultFont = [NSFont fontWithName: @"Helvetica-Bold" size: 20];
seems to always want to go inside of a method body, rather than to be somehow
broken out and put at the top of the file so that it can be changed easily.
Your thoughts on magic numbers in Objective-C/Cocoa?
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.