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.
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
fileNameagain. However, many Obj-C programmers, encourage the following style:or even (depending on horizontal space on the line):
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
tempNameas your variable name since it doesn’t explain the role of the variable — you’d instead use something likefileNameWithExtension. 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).