r/java • • Mar 08 '24

Update on String Templates (JEP 459)

https://mail.openjdk.org/pipermail/amber-spec-experts/2024-March/004010.html
176 Upvotes

188 comments sorted by

View all comments

3

u/DelayLucky Mar 10 '24

Great news on the loss of the processor class!

For any T other than String (such as PreparedStatement), the APIs accepting them are usually not ubiquitous.Updating them to support the template overload should be easy. Even if not, one can add a static PreparedStatement sql(StringTemplate); utility and then use it as:

sendQuery(sql("select ... from \{table}"));

But there will be a ton of methods in the code base that accepts String already and it's sad that you have to choose between two evils, that is: either string concatenation or `String.format()`. It loses like 50% of the convenience that programmer would enjoy.

It'd be nice if the compiler can at least do call-site inference, and interpret "\{foo}" either as a StringTemplate when it's expected, or process it to String when only String is accepted.

For example:

// calls println(String)
println("error: \{errorMessage}");

There is no need for the println API to add overload for StringTemplate because it can do no better than plain string interpolation. The compiler should just translate it to be equivalent to STR."error: {errorMessage}".

While if you try to pass it to an API that does expect StringTemplate, it'll be passed as StringTemplate (even if the API also has overload for String):

// calls sendQuery(StringTemplate)
sendQuery("select & from \{table}");

1

u/pohart Mar 10 '24

I think that it exactly the kind of default processing they were trying to avoid. My call to preparestatement should fail to    Compile until jdbc supports templates

2

u/DelayLucky Mar 10 '24 edited Mar 10 '24

It does fail to compile if the sendQuery() method doesn’t accept String or StringTemplate.

If it accepts String? Well, that means the API is already subject to SQL injection. In other words, the safety is in the API enforcing it by requiring PreparedStatement or StringTemplate. Not in the inability to create strings conveniently, which the programmer already have many ways to do.

The proposal helps good APIs by allowing them to achieve both safety and ergonomics. If it can’t help the bad APIs because they are inherently unsafe, that’s ok.

0

u/[deleted] Mar 10 '24

[deleted]

1

u/DelayLucky Mar 10 '24

I might expect StringTemplate.toString() to return the literal template with the {placeholder}s.

And regardless, requiring users to wrap their nice interpolation syntax inside a ceremony of toString() is quite some clutter considering how streamlined the syntax is otherwise and how common such thing is.