JEP Draft: String Templates (Final)
openjdk.org
openjdk.org
Try this:
STR.”x=\{x} y=\{y} z=\{z}.”
Compared to: “x=“ + x + “ y=“ + y + “ z=“ + z + “.”
A string template incurs an overhead of 3 characters per variable (“\“, “{“, and “}”) plus the leading “STR.”, which is 4 characters. Concatenation incurs an overhead of 4 non-whitespace characters per variable (`”+` and `+”`), and that’s ignoring whitespace. If you have more than 3-4 variables, string templates are shorter.The concatenation example is less readable as well. Have I included whitespace to exactly match the string template example? It’s a little hard to tell at a glance because I have to distinguish what is code whitespace and what’s included in the string.
Also this is about enabling a _system_ of templating, and potentially letting the IDE treat it as such and warn you at compile-time. Small snippets tend to creep all over a codebase. Some use-case that this enables:
* HTML templating React-server-side-style: response.send(HTML_PART."""<div>\{name}</div>"""). Here both the HTML is validated, and the variable is escaped; at compile-time. How do you beat this?
* Query-building: businessFilterClause.add(WHERE_VALIDATE."""PRODUCT_MODEL IN \{authorizedModels}"""). And at compile-time or build-time having it validated against a database schema, and the compatibility of your types.
They are very, very useful, but lots of people said similar things to you about not getting it. Then… they used them, I guess. \{} is not very verbose either, and the use of generic formatters is a really nice addition.
But I don't know what I am missing to not see the breakage. For an existing String literal having a ${...} does not make it into a template that will be processed. You have to explicitly invoke STR. on that to process it as a template. Else if will be just like any other String with no interpolation. STR. is a completely new feature and is illegal in prior versions so I don't see how this breaks compatibility.
Even if you had a variable named STR in existing code, it is illegal to do STR."some str literal".
I guess it is too late now.
The TC39 committee actually come up with an additional proposal for that use case.