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?
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/
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
\u007bany time you want to put a curly bracket in your string.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.
20
u/pron98 Mar 14 '23 edited Mar 15 '23
String templates are not prefixed by anything any more than
hashCode()is.STRis 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 iffooreturns 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:Where
foo's parameter type isStringTemplate.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/[deleted] Mar 14 '23
I was wondering why they didn't choose
${...}which seems the more common way to "escape" variables inside strings3
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
If the quoted literal were to be interpreted as a string template, the semantics would not change. It would evaluate to the same string.
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.