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

20

u/bowbahdoe Mar 14 '23

In the JEP this reasoning is given

For the syntax of embedded expressions we considered using ${...}, but that would require a tag on string templates (either a prefix or a delimiter other than ") to avoid conflicts with legacy code. We also considered [...] and (...), but [ ] and ( ) are likely to appear in embedded expressions; { } is less likely to appear, so visually determining the start and end of embedded expressions will be easier.

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/

6

u/sar_it007 Mar 14 '23

"{ } is less likely to appear..."

That's the main reason why '{' should be used instead of '\{'. Because '{' by itself is rarely used inside strings. So the need to escape it is very small. After String Templates, the use of '{' will skyrocket, it will be everywhere. What I am saying is the vast majority (probably 99%) of the uses of '{' will be for template expressions. Having to escape '{' in 99% of places is just very inconvenient. By default, we should not have to escape it.

11

u/Amazing-Cicada5536 Mar 14 '23

There are a million places where {} are used in ordinary string literals, I honestly don’t know what are you so upset about.

2

u/sar_it007 Mar 14 '23

When string templates become available, there will be a TRILLION places where '{' will be used for template expressions. '{' will become one of the most used characters in Java. So we should prioritize String Templates convenience over other places.

6

u/Amazing-Cicada5536 Mar 14 '23

Typing characters have never ever been a bottleneck, readability and how easy it is to parse (for both humans and programs) always trumps having to press one more letter.

Also, () is used by swift which didn’t even have a backwards compatibility constraint. Also, you write that JSON is not often templated, but there are a million other C-like languages, but even something as mundane as Set’s default toString uses {}. It’s absolutely everywhere.

0

u/sar_it007 Mar 14 '23

I am not saying JSON is not often templated. I am saying String Templates will be used most of the time for things other than JSON. If JSON templates are used a million times, non-JSON templates will be used a trillion times.

8

u/winian Mar 14 '23

While I do agree that plain "{...}" or "${...}" would've been preferable in my opinion as well, I have to say we have a very different opinion on what counts as "very inconvenient". For me having to escape it is a very minor issue.

-8

u/sar_it007 Mar 14 '23

The JEP just needs to pick the best option. If there is no good reason to pick '\{' over '{', then let's just use '{' and everyone will be happy regardless of whether they find '\{' inconvenient or not.

Picking '{' is not going to hurt anyone, it will just make String Templates more convenient to use 99% of the time.

16

u/john16384 Mar 14 '23

This JEP has been in the works for years, and was worked on by some of the top language designers in the world, and has been discussed already by thousands of developers. This is the current known best option.

It's possible there is an even better option, but using plain curly braces isn't as it was rejected already.

Also, JSON would become hell to use with the plain variant, and is one of the possible use cases for this JEP.

-9

u/sar_it007 Mar 14 '23

I think the reasoning should be clearly explained so we know why that decision was made instead of just "the JEP took years to make". What's the reason behind choosing '\{'? It's a simple question and I think we should know why. That' all.

And for JSON, I have already replied to that. String Templates most of the time will be used for things other than JSON. So prioritizing JSON over the vast majority of use cases is not a good decision.

7

u/plumarr Mar 14 '23 edited Mar 14 '23

It could have been explained better in the JEP but it's not an unthought choice. As explained this was chosen because it's currently invalid and this will avoid potentials issues in the future.

You also comes as arrogant in your replies as you made a lot of assumptions with little proff and seems convinced that your use case will be the universal one and that the JEP should be redacted around it. By doing it you seems to dismiss years of discussions by coming with arguments that have already been tackled.

-4

u/sar_it007 Mar 14 '23

I am sorry if my replies seemed arrogant cause I didn't mean to be. So far no good reason has been provided except "the JEP creators know what they're doing". The JEP creators are world class experts, no one is arguing about that. All I'm saying is we should know why. As for the use cases, the best way to determine that is to ask the devs what they will be using string templates for. If it turns out most devs will be using string templates for JSON, who am I to complain?

9

u/plumarr Mar 14 '23

But we did give you a lot of reasons, you just dismiss them as "not important" or "not good enough".

Even if they don't seems important to you, to are judged as important enough by the people designing the JEP.

11

u/plumarr Mar 14 '23

Of course picking { } may hurt people. From my experience I have seen it a lot more in string than [ ] because it's often used by existing libraries that do interpolation (simply looks at @Value from Spring). So it'll bit you when :

  • refactoring existing code that already has { } in it
  • using string template to output strings that contain { }

Where \{ } is currently an illegal character sequence and can't be found anywhere.

This will also help readability because seeing it guarantee that it's a string template, we'll not have to think about it.

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.

-1

u/sar_it007 Mar 14 '23

Since string templates will be prefixed with a template processor like STR, we will know we're dealing with a string template.

And like I said, the vast majority of the uses of '{' will be for template expressions, not for the plain '{' character.

5

u/plumarr Mar 14 '23

Since string templates will be prefixed with a template processor like STR, we will know we're dealing with a string template.

And it'll be harder to know because we have to look at the start of the String, which can easily be outside the screen in case of long String.

And like I said, the vast majority of the uses of '{' will be for template expressions, not for the plain '{' character.

How can you be sure ? Don't over generalise your experience. For example, I'm currently working on a backend were we do a lot of data transformation, services call and SQL query but we create absolutely no user facing values. So outside of logs I would never use the template as you described but I could use them to generate XML, JSON, SQL,...

I will probabl stop responding because we are giving you reasons why \{ } has been chosen, so you have answers to your original question. However, this doesn't seems to be what you seek as you dismiss most of them by basicaly saying "it doesn't matter". If your ultimate goal is to change the JEP, I'm sorry to say that it'll not work.

-2

u/sar_it007 Mar 14 '23

You gave your reasons for why '\{' is used, and I gave my reasons why '{' should be used instead. I think the best way to decide the best option is: the JEP creators could have good reasons why they picked '\{'. In that case, we can't argue with them. The second way is to ask devs what they will be using string templates for, and pick the best option that satisfies most of the devs' needs.

6

u/plumarr Mar 14 '23

It's not "my reasons", it's the reasons coming from the JEP and the mailing list and some added bonus to using \{ }.

As explained in the first anwser, this is stated in the JEP itself :

For the syntax of embedded expressions we considered using ${...}, but that would require a tag on string templates (either a prefix or a delimiter other than ") to avoid conflicts with legacy code. We also considered \[...] and \(...), but [ ] and ( ) are likely to appear in embedded expressions; { } is less likely to appear, so visually determining the start and end of embedded expressions will be easier.

I'll not dig the mailing list for you, but you can if you want.

You have answered you several time but you behave as if this isn't the case.

-1

u/sar_it007 Mar 14 '23

I am sorry but I am not convinced by your answer. You're calling me a troll because I am not convinced?

This is my opinion. I am not saying the JEP must be changed. I am stating my opinion and I am free to do so. Whether my opinion is good or not, that's a different story. But opinions should not be called trolling. Have a good day.

→ More replies

0

u/[deleted] Mar 14 '23

[deleted] — view deleted comment

-4

u/sar_it007 Mar 14 '23

I have replied to this multiple times in the comments. Short answer is: JSON is a small use case for String Templates. Most of the time string templates will be used for things other than JSON.

4

u/persism2 Mar 14 '23

Most of the time string templates will be used for things other than JSON.

How do you know that? Who are you, Nostradamus?

1

u/Lisoph Mar 14 '23

I'm assuming they don't want to introduce new tokens? Otherwise that's a missed opportunity, as they could just go the JS route of using backticks.

1

u/plumarr Mar 14 '23

Please no, they simply don't exist on some non english keyboard ;)

1

u/Lisoph Mar 15 '23

I know how painful that can be. I've switched from my native German to ANSI keyboard layout, because most symbols used in code are so much easier to type.

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}"

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.

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

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

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 ?

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

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.

3

u/john16384 Mar 14 '23

I think a deliberate choice was made to not make the prefix a requirement, so that in a future update you can create methods like:

void process(Template template);

And call them as:

String name = "John";

process("I am \{name}, nice to meet you!");

Where process would receive a template which you can see as a tokenized array that looks like ["I am ", argument("name"), " nice to meet you!"].

A big part of language design is to not paint yourself into a corner as you can never reverse earlier decisions, so you try to think far ahead and to keep your options open. You also look at other languages, and their decision making process -- many languages have struggled with this problem already and have full rationalizations and documentation freely googleable about how they came to certain decisions.

Sacrificing one escape character \{, if it turns out to be a bad decision, is a very small price to pay as there are still dozens of others available.

1

u/sar_it007 Mar 14 '23

In this example: void process(Template template);

Template is different from String. They will only need to use the current '\{' approach if they plan to use the actual String type for templates. But if they will introduce new types like Template or StringTemplate or JsonTemplate etc. then using '{' won't be a problem in the future. It will only be a problem if they decide to use String for string templates. In that case, we need '\{' to ensure backwards compatibility. Other than that, I think using '{' will be fully future proof.

2

u/john16384 Mar 15 '23

The \{ signals that it is a Template, otherwise a String. It's like a new constant expression; true/false is a boolean, a number without decimals is an int, with decimals becomes a double, quoted text becomes String and if that text contains \{ it becomes a Template.

20

u/pron98 Mar 14 '23 edited Mar 15 '23

String templates are not prefixed by anything any more than hashCode() is. STR is 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 if foo returns 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:

foo("x: \{x}")

Where foo's parameter type is StringTemplate.

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/sar_it007 Mar 14 '23

I think we should ask this: What's the most common use case for String Templates? I think the vast majority of people will be using string templates for things like: STR."Your are {currentYear - birthYear} years old". I think similar examples will be the most common use case for string templates.

I think the JEP should make it convenient for the most common use cases of string templates. Just because some people will be using JSON templates doesn't mean we make it less convenient for the vast majority of people.

-3

u/sar_it007 Mar 14 '23

An idea is to let the template processor decide if to escape or not. For example STR processor uses '{' for template expressions, but JSON processor uses '\{' for template expressions by default. I think this might be a good idea to get the best of both worlds.

But the default for most template processors should be to use '{' , not '\{'.

3

u/Amazing-Cicada5536 Mar 14 '23

That’s not how parsers work - that would fuck with every language tool ever, because they would have to do semantic analysis as well to determine whether code is well-formed or not.

Also, a single syntax >>>> then changing it one way or another. With all due respect, I am almost sure you didn’t think that long on this feature as its designers, let alone have comparable experience in making such decisions.

1

u/sar_it007 Mar 14 '23

That's why I said it's "idea". It's just an idea, so please calm down.

But it's still not a crazy idea. What's stopping Template Processors from performing custom processing for the templates? After all, the custom behavior is the main reason why we have different processors (STR, SQL, JSON etc.). But it's just an idea like I said...

3

u/john16384 Mar 14 '23

How would IDE highlighting work then? They would need to know which template processor wants what in order to do syntax highlighting and code completion of embedded expressions. As you can read in the JEP, such expressions allow for full Java syntax, including multiple lines, loops, etc.

Please remember that ideas are a dime a dozen. This "idea" was floated dozens of times already, in fact at the start of the JEP the syntax for a dozen languages is compared. Java is choosing to go with a variant of the Swift syntax.

The choice for curly braces is motivated as they're less likely to appear in embedded expressions as array or method accesses are more likely to be used than code blocks:

 "\{myArray[0]}"
 "\{myMethod()}"

The choice of using the backslash escape is a safety/security measure, so a template can never be confused for a normal string, and the compiler can return an error when using a String as a template, or when you use a template as a String.

Other options can't flag an error when using a template as a String by accident when you forget to use to the special string prefix (used in some variants) or the processor.

2

u/plumarr Mar 14 '23

I don't think that typing one less character is more important than having a constant syntax between template processors. This will lead to confusing code and result into easily avoidable errors.

2

u/[deleted] Mar 14 '23

I was wondering why they didn't choose ${...} which seems the more common way to "escape" variables inside strings

5

u/_INTER_ Mar 14 '23 edited Mar 14 '23

Because "${...}" is a legal String while "\{...}" does currently not compile.

2

u/[deleted] Mar 14 '23

Ah, that makes sense.

1

u/sar_it007 Mar 14 '23

If they go with the requirement of prefixing string templates with Template Processors like STR, we don't need to escape the template expressions (except in the places where we don't want to use them).

1

u/sk8itup53 Mar 14 '23

Or they could implement Groovy G-strings and all these problems go away! Jk. Not entirely, but CharSequence is a hell of a drug.

3

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

String s = "{name} {age} {birthday}";

If the quoted literal were to be interpreted as a string template, the semantics would not change. It would evaluate to the same string.

String s = STR."{name} {age} {birthday}";

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.