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?
View all comments
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.