Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it always inappropriate to #import more than absolute necessary in Objective-C interfaces?

I'm well aware that the general rule of thumb is you should only import what is necessary—base class interfaces, protocol interfaces, etc.—for a class to compile and use @class for everything that can be forward-declared. However, I ran into the following scenario in which I felt like #import was a more appropriate solution:

#import "ClassA.h"      // Previously, @class ClassA;
#import "ClassB.h"      // Previously, @class ClassB;
#import "ClassC.h"      // Unnecessary to forward-declare

@interface ClassD : NSObject

@property (nonatomic, retain) ClassA *  classAObject;
@property (nonatomic, retain) ClassB *  classBObject;
@property (nonatomic, copy)   NSArray * classCObjects;

@end

At first, I simply forward-declared ClassA and ClassB (as the components of classCObjects are of ClassC only by contract). This was my initial instinct.

But after trying to use ClassD elsewhere, I quickly realized that I had to also import ClassA, ClassB, and ClassC along with ClassD everywhere I used it. This seems like something another class shouldn't have to care about when using ClassD. My thinking was that, basically, a user of ClassD should really only care about importing ClassD.h and assume it can work with the entire class without a bunch of other #import statements. Given the above approach, I've basically included everything necessary to work within the domain of ClassD right in its interface.

Is there a strong reason why this approach is not ideal, except for "you've included more than is absolutely necessary for compilation?"

like image 486
CIFilter Avatar asked Feb 08 '11 19:02

CIFilter


2 Answers

While the strategy you're generally following-- don't import more than necessary--is awesome, classy style and a great thing to aim for in general, don't sweat the tricky cases too much. Just #import what you need.

In practice, on a modern machine, the only effect over-#importing will have is to add a few unobservable microseconds to your compile time. Use the developer time you'll save for making your app awesomer. :)

like image 133
Ben Zotto Avatar answered Sep 28 '22 08:09

Ben Zotto


As a programmer, one should go forward declaration of classes where ever it is possible. It considerably reduces compilation time on big projects. But spending too much time on where to forward declare isn't any way going to help you design a very good attractive app. So, if you can forward declare do it but it is not a must.

like image 39
Mahesh Avatar answered Sep 28 '22 08:09

Mahesh