[string-templates] Processors with side effects

Tagir Valeev amaembo at gmail.com
Wed Sep 21 12:22:20 UTC 2022


Hello!

I was thinking about how Java beginners may benefit from string
templates. Some teaching materials rely on System.out.printf to
produce formatted output, like

System.out.printf("Hello %s!", user);

With string templates proposal, we can use

System.out.println(FMT."Hello %s\{user}!");

This is not very exciting. But I realised that PrintStream may
implement TemplateProcessor by itself (returning Void or whatever),
and print directly:

System.out."Hello %s\{user}!";

Will such use cases be encouraged, or this should be considered as
misuse of the feature?

Well, for side effect we may still want to specify formatting options,
like whether it should be a concatenation, or formatting, and with
which locale, so probably it would be better to have an intermediate
method (or even field!) that returns a TemplateProcessor:

System.out.printstr."Hello \{user}!";
System.out.printfmt."Hello %s\{user}!";
System.out.printfmt(myLocale)."Hello %s\{user}!";

That said, in "Safely composing and executing database queries"
section of JEP 430, it's assumed that the DB object always produces a
ResultSet. However, in PreparedStatement there's also executeUpdate()
(returning int) and execute() (returning boolean) which might be
sometimes more appropriate. So a level of indirection between
connection and template processor is probably necessary:

ResultSet resultSet = conn.query()."SELECT \{col} FROM \{table}";
int count = conn.update()."UPDATE \{table} SET \{col} = \{value}";

With best regards,
Tagir Valeev.


More information about the amber-spec-observers mailing list