Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use an intermediate temp variable when appending to an NSString?

This works -- it does compile -- but I just wanted to check if it would be considered good practice or something to be avoided?

NSString *fileName = @"image";
fileName = [fileName stringByAppendingString:@".png"];
NSLog(@"TEST  : %@", fileName);

OUTPUT: TEST  : image.png

Might be better written with a temporary variable:

NSString *fileName = @"image";
NSString *tempName;
tempName = [fileName stringByAppendingString:@".png"];
NSLog(@"TEST  : %@", tempName);

just curious.

like image 657
fuzzygoat Avatar asked Nov 24 '09 17:11

fuzzygoat


People also ask

How to append NSString?

Working with NSString. Instances of the class NSString are immutable – their contents cannot be changed. Once a string has been initialized using NSString, the only way to append text to the string is to create a new NSString object. While doing so, you can append string constants, NSString objects, and other values.


1 Answers

Internally, compilers will normally break your code up into a representation called "Single Static Assignment" where a given variable is only ever assigned one value and all statements are as simple as possible (compound elements are separated out into different lines). Your second example follows this approach.

Programmers do sometimes write like this. It is considered the clearest way of writing code since you can write all statements as basic tuples: A = B operator C. But it is normally considered too verbose for code that is "obvious", so it is an uncommon style (outside of situations where you're trying to make very cryptic code comprehensible).

Generally speaking, programmers will not be confused by your first example and it is considered acceptable where you don't need the original fileName again. However, many Obj-C programmers, encourage the following style:

NSString *fileName = [@"image" stringByAppendingString:@".png"];
NSLog(@"TEST  : %@", fileName);

or even (depending on horizontal space on the line):

NSLog(@"TEST  : %@", [@"image" stringByAppendingString:@".png"]);

i.e. if you only use a variable once, don't name it (just use it in place).

On a stylistic note though, if you were following the Single Static Assigment approach, you shouldn't use tempName as your variable name since it doesn't explain the role of the variable -- you'd instead use something like fileNameWithExtension. In a broader sense, I normally avoid using "temp" as a prefix since it is too easy to start naming everything "temp" (all local variables are temporary so it has little meaning).

like image 56
Matt Gallagher Avatar answered Sep 23 '22 00:09

Matt Gallagher