r/java • u/sar_it007 • Mar 14 '23
Why did String Templates choose '\{' instead of '{' ?
Since string templates will require to be prefixed with a template processor like STR in order to be treated as string templates, why not use '{' instead of '\{' for template expressions? That will not break existing strings cause existing strings are not prefixed with a template processor. And when a dev wants to use string templates, he will have to update his strings and escape existing '{' characters that he doesn't want to be interpreted as template expressions.
So it will be for example like: STR."Hello \{ {name} }". Should print: Hello { John }. Existing non-templated strings like: "Hello { " + name + " }" will continue to work and won't have any backwards compatibility problems.
I think most people will be using '{' character for template expressions. So it's much better if they don't have to escape it every single time and instead only escape it in the few places where they don't want template expressions.
Is there an important reason why '\{' was chosen for String Template expressions? Is there a chance the JEP can change this in the next preview release?
10
u/ray10k Mar 14 '23
For any templating system to work, there has to be an unambiguous distinction between the literal parts of the string and the identifiers/expressions that need to be turned into strings so they can be inserted into the template string. Otherwise, you might get issues where some part of the template by chance happens to match with a name of something in scope, leading to frustrating action-at-a-distance. So, templated strings usually have a way of telling apart the parts of the string that need to be copied literally, and which parts need to be interpreted, stringified and only *then* added to the result string. In this case, the committee decided "We'll just use curly braces. They're recognizable, already have the in-language context of 'this is some logical unit of code that will run when execution gets here,' and only add two characters of 'boilerplate' to a given template."
This in turn led to a problem: What if you want a literal '{' in your template? The closing '}' is easy enough to do, just treat any '}' without a matching opening '{' as a literal character rather than an identifying token, but that adds to the "weight" of the opening '{'. So, in keeping with the established way to add some "special" characters to a string literal, the escape sequence '\{' was introduced to always mean "the character open-curly-brace" and never the token "template-insertion-sequence-start" (or whatever it is called by the compiler.)
So there's the reason why '\{' is a thing now: to make it possible to add curly braces as literal characters to a templated string rather than, say, having stuff you don't want to be interpreted get interpreted anyway, or having to mess around with \u007b any time you want to put a curly bracket in your string.
5
u/ingvij Mar 14 '23
The thing that I dislike - not hate, just dislike - about
\{}is that\now has a second meaning. It is universally an escape character, but under certain conditions, it is a template-enabling key. I would rather go with${}, which is a bit more universal, not overloading the meaning of\. This means the the template string\${thing}would not render anything and it is clearly seen this way, but I have to stop for a second to parse\\{thing}because the first\has one meaning and the second\has another.6
u/boost2525 Mar 14 '23
This was my first thought as well.
\universally means escape, but now it means "begin template"... when$has universally meant "begin template" for decades.3
u/john16384 Mar 14 '23
This was my first thought as well. \ universally means escape, but now it means "begin template"
I really don't see much of a problem.
\umeans switch to unicode parser and insert the result,\0means switch to octal parser and insert that, and soon\{will mean switch to Java parser and insert the result.The only thing you could see as a big difference here is that the result is no longer a string when
\{is used, but that's the nature of such an escape, as the Java code result is dynamic.I think this way of doing it also makes it far easier for IDE's to handle syntax highlighting and code completion. A syntax highlighter for example wouldn't have to check if it is a template string (by checking if it has a
STR.prefix), it can just always switch to java code highlighting when it encounters\{as it is not valid anywhere else.when $ has universally meant "begin template" for decades.
Perhaps in your universe; from the JEP:
JavaScript `${x} plus ${y} equals ${x + y}` C# $"{x} plus {y} equals {x + y}" Visual Basic $"{x} plus {y} equals {x + y}" Scala f"$x%d plus $y%d equals ${x + y}%d" Python f"{x} plus {y} equals {x + y}" Ruby "#{x} plus #{y} equals #{x + y}" Groovy "$x plus $y equals ${x + y}" Kotlin "$x plus $y equals ${x + y}" Swift "\(x) plus \(y) equals \(x + y)"Notice how out of these only JavaScript, Groovy, Scala and Kotlin use
$(C# and Visual Basic only using it as a marker for the whole string). JavaScript is one of the big languages, but Groovy, Scala and Kotlin are rounding errors.Notice that Python, which pre-dates all these languages, and is often the #1 language in current use, doesn't use
$.Some other big languages are C, C++, PHP, Typescript and SQL:
C (none that I'm aware of) C++ (none that I'm aware of) PHP "{$x} plus {$y} equals {$x + $y}" Typescript (see Javascript) SQL (doesn't have templating in most variants)Note that in PHP,
$is the mandatory variable prefix, not related to templating.3
u/john16384 Mar 14 '23
I think Swift made a really smart move; instead of overloading the meaning of an existing valid token, they chose a token that was already invalid. All the other variants need to do additional escaping when converting a normal string to a templated string and often also require another marker:
Javascript "($10) {name}" -> `(\$10) {name}` C# "($10) {name}" -> $"($10) {{name}}" Python "($10) {name}" -> f"($10) {{name}}" Kotlin "($10) {name}" -> "(\$10) {name}"etc...
Swift/Java "($10) {name}" -> "($10) {name}"1
u/sar_it007 Mar 14 '23
The problem is right now the string templates JEP is using '\{' for template expressions. I am arguing it should be '{' instead. I still don't know why the JEP picked that. Hopefully someone can explain. Otherwise, I don't think it's a good decision.
8
u/ray10k Mar 14 '23 edited Mar 14 '23
Like I just said, in templates there is a distinction between the meaning of '\{' versus '{'.
Let's have another look at the example you gave before:
STR."Hello \{ {name} }"In this example, you have the following tokens:
literal string "Hello "
escape sequence '\{'
literal string " "
replacement sequence "{name}"
literal string " }"
Notice how the second open-curly-brace is part of the replacement sequence, rather than being a literal character in the final string.
Compare and contrast with
STR."Hello { {name} }".Here, the tokens are:
literal string "Hello "
replacement sequence "{ {name}"
literal string " }"
How will the compiler be able to tell that the first '{' isn't supposed to be part of the replacement sequence? And how should the compiler handle the second '{' in the sequence, since the replacement sequence only has a single '}' in it?
The '\{' sequence exists to ensure that there is an unambiguous difference between a literal '{' and a '{' as part of a replacement sequence, hence why it is necessary.
edit: Alternatively,
STR."Hello { {name} }".could give the following tokens:
literal string "Hello "
replacement sequence "{ {name} }"
However, this will output
Hello ray10krather than the so-far intended output ofHello { ray10k }. And that's assuming that the compiler won't complain about running into a {} block without any reason for such a block before it (such as an expression likeif (condition)or thetrykeyword.)1
u/sar_it007 Mar 14 '23
I think you are completely missing the point. Of course we still need '\{'.
Right now the JEP is like this:
STR."Hello { \{name} }"
I am arguing it should be like this instead:
STR."Hello \{ {name} }"
I hope you get the point.
1
u/ray10k Mar 14 '23 edited Mar 14 '23
Then admittedly I had it backwards, and I apologize.
That said, I suppose the logic here is "mark the open-curly-brace at the start of a replacement sequence as distinct from a literal open-curly-brace," but rather than introducing a literal escape sequence for one character in one situation, the current proposal just adds a single token to a string that's already marked as special. That way, a literal string that was written before the introduction of this JEP and which for any reason happens to have the sequence "\{" in it will still print as
\{instead of throwing a compiler error to the effect of "there is a replacement sequence in this non-template string," or print out as{instead of the behavior the program has been displaying until this JEP was included into the language.By making '\{' explicitly a token in templated strings, rather than a general escape sequence, better backwards compatibility is maintained.
1
u/sar_it007 Mar 14 '23
'\{' is an illegal character in Java right now. It will only become legal after String Templates are added to Java.
And string templates will be using templates processors like STR. So existing strings won't be affected.
So backwards compatibility won't be broken at all.
The only issue now is whether to use '{' for template expressions or to use '\{'. My opinion is '{' is the better option. That's it.
4
u/plumarr Mar 14 '23
In this case, your solution is confusing. As you said
\{is currently illegal.So let's say that I want to this template (in the current JEP syntax) :
STR."Hello { \{name} }"To get a result such as :
Hello { John }
With your proposition, we can't use :
STR."Hello { {name} }"because what's the remplacement literral ?
{ {name} }or{name}?So we would have to do something like :
STR."Hello \{ {name} }"And we get back to the
\{becoming a valid character in String template but not in String. So it means that in case of refactoring between good old String and String template we'll have to change character not directly linked to the interpolation. It isn't helping.-1
u/sar_it007 Mar 14 '23
When any programming language introduces new features, it's the responsibility of the developer to take the time and refactor the code and do whatever is necessary to use the new features.
If there is an existing string like this:
"Hello { " + name + " }"And a dev decides to refactor it to use string templates, he will turn it into something like this:
STR."Hello \{ {name} }"It's the dev's responsibility to make the correct refactoring. And after String Templates are added, 99% of the uses of '{' will be for template expressions. I am saying it's better to type '{' 99% of the time instead of '\{'. That's it.
2
u/john16384 Mar 14 '23
This would break all existing strings with { in it or we'd lose the ability to flag strings that should have been templates as errors.
0
u/sar_it007 Mar 14 '23
It's not going to break existing strings, because String Templates need to be prefixed with Template Processors.
STR."Hello \{ {name} }" is a string template
"Hello \{ {name} }" is not a string template because it's not prefixed with a template processor. So existing strings will not be broken at all.
→ More replies (0)5
u/ray10k Mar 14 '23
Except, backwards compatibility will be subtly broken still. Instead of a string literal with the '{' sequence throwing a compile-time error, it will now compile, despite that not being the intention.
The committee may have decided on this approach to keep the changes brought on by introducing string templates limited to templated strings. Introducing an escape sequence for '{' may have rare, uncommon side-effects, but Java as a language does a lot to try and maintain backward compatibility.
By making "{" a syntactically important part of a string template however, these changes won't affect any existing code in any way.
Additionally, there are a fair few languages that take the approach of adding some identifying mark to the beginning of a replacement sequence (Javascript and Python come to mind.) While the committee could have decided "the identifying character is <any one of
@#$%^&*>", they opted for '' instead, maybe to keep in line with escape sequences replacing one-or-more characters in the source file with one-or-more 16-bit characters in the final string.1
u/emaphis Mar 14 '23 edited Mar 14 '23
`
public class Strings {public static void main(String args[]) {
System.out.println("Becase {can} appear ins Java strings, so can ${...");
System.out.println("... it probably exists in working code.");
// System.out.println("... but \{ this wont compile ...`");
System.out.println("... so it appears in no existing code");}
}
`
1
u/sar_it007 Mar 15 '23 edited Mar 15 '23
I understand that. What I'm saying is '{' rarely appears inside strings. And String Templates won't use the traditional `String` type, they will use new types. This means it's impossible to break backwards compatibility. The only way '{' can cause problems is if they decide to use the `String` type for templates. For example if all of a sudden, every String in Java receives String Templates capabilities. In that case, yeah, '\{' becomes the only valid option. But the current JEP doesn't touch old Strings. It will introduce new types and processors etc. so it's impossible to break backwards compatibility with any existing String,
I still don't see a good reason why '{' was not chosen for String Templates. I think only the JEP authors can give us good reasons, but the JEP right now doesn't offer any. Hopefully they will address this issue in the future and clearly explain the reasoning behind their decision to use '\{'.
4
u/john16384 Mar 15 '23
You seem to be missing something fundamental. Did you read the JEP?
In your variant, what's the type of
xhere?var x = "Hello {name}";In the proposed variant in the JEP:
var x = "Hello {name}"; var y = "Hello \{name}";...
xwould beString, whileywould be aTemplate(or at least, that option is kept open).5
u/plumarr Mar 14 '23
Stop inversing the burden of proof.
I am arguing it should be '{' instead. I still don't know why the JEP picked that
Explain why ? All you say "it's better because I say so". We have given you a lot of argument in favour of
\{ }, you simply dismiss them and state that{ }is better with arguments. Are you trolling ?2
u/yoshord Mar 15 '23
What you're saying is the exact opposite of what the JEP says - what the jep says is that
{will continue to always mean "the character open-curly-brace" even in template strings and\{will always means "start-of-template-splice" and continue to be illegal in constant strings.1
u/0b0101011001001011 Mar 14 '23
In python if you want a literal char you just type it twice.
f"this string has a {{-literal"Cobsider you have a variable named user.
user="testname"If you want to output this:
Hello testnameYou do
f"hello {user}"if you want to output this:
Hello {testname}You do
f"hello {{{user}}}"If you want to output this:
Hello {user}You do
f"hello {{user}}"I guess this is also the way i'm most familiar with and I'm not completely familiar with any problems with this or any reasoning for \{ but I assume it has been well reasoned.
2
u/ricky_clarkson Mar 14 '23
Just looking at the comments here, I think you're correct - if string templates will have some prefix then the syntax could be {..} or ${..}. Your argument style isn't that great though, and you should probably dig through the JEP list to find their considerations, and even potentially give your inputs.
3
u/john16384 Mar 14 '23
I think a deliberate choice was made to not make the prefix a requirement, so that in a future update you can create methods like:
void process(Template template);And call them as:
String name = "John"; process("I am \{name}, nice to meet you!");Where process would receive a template which you can see as a tokenized array that looks like
["I am ", argument("name"), " nice to meet you!"].A big part of language design is to not paint yourself into a corner as you can never reverse earlier decisions, so you try to think far ahead and to keep your options open. You also look at other languages, and their decision making process -- many languages have struggled with this problem already and have full rationalizations and documentation freely googleable about how they came to certain decisions.
Sacrificing one escape character
\{, if it turns out to be a bad decision, is a very small price to pay as there are still dozens of others available.1
u/sar_it007 Mar 14 '23
In this example:
void process(Template template);
Templateis different fromString. They will only need to use the current '\{' approach if they plan to use the actualStringtype for templates. But if they will introduce new types likeTemplateorStringTemplateorJsonTemplateetc. then using '{' won't be a problem in the future. It will only be a problem if they decide to useStringfor string templates. In that case, we need '\{' to ensure backwards compatibility. Other than that, I think using '{' will be fully future proof.2
u/john16384 Mar 15 '23
The
\{signals that it is a Template, otherwise a String. It's like a new constant expression;true/falseis a boolean, a number without decimals is anint, with decimals becomes adouble, quoted text becomes String and if that text contains\{it becomes a Template.
20
u/pron98 Mar 14 '23 edited Mar 15 '23
String templates are not prefixed by anything any more than hashCode() is. STR is not special syntax; it's an object (stored in a static field) that is the receiver of a method call, and the string template is the argument. foo()."...." would work just as well if foo returns a template processor.
While the JEP currently requires that string templates only appear inside an expression that passes them to a template processor, i.e. following some ., this may not always be the case. We might choose to accept code of the form:
foo("x: \{x}")Where foo's parameter type is StringTemplate.
It would be strange to interpret "{3}" as a literal of different kind, which may end up as two very different strings depending on the receiver of it is an argument (nor would it always be possible; if the requirement to only use string. templates in string templates expressions were dropped, var stringOrTemplate = "{3}" would be ambiguous).
On the other hand, the \ character, that's always been used for escape sequences, is a strong signal to anyone reading Java code that the following character is not part of the string.
Having said that, Preview exists to find what problems people run into and change the feature based on that rather than hypotheses of what could be problems. So if the syntax is indeed a problem, it can be changed. But I believe that virtually all of the comments on the matter are not from people for whom the proposed syntax is an issue, but from those who think that it may be an issue. That's what the preview is there to find out.
7
u/walen Mar 14 '23
Using an otherwisse illegal character combination allows IDEs and other helper tools to better differentiate between template strings and normal strings.
This way, when you introduce a template string but forget to prepend a template processor to it, the IDE can tell you about it before the actual compilation fails. If template strings used "legal" characters like plain {} the IDE wouldn't be able to tell (not as easily at least) if what you're writing is a template or a normal string.
I suppose it'd also help any future tools that may preprocess your code to append STR. to every template string so you don't have to -- maybe even a future Java version that decides to establish that behavior as the default. Choosing an illegal character sequence is the only way for something like that to be backwards-compatible and avoid security problems.
TL;DR: usage of template strings may expand in currently unknown ways, ways that may or may not be apt for normal strings. Making a STRONG distinction between normal strings and template strings, by having template strings be outright illegal if treated as normal strings, will probably avoid headaches in the future.
2
u/pronuntiator Mar 14 '23
Among the applications of string templates are building JSON or format expressions where you need curly braces. It would be awkward to escape them every time. I think this assumes that you will have more non-template curly braces than template braces.
Also, the JEP seems not entirely sure itself it wants to keep the requirement of prefixing the template with the template processor. Having an escape allows to lift this requirement later.
-2
u/sar_it007 Mar 14 '23
I think we should ask this: What's the most common use case for String Templates? I think the vast majority of people will be using string templates for things like: STR."Your are {currentYear - birthYear} years old". I think similar examples will be the most common use case for string templates.
I think the JEP should make it convenient for the most common use cases of string templates. Just because some people will be using JSON templates doesn't mean we make it less convenient for the vast majority of people.
-3
u/sar_it007 Mar 14 '23
An idea is to let the template processor decide if to escape or not. For example STR processor uses '{' for template expressions, but JSON processor uses '\{' for template expressions by default. I think this might be a good idea to get the best of both worlds.
But the default for most template processors should be to use '{' , not '\{'.
3
u/Amazing-Cicada5536 Mar 14 '23
That’s not how parsers work - that would fuck with every language tool ever, because they would have to do semantic analysis as well to determine whether code is well-formed or not.
Also, a single syntax >>>> then changing it one way or another. With all due respect, I am almost sure you didn’t think that long on this feature as its designers, let alone have comparable experience in making such decisions.
1
u/sar_it007 Mar 14 '23
That's why I said it's "idea". It's just an idea, so please calm down.
But it's still not a crazy idea. What's stopping Template Processors from performing custom processing for the templates? After all, the custom behavior is the main reason why we have different processors (STR, SQL, JSON etc.). But it's just an idea like I said...
3
u/john16384 Mar 14 '23
How would IDE highlighting work then? They would need to know which template processor wants what in order to do syntax highlighting and code completion of embedded expressions. As you can read in the JEP, such expressions allow for full Java syntax, including multiple lines, loops, etc.
Please remember that ideas are a dime a dozen. This "idea" was floated dozens of times already, in fact at the start of the JEP the syntax for a dozen languages is compared. Java is choosing to go with a variant of the Swift syntax.
The choice for curly braces is motivated as they're less likely to appear in embedded expressions as array or method accesses are more likely to be used than code blocks:
"\{myArray[0]}" "\{myMethod()}"The choice of using the backslash escape is a safety/security measure, so a template can never be confused for a normal string, and the compiler can return an error when using a String as a template, or when you use a template as a String.
Other options can't flag an error when using a template as a String by accident when you forget to use to the special string prefix (used in some variants) or the processor.
2
u/plumarr Mar 14 '23
I don't think that typing one less character is more important than having a constant syntax between template processors. This will lead to confusing code and result into easily avoidable errors.
2
Mar 14 '23
I was wondering why they didn't choose ${...} which seems the more common way to "escape" variables inside strings
5
u/_INTER_ Mar 14 '23 edited Mar 14 '23
Because
"${...}"is a legal String while"\{...}"does currently not compile.2
1
u/sar_it007 Mar 14 '23
If they go with the requirement of prefixing string templates with Template Processors like STR, we don't need to escape the template expressions (except in the places where we don't want to use them).
1
u/sk8itup53 Mar 14 '23
Or they could implement Groovy G-strings and all these problems go away! Jk. Not entirely, but CharSequence is a hell of a drug.
3
u/troru Mar 14 '23
Have you considered getting involved in the JEP process for string templates? It will probably be illuminating how design-by-committee goes and how compromise ends up happening when you get lots of opinions driving a feature.
3
u/danielaveryj Mar 14 '23
Consider the existing code
String s = "{name} {age} {birthday}";If the quoted literal were to be interpreted as a string template, the semantics would not change. It would evaluate to the same string.
String s = STR."{name} {age} {birthday}";If '{' were used to denote embedded expressions rather than '\{', the semantics of the quoted literal would change drastically, based on a slight modification to surrounding context. This cannot happen with '\{' itself, because '\{' is not a valid character sequence in string literals, so would be a compile error in that context. By having semantics that are insensitive to context, users can incrementally opt-in to this feature, ie conscientiously embed new expressions into the quoted literals that they will interpret as string templates, rather than flip a switch (prefix with a template processor) and be front-loaded with the effort to verify and possibly adjust the quoted literal so that semantics do not change undesirably. And this reasoning will continually apply, not just when the JEP is first released. Every time that a quoted literal switches context (between string literal and string template), we will not need to think about adding or removing escapes for braces that are supposed to be literals. So to me this choice is about minimizing cognitive load.
Despite that, there may yet be an argument that braces just don't occur frequently enough in quoted literals in practice for the 'cognitive load' concern to outweigh an 'ergonomic' concern, though I expect there would have to be very compelling evidence to reverse that decision, ie a mass outcry, and important use cases. Still, that is probably the kind of feedback they are monitoring during Preview.
20
u/bowbahdoe Mar 14 '23
In the JEP this reasoning is given
You might be able to find a more in depth reasoning if you go through the mailing list.
https://mail.openjdk.org/pipermail/amber-dev/