Minthos
Minthos

Reputation: 900

Are C functions bad style in Objective-C interfaces?

I declare an interface with some functions and some methods. Instead of declaring:
-(void)foo;
+(void)bar;

I declare:
-(void)foo;
void bar();

I think it's fine. The compiler thinks it's fine. Do other programmers also think it's fine?

Upvotes: 0

Views: 116

Answers (3)

Jano
Jano

Reputation: 63697

Concerns when choosing a C function or a static method: (from the top of my head)

  • Name collisions: Prefer static methods.
  • Functionality: Names are like roads, they tell you where you are and where you can go. If the code is related to something else you should make it a class method. Even when it is a garbage dump of unrelated methods (xxxUtils classes). Otherwise use a C function.
  • Locality: Prefer static methods as a way to group code in higher level units (because this is easier to see and understand from 30,000 feet).
  • Typing: A C function requires less of it. CGPointMake convenience function wouldn't be so convenient with more typing.
  • Linking: A bad call to a C function is seen before runtime.
  • Global state: Not a choosing criteria, but worth saying that in a OOP language, the output of C functions and class methods should depend on their inputs only. Touching global state goes against encapsulation, hides dependencies, makes code harder to understand, etc.
  • Overloading: C functions can be overloaded when tagged with __attribute__((overloadable)).

Upvotes: 2

foundry
foundry

Reputation: 31745

I don't quite understand the point of the question. You can similarly declare them all together:

 -(void)foo;
 +(void) bar;
 void bar();

All are legal in objective C and can co-exist with the same name as they are different entities (instance method, class method, C function). You can call void bar() from either of the former without issue, but not v/v as void bar() doesn't get passed a reference to self.

If the question is rather an issue of style, I would declare C functions separately from the @interface as they are not Objective-C.

With recent versions of Clang there is no need to declare these at all if they are not for public use...

update

Having read @Jano's answer, I now understand the point of the question a little more: why choose a class method over a function where either can achieve the same result (neither have access to self). These days I tend to always use the class method, it just seems to make sense in an obj-C context. Jano's answer seems pretty exhaustive as to why.

Upvotes: 1

Anoop Vaidya
Anoop Vaidya

Reputation: 46563

Its just a matter of USED-TO.

I would go for Objective-C style of methods unless I need some functions that are only available in C like pow().

Even if you want to add a C method, I feel it should be in a separate file, as AllCMethods.c It will be easier to recall, remember, use all obj-c methods and C-methods.

Upvotes: 0

Related Questions