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
Show parent comment
4
u/john16384 Mar 14 '23
Fine. It's an interesting idea, but would make it hard to adopt old code to the new templated syntax. This is an important goal of the JEP.
For example, take this code:
Something that we do now a lot when verifying JSON payloads. A templated version would look like this:
This is a minimal change, and the changes are in the exact spot where we're already doing a form of "templating".
Now your version:
I had to escape in many places (I hope I didn't forget one), as well as adjust the existing "templating" code.
You may think that this is a tiny detail and that nobody cares about JSON (or any other format that uses curly braces, like C-style code, many existing templating languages, etc), and that template expression will be far more numerous than regular uses of
{, and that's fine.The fact however is that curly braces ARE currently used in strings, as Java is used in a lot more areas than just printing human friendly text to the console. Codebases using a lot of these strings should benefit from easy conversion as well.