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]
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...
If it makes your code cleaner, I'm all for it. Just keep in mind that any other developers who have to read your code will not immediately know what NSFM
or fm
represent.
I would suggest a slightly more descriptive name: NSFileMgr
. To most Cocoa developers, this would make the purpose of the variable a lot clearer without having to look it up.
UPDATE: See Barry Wark's answer for some very good points in regards to testing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With