Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a reason why I shouldn't just define #define NSFM [NSFileManager defaultManager] instead of writing it out each time?

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] 
like image 784
zekel Avatar asked Jan 23 '23 17:01

zekel


2 Answers

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...

like image 177
Barry Wark Avatar answered Jan 25 '23 07:01

Barry Wark


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.

like image 35
e.James Avatar answered Jan 25 '23 06:01

e.James