views:

108

answers:

3

There is a built-in shortcut NSApp, is there any reason that I shouldn't add one for NSFileManager?

#define NSFM [NSFileManager defaultManager]

I think omitted this will make my code cleaner and I can't see any benefit to keeping it in. (I plan on doing this in all my projects from now on, so it won't be obscure.)

NSFileManager *fm = [NSFileManager defaultManager] 
+3  A: 
e.James
Meh. Abbreviations. Yuck. If you are going to do this, at least use something like *DefaultFileManager* or *DEFAULT_FILE_MANAGER*. However, if you are really using the file manager *that* much, I would suggest caching the return value in a local or instance variable.
bbum
@bbum a local variable actually sounds like a much better idea: `NSFileManager * fileManager = [NSFileManager defaultManager];` although I'm not opposed to using a global reference for something that is, for all intents and purposes, a global variable.
e.James
+3  A: 

Why don't you just use a local variable?

NSFileManager *fm = [NSFileManager defaultManager];
// use fm...

or better yet, inject the file manager as a method argument:

- (void)myMethod {
  //using [NSFileManager defaultManager]
}

becomes

- (void)myMethodWithFileManager:(NSFileManager*)fm {
 //usin fm
}

Since the defaultManager is a singleton (effectively a global), it makes testing really hard. Injecting the dependency saves you typing (as you want) within the method and makes it much easier to unit test—you can inject a test double instead of the defaultManager.

Finally, Cocoa and Objective-C generally come down on favoring explicit code over short code. The philosophy is basically that using more verbose names makes the code easier to read (and thus to maintain). This philosophy goes all the way to Objective-C's selector style with interleaved named arguments. Unless you really can't handle the extra typing (and Xcode's code completion won't work for you), stick with the existing names. When in Rome and all that...

Barry Wark
+1 The unit-testing angle is a very important point. Shame on me for not mentioning it.
e.James
A: 

I would use a local variable every time because using the defaultManager is not thread safe. If at any point you start using threads in your application you may end up with hard to find bugs and not know why until you run upon this bit of documentation.

cocteau