Is there a reason why I should not just define #define NSFM [NSFileManager defaultManager] instead of writing every time?

There is a built-in shortcut to NSApp, is there a reason why I should not add one for NSFileManager?

#define NSFM [NSFileManager defaultManager] 

I think this is omitted, it will make my code cleaner, and I see no benefit from storing it. (I plan to do this in all of my projects from now on, so it will not be obscure.)

 NSFileManager *fm = [NSFileManager defaultManager] 
+4
source share
3 answers

Why don't you just use a local variable?

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

or better yet, enter the file manager as an argument to the method:

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

becomes

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

Since defaultManager is singleton (virtually global), it makes testing very difficult. Dependency injection saves you typing (as needed) in the method and makes it much easier to unit test - you can enter a test double instead of the standard Manager.

Finally, Cocoa and Objective-C tend to decline in favor of explicit short code. The philosophy is basically that using more detailed names makes the code easier to read (and therefore maintain). This philosophy is fully consistent with the Objective-C style, with alternating named arguments. If you really can't handle the extra text input (and the completion of the Xcode code will not work for you), stick with the existing names. When in Rome and all this ...

+5
source

If this makes your code cleaner, I'm all for it. Just keep in mind that any other developers who need to read your code will not immediately recognize that they represent NSFM or fm .

I would suggest a slightly more descriptive name: NSFileMgr . For most Cocoa developers, this would greatly facilitate the assignment of a variable without having to look for it.

UPDATE: See Barry Wark's answer for some very good points regarding testing.

+3
source

I would use a local variable every time because using defaultManager is not thread safe. If at some point you start using threads in your application, you may run into difficulties finding errors and not know why until you run this bit of documentation .

+1
source

Source: https://habr.com/ru/post/1299023/


All Articles