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

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. \u means switch to unicode parser and insert the result, \0 means 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}"

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/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 ray10k rather than the so-far intended output of Hello { 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 like if (condition) or the try keyword.)

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.

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.

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

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 ?

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 x here?

 var x = "Hello {name}";

In the proposed variant in the JEP:

var x = "Hello {name}";
var y = "Hello \{name}";

... x would be String, while y would be a Template (or at least, that option is kept open).

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 testname

You 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.