[string-templates] Processors with side effects
Jim Laskey
james.laskey at oracle.com
Wed Sep 21 12:54:36 UTC 2022
> On Sep 21, 2022, at 9:22 AM, Tagir Valeev <amaembo at gmail.com> wrote:
>
> 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?
Misuse will come whether we like or not. The plan is to have a "User Guide to String Templates" influence developers toward safe and reasonable usage.
>
> 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}!";
One flavour you didn’t propose was
OUT."Hello \{user}!”;
Or
OUT."Hello %s\{user}!”;
Similar to "import static java.lang.System.out” used by some developers.
No doubt, there will be significant spin off and discussion from the JEP’s proposal.
>
> 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}";
Since the JEP was originally written we’ve done some more research about what SQL template processors might look like. More expert consultation will take place but the current leaning is toward producing PrepareStatements. So the code will be more like;
PreparedStatement stmt = conn."SELECT \{col} FROM \{table}”;
ResultSet rs = stmt.executeQuery();
Or just
ResultSet rs = conn."SELECT \{col} FROM \{table}”.executeQuery();
The advantage here, beside the validation, is that the statement will only be compiled and optimized (using meta data) once per callsite/connection and reused with different values per iteration.
As stated, we will be gathering more direction from the DB community (think separate JEP.)
Cheers,
— Jim
>
> With best regards,
> Tagir Valeev.
More information about the amber-spec-observers
mailing list