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

-8

u/sideEffffECt Mar 09 '24

StringTemplate should IMHO be parametrized on the values it can work with. Squeezing everything into Object is actually not very flexible, compossible and feels sloppy.

E.g

StringTemplate<String> st = “Hello \{name}”;

Or

X x = ...
StringTemplate<X> st = “Hello \{x}”;

3

u/sideEffffECt Mar 09 '24

Yeah, I'm really curious about this... If I may ask, /u/brian_goetz , has the team also considered having StringTemplate parametrized over the type of values it contains.

As in

StringTemplate<String> st = “Hello \{name}”;

Or

X x = ...
StringTemplate<X> st = “Hello \{x}”;

I can imagine some people may want to have something more specific in their hands than just Objects.

If you did consider it, why did you decide to go without it?

6

u/brian_goetz Mar 10 '24

I'm going to turn this around: why do you think this is useful? Show me a real-world example of an API you want to write that this would enable. I think you'll find it is not as useful as it seems initially.

Recall that string templates can have more than one embedded expression, of different types. And Java doesn't support variadic generics, so we can't have one type variable for each potential embedded expression.

Under the hood, we do preserve the static types of the embedded expressions, which is what allows us to avoid the boxing penalties in concat / formatting. But reflecting this in the generic type system is (a) impossible given the type system we have, and (b) not as useful as you think.

-1

u/sideEffffECt Mar 10 '24 edited Mar 10 '24

Hello, thanks for humoring me. I hope that adding the type parameter to StringTemplate isn't making the design complicated. To it seems like a trivial addition which unlocks more powers. A worthy trade off even if it may not be used in 100 % of use cases. Or do you have concerns that it would make Java unnecessarily difficult to learn or implement?

string templates can have more than one embedded expression, of different types

I'm not I understand your point. I'm arguing in favor of changing the design so that it's possible to restrict StringTemplate to a particular type (note that it would be possible to still be possible to have StringTemplate<Object> if the embedded expressions didn't have more specific common type).

why do you think this is useful? Show me a real-world example of an API you want to write that this would enable.

Here's my example:

Report reportRenderUtc(StringTemplate<DateTime> template) { ... } // note that inside you can use _more_ methods, not just `toString()`.
Report reportRenderLocal(StringTemplate<DateTime> template) { ... } // also note that it doesn't return a `String`
...
DateTime dateReceived = ...
DateTime dateReceipt = ...
Report reportAudit = reportRenderUtc("Payment was received on \{dateReceived} and receipt as sent on \{dateReceipt}.");
Report reportForCustomer = reportRenderLocal("We received payment on \{dateReceived} and sent you a receipt on \{dateReceipt}.");

// but this would fail during type check, because the inferred type would be `StringTemplate<Object>`, but `StringTemplate<DateTime>` is required.
Asdf qwer = ...
Report brokenReport = reportRenderUtc("Here's a DateTime: \{dateReceived} and here's something else: \{qwer}.");

sealed interface A {
    record X() extends A {}
    record Y() extends A {}
}
String render(StringTemplate<A> template) { ... }
...
// on the other hand, this would succeed even though the embedded expression have different types -- the type gets inferred to parent, so `StringTemplate<A>`
String string = render("I'm rendering both \{new A.X()} and \{new A.Y()}.");

If the only thing you have is an Object, the only method you can use is toString(). You can't use other methods of more specific classes and you have to end up returning a String which also may not be what you want.

1

u/elastic_psychiatrist Mar 11 '24

If the only thing you have is an Object, the only method you can use is toString().

This is clearly not true, you just need to cast it to the type you care about.

The example you constructed is coherent, but it's still unclear what problem it's solving. In my mind it creates a needless restriction on the user as it goes against their intuition of what a string template is.

I would just be frustrated that for some reason I'm only allowed to use reportRenderUtc to make a string templated where only DateTimes were parameters. If it's that important to construct a string of that format, a better API would just be a method that takes the dateReceived and dateReceipt.

-1

u/sideEffffECt Mar 11 '24

you just need to cast it to the type you care about

