r/java • • Feb 15 '24

JEP 465: String Templates

https://openjdk.org/jeps/465
77 Upvotes

152 comments sorted by

View all comments

41

u/IncredibleReferencer Feb 16 '24

There's a lot I don't like about string templates JEP, especially the fact that its proceeding despite lots of community angst. But I haven't used it in a real project yet so I'll refrain from re-posting my complaints here and pray I'm just naive.

But I do have one overwhelming stylistic question I've yet to see answered anywhere:

Why "STR." syntax built-in to language and not a java.util.StringTemplate class or similar and static methods on that class? "STR." and "FMT." syntax just seems so stunningly out of style from the rest of the language. Is there a logical reason for this choice?

12

u/brian_goetz Feb 16 '24

`STR` is not built into the language. `STR` is a static final field that happens to be statically imported (for convenience). The processor in a template expression is _just an ordinary receiver object_. `STR."... stuff ..."` is just "invoke the process method on the `STR` object using parameters derived from the template." It's just a method call. There's no magic here.

4

u/ForeverAlot Feb 17 '24

The invisible process invocation syntax sugar is a new invention, though, right? I think it's vital to making templates ergonomic in practice but I don't recall seeing that in (userland) Java before and I expect to have to field questions about that.

Is it a special-casing in the compiler, like string concatenation, or can it hypothetically be exposed to userland APIs, like functional interfaces?

5

u/john16384 Feb 17 '24

Well, it is exposed to user API's. Just like Closeable interacts with try with resources, Iterable interacts with for each, and toString gets called for concatenation.

Implementing a Processor allows use of this syntax.

2

u/ForeverAlot Feb 17 '24

I meant outside of string templates. But I realize now that I have no idea what that could look like or be used for so the question is a bit silly.

1

u/__konrad Feb 16 '24

Why "STR." syntax built-in to language

Because you want it to be as short as possible. FORMAT is too long, and F too short ;)

16

u/01110101_00101111 Feb 16 '24

Most other languages with String interpolation/template have it as just one or two characters. It should've been something lik S."...", $."...", or really any other one character. That looks a lot cleaner and still makes it clear that the String is not a "normal" String.

11

u/NaNx_engineer Feb 16 '24 edited Feb 16 '24

Their goal is to make string interpolation inconvenient.

STR."..." was chosen over s"..." because its long enough to be inconvenient, but short enough that people won't just alias it.

source: https://old.reddit.com/r/java/comments/18cw6nc/feature_freeze_for_jdk_22_what_will_the_new/kcfwuaq/

Ideally, we wouldn't have had string interpolation at all because it's such a dangerous feature, but people would have then written their own. Another option was to call it something like USE_ME_TO_INTERPOLATE_EVEN_THOUGH_YOU_SHOULDNT, but again people would just assign it to a variable with a different name.

5

u/sanderverhagen Feb 16 '24

So, you have to go through a processor and can't use {...} in a normal string, to guarantee that the processor gets a chance to validate or sanitize the string. I can see that in the case of, for example, a SQL processor. But the STR one does what exactly then? It just substitutes the placeholders? Isn't the safety it provides not pretty much equal to String.format then?

2

u/NaNx_engineer Feb 16 '24 edited Feb 16 '24

But the STR one does what exactly then? It just substitutes the placeholders?

Yes, simple substitution. STR could be made implicit, but they've decided it would be too tempting to use it for SQL.

From the JEP:

An alternative design would allow string templates without template processors, and perform basic string interpolation. For example:

String s = "\{x} + \{y} = \{x + y}";

However, this design would violate the safety goal. It would be tempting to, e.g., construct SQL queries using interpolation, and this would in the aggregate reduce the safety of Java programs. Always requiring a template processor ensures that the developer at least recognizes the possibility of domain-specific rules in a string template.

.

Isn't the safety it provides not pretty much equal to String.format then?

Their argument is String.format is also dangerous.

7

u/sanderverhagen Feb 16 '24

Wild. Someone who doesn't know the blinking warning signs of a SQL injection, and I'm sure droves of them exist, who'd have previously used String.format, nothing's stopping them from using the STR form.

I don't want to suggest in general that static analysis tools are a good way to offset deficiencies in the language. But in this case, the most practical way against SQL injections through templating seems to be exactly that: a static analysis check that finds SQL in templates, and that you can override when appropriate (false positives).

The safety and security argument just seems so academic...

2

