Should I return an NSMutableString in a method that returns an NSString

Ok, so I have a method that accepts NSString as input, performs an operation on the contents of this string, and returns the processed string. Thus, the declaration:

 - (NSString *) processString: (NSString *) str; 

Question: should I just return the NSMutableString instance that I used as my "working" buffer, or do I need to create a new NSString around the changed one and return this?

So what should I do this:

 - (NSString *) processString: (NSString *) str { NSMutableString *work = [NSMutableString stringWithString: str]; // process 'work' return work; } 

Or that:

 - (NSString *) processString: (NSString *) str { NSMutableString *work = [NSMutableString stringWithString: str]; // process 'work' return [NSString stringWithString: work]; // or [work stringValue]? } 

The second one makes another copy of the string that I return if NSString does not do such smart things as copy-on-modify. But the first returns that the caller can theoretically go over and change later. I don't care if they do this because the string belongs to them. But are there any good reasons to prefer the latter form over the first? And, is it preferable to stringWithString or stringValue ?

+4
source share
1 answer

Depends on how much you need to defend.

There is no sensible way a client of your code can check for volatility. Thus, there is no sensible way in which a client can drop from NSString to NSMutableString and unexpectedly achieve non-compiler-warning variability for the string.

So, as long as you trust your customers, you can also return a mutable string (like NSString ). Even if the client does something stupid and mutates, the compiler warnings will be damned, nothing will break.

In cases where this is important, you are returning the mutable backup storage of some object that should not be mutated externally. In this case, the client can ignore compiler warnings and / or pass it in a mutable version and completely crop your object.

Or, more subtly, a client can get a link to a supposedly unchanged return type and hold it long enough to mutate later, leaving their link in an amazing state.

Best practice: when calculating and returning a transition value, volatility does not matter. When returning links to an internal mutable store, it is best to make an immutable copy.

+7
source

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


All Articles