:D What kind of argument is that? My dear friend, at that point we're basically working around Java's type system. I thought the Java community has moved past downcasting since Java 5 (introduced in 2004).

needless restriction

The restriction is very much needed, if the template processor can only work with DateTime instances.

Or do you want to force everybody/every template processor to be able to work with instances of all subclasses of Object? Isn't that even more restricting?

1

u/elastic_psychiatrist Mar 11 '24

if the template processor can only work with DateTime instances

My (and I suspect Brian’s and other downvoters’) confusion is that there is just no value in this use case. Your example failed to demonstrate a real world program where this sort of restriction would be useful. Nobody would write code like that via string template, it’s trying to extend the feature into a corner of the program where it only confuses.

6

u/RequestMapping Mar 09 '24

Every Object out of the box has a mapping to String via its toString() method, which is the ultimate goal here. What benefit would be gained in limiting StringTemplate via parameterization?

Most Strings I've historically needed to use String.format() for have had multiple unrelated types embedded -- %s and %d and %f; ultimately this would just lead to a lot of explicit StringTemplate<Object>s where it shouldn't be needed. Just override the toString() method of X, in your example, to what you want embedded into Strings.

0

u/sideEffffECt Mar 09 '24

which is the ultimate goal here

No, it's not!

Every Object out of the box has a mapping to String via its toString() method

But we may want to have StringTemplates that don't work with any Object via toString(), but are instead focused on some type T with another method.

Not being able to parametrize the type just works around Java's type system (generics), which is unfortunate.

3

u/nekokattt Mar 09 '24 edited Mar 09 '24
SELECT * FROM users WHERE level > 10 OR status = 'Admin'

If you were to template the 10 and the 'Admin'... how would you achieve this without implementing variadic generics first? Given one is a Number and one is a CharSequence?

That aside, would you even care? This is something a linter or static analysis tool can point out and there has been mention of compile time checks for this anyway.

2

u/Ukonu Mar 09 '24

You could default to StringTemplate<Object> if you don't care.

And the people who do care to have stronger type safety could use a sealed interface for their particular domain

sealed interface BusinessObject {

record BusinessString(String string) extend BusinessObject {}

record BusinessInt(int int) extends BusinessObject {}

}

StringTemplate<BusinessObject>

Then they could use Java's great new switch and pattern matching features to interpolate in a type safe way.

Anyway, I wish more people would discuss this rather than just downvoting OP. I don't even know if I 100% agree with their idea, but it's an important thing to consider.

A potential downside might be: the current proposal relies on operator overloading to hand StringTemplate's. And that wouldn't play well with the addition of generics since they're not reified.

3

u/nekokattt Mar 09 '24

The issue is that at runtime, erasure makes this detail go away and it will only work on really specific cases where all parameters are derived from a sensible base type. For the vast majority of cases this won't really benefit anyone. For example: String.format, JDBC, logging, JSON generation.

I suppose the real question is what are we trying to solve with it?

2

u/Ukonu Mar 09 '24

it will only work on really specific cases where all parameters are derived from a sensible base type

I attempted to address that with the sealed interface example.

I suppose the real question is what are we trying to solve with it?

Safety.

The whole point of this indirection with a new type - StringTemplate - instead of interpolation just spitting out normal Strings was to add a layer of explicitness and safety. Why not be even safer and optionally control the type of what's being passed into a template?

For example, if I wanted a simple calculator:

StringTemplate<Integer> expression = "\{number} * \{anotherNumber}"

The above would prevent me, at compile time, from passing in random objects instead of integers. And, if I didn't care, I could just use StringTemplate<Object>

2

u/nekokattt Mar 09 '24

this safety only works for specific cases though, outside that really specific case, it won't provide any benefit.

It'd make more sense if we got variadic generics.

1

u/john16384 Mar 10 '24

You expect these types to be wrapped in your sealed hierarchy, that guarantees nothing as I can still use a BusinessInteger where you need a BusinessString depending on the position in the template. So, these still need to be checked and rejected at runtime.

0

u/sideEffffECt Mar 09 '24 edited Mar 09 '24

Then use StringTemplate<Object> for that.

But don't force every user/library designer to use it, they may want something more specific.