HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Import management

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
managementimportstackoverflow

Problem

I am working on a personal iPhone ObjC project, and was recently getting frustrated with how tedious importing the same set of headers over and over was getting… So I created a header file that literally only imports other header files, and looks something along the lines of this:

//BackboneTools.h
#import "ASIHTTPRequest.h"

#import "CPTXYGraph.h"
#import "CPTGraphHostingView.h"
#import "CPTColor.h"
#import "CPTPlatformSpecificCategories.h"
#import "CPTFill.h"
#import "CPTPieChart.h"

#import "DateFormatter.h"
#import "JSONAssistant.h"
#import "Query.h"
#import "SegmentsManager.h"
#import "SharedState.h"

#import "NSString+Trimmable.h"
#import "UIImage+Resizable.h"


So now I usually just import this file in the .m files of my (many) View Controllers. As you can imagine, this makes imports a lot easier for me, especially for classes that mix and match these dependencies.

I was wondering if this is good style in ObjC. I know that monoliths like Foundation.h and UIKit.h do the same thing, though I wasn't sure if that approach is frowned upon for smaller projects.

Solution

You should always create classes as components, components you can rearrange.

Now you are lazy and import all needed classes in Prefix.pch, and it works fine for you. But imaging in few month you are working in another project and you realize, that that class you wrote would fit perfectly into your new app.

You have been busy in the meantime and forgot about few implementation details. you open the implementation file to see, what other files you need to copy over to the new project. But: as everything is imported in one place, you cannot tell easily. you must go through code and trial&error to identify the pre-requiereties. What a nightmare.

That said here is my policy of imports:

  • in .h files only the bare necessary:



forward declaration for any class

imports for any file containing an unknown protocol that will be extended or implemented publicly, or that a property like an delegate need to conform to.

  • in .m files next to the own .h file import of the classes, that were forward declared and all classes needed.



So actually it is a «latest moment possible» strategy.

oh, and of course it means: If you change some parts of the class, check, if you can remove imports.

Context

StackExchange Code Review Q#13963, answer score: 5

Revisions (0)

No revisions yet.