by chrismeller · 7y ago · 0 comments
While I use them every day, my favorite is still “replacing” String.Format with string literals. Shorter, sure, but less intuitive particularly for people coming from another language. You can do roughly the same thing in PHP with backticks, but most people avoid them for the same reasons.
I’m not sure how I feel about the trend as a whole. As long as I can continue using the old methods as well I suppose I don’t have much room to complain, but sometimes it does feel like we’re just changing for the sake of change and that’s usually a bad indicator.
For example:
var h = "Hello ";
var w = "world";
var output = String.Format("{1} {2}", h, w);
output = $"{h} {w}";
Would compile fine but throw on the String.Format() line due to the typo.There are also instances where, such as with Console.Write you are now formatting a string in order to pass it into... a method that formats strings. Yes, the same benefit is still provided, but with a fairly obvious decrease in clarity and increase in redundancy.
You feel that "{0} {1} {2}" provides better clarity than $"{FirstName} {MiddleInitial} {LastName}"?
In what's ways specifically? Using String.Format you have to keep your indices correct and 'compiling' the string in your head requires jumping back and forth between the format string and the args.
Interpolation wins on every account as far as I'm concerned.
Many languages also have format strings with interpolation: JavaScript, Python, Ruby, Swift, PHP, etc.
Java, C/C++/Objective-C/Go (I'm lumping them up because they're basically C + C NextGens), Matlab, SQL, ASM don't have them.
Everything else, has them.
On the list of languages that don't have it, Java is planning to add it, I don't see the C family to change because it's very conservative, and the others are domain specific and don't care that much about string operations.
Maybe for people coming from C++, but string interpolation is a feature in Python, JavaScript, PHP, etc. It's not exactly an unusal concept (like it was back when PHP started doing it)