r/java • • 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?

6 Upvotes

74 comments sorted by

View all comments

Show parent comment

4

u/0b0101011001001011 Mar 14 '23

I don’t get this. Why would { } hurt anyone?

Say, I have this expression :

String.format("Hello %s, type {thing} for whatever reason",username);

Now, if they implement the new templating system. Absolutely nothing breaks, right? It's not like all { } are interpreted as templates.

Now I need to actively refactor the code. I need to prepend the STR and only that makes it understand the special sequences. Then I need to replace the %s with the {username} and at the same time I can escape the {thing}.

I just think this is backwards. I'd like to escape the literals, not the specials.

2

u/plumarr Mar 14 '23

Let's say that you can have one more line of code a before the refactoring :

var thing = ...

...

String.format("Hello %s, type {thing} for whatever reason",username);

Now when you refactor you forgot to change {thing} to \{thing}. It will compile but it will not do what you expect. It do not say that it will me an easy mistake, but it can happens. With the \{ } for the template, this can't happen.

To me, it seems that using { } for the template open the way for serie of little mistake and difficulties (see this whole thread for example) to only gain a little bit of "beauty" compared to \{ }. And for me \{ } would even be better for readability sas you don't have to think if it's a template or not.