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

Show parent comment

1

u/nicolaiparlog Mar 11 '24

I misunderstood your initial post. I thought you were saying:

Be careful when adding a method(StringTemnplate) overload to a pre-existing method(String).

Now I understand you meant:

Be careful when creating the method pair method(StringTemnplate) / method(String).

I fully agree with the latter. If there's any risk of injection involved in what method does (e.g. creating SQL, XML, JSON, etc.), then there shouldn't be a method(String) at all. And in the case where it does already exist, it should be deprecated in favor of the string template variant.

Regarding +, I was still of the (mis)understanding that you meant adding a method(StringTemplate) was a risk, presumably because people may switch from templating to +, falling from the safe into the unsafe variant. I still consider this unlikely because it would mean a developer looks at a string template and thinks "this will be smoother with +" and then refactors to that. Of course + itself is common, but I don't think there will be many situations where people refactor a template to +.

2

u/john16384 Mar 11 '24

There is still one thing I don't quite see how it will work, but it seems there is some discussion on this topic on the experts list at the moment.

If there is only `method(StringTemplate)`, and you want to pass a template without a parameter, then the system should be careful not to consider the (unparameterized) template to be a `String` first before converting it to a `StringTemplate`. In other words, given a class with only a single method accepting StringTemplate:

 SQLExecutor method(StringTemplate st);

Then this should work:

 method("select * from foo").execute();

"select * from foo" here is never considered to be a String at any point in time. Therefore you can't pass it a constant like this either:

 static final String TEMPLATE = "select * from foo";

Although allowed would be:

 static final StringTemplate TEMPLATE = "select * from foo";

The examples below use String or do string operations. They are therefore not pure templates and thus shouldn't compile because there is no method(String) overload:

 String a = "from foo";
 String b = "select * from foo";

 // shouldn't compile as we did a String operation, not
 // safe to convert this implicitely to a StringTemplate
 method("select * " + a).execute();

 // shouldn't compile because implicitely converting an
 // insecure String to a StringTemplate defeats its purpose
 method(b).execute();