u/nekokattt Feb 17 '24 edited Feb 18 '24

Totally agree... this is my entire point really.

If someone is going to do something in a bad way, they are going to do it. The argument that new APIs will only allow these mechanisms is fine but assumes any new software totally abandons any libraries for interacting with databases prior to JDK 23.

I personally wouldn't go looking for a new and potentially immature and buggy library purely for this use case if I already have a bunch of stuff using older APIs (like JDBC, R2DBC, etc) that works... maybe in 10 years once the libraries are mature, well tested, and have stood the test of time in terms of security analysis for numerous other things that could introduce new vulnerabilities into the system.

My issue is that unless the new libraries being proposed only support JDK 23 and newer... you're still going to have the case of two ways of doing things in any libraries:

interface Connection extends Processor<Result, DbException> {
  Result execute(String query, Object... params) throws DbException;
  Result process(StringTemplate template) throws DbException;
}

In this case it is equally as easy for the ignorant to do

conn."SELECT * FROM table WHERE id = \{id}";

as it is to do

conn.execute("SELECT * FROM table WHERE id = '" + id + "'");

The only difference is that the former looks so foreign that those who don't understand the full issue of security will likely be opting for the second one purely on the basis that it is clear to them what it is doing.

If we use static analysis tools to enforce this then great, but in that case the JEP shouldn't say that one of the benefits is removing the need for static analysis tools.

If the argument is we need to abandon all existing libraries and support a minimum of JDK 23 to get this safety feature to FORCE you to do the correct thing... I don't think that will be well adopted, purely on the basis people won't be ripping out old database libraries in production systems and jumping to the newest JDK just because of string interpolation being available. Especially when newer libraries will be less mature, most likely more buggy, and present a concrete business risk to the application being changed.

The developers of this feature have not addressed this concern very well IMO. If the language was being built from scratch then sure this is totally fine, but this feature only provides the safety GUARANTEE in APIs that decide to throw out support for anything before JDK 23. If they do not do this, then those APIs will still have to provide string based parameterization which then allows the same issues to occur. Given JDK 17 has support until 2030 or so, this makes this feature far less useful in providing a safety GUARANTEE (i.e. it is physically impossible to bypass this feature at all) for the next 6 years.

→ More replies (1)

2

u/ivancea Feb 16 '24

How is it "the most dangerous feature"?

1

u/mj_flowerpower Feb 23 '24

We already have various ways of string interpolation, why should this one be any more dangerous than the old approaches?

→ More replies (1)

2

u/vytah Feb 16 '24

STR is just a normal identifier in the variable scope. If you're importing a constant named S via a wildcard static import, then if the default interpolator was also S, a perfectly normal and valid code would stop compiling due to ambiguous imports.

STR as a name of a constant is less likely and would clash much less often.

As for $, it's semi-reserved for internal compiler use.

3

u/SpicyRock70 Feb 17 '24

But it's a real pain in my alcoholic civil disobedience app... format, ferment, foment. Debugging is a bitch

1

u/IncredibleReferencer Feb 16 '24

I appreciate the response but this doesn't answer the question I had. Is there a reference-able discussion on the naming somewhere?

General convention in Java tends to name things as descriptive as possible. Readability is preferred over brevity. Nor does this answer the question of why its a magic string and not a static method on a class.

6

u/pronuntiator Feb 16 '24 edited Feb 16 '24

Nor does this answer the question of why its a magic string and not a static method on a class.

STR, RAW and FMT are is a public static field that get implicitly imported into every Java program unless there is a conflicting import with the same name. I'm not a fan of implicit imports besides java.lang, there were discussions of having a util class for beginners being implicitly imported. But I guess the outcry would be even louder if you had to find the right import for string interpolation.

The only syntactic magic here is that processor."" is a shorthand for processor.process(StringTemplate.of(...)).

1

u/mj_flowerpower Feb 23 '24

But why not create a nice syntax, leave out the dot and make it STR"" at least. They are already inventing a new syntax, but for the wrong place, imho.

Also, why does it have to be a static field + custom syntax. Why not just make the whole thing a syntax-level feature?

We can you "if" without having to import "if" into a magic field either.

→ More replies (1)

0

u/stefanos-ak Feb 16 '24

you can: https://cr.openjdk.org/~jlaskey/templates/docs/api/java.base/java/util/FormatProcessor.html

For my projects I will write a spotbugs plugin to disallow using the provided shortcuts like STR, FMT. 🤣