[string-templates] Accidental use of StringTemplate instead of string
Victor Nazarov
asviraspossible at gmail.com
Fri Oct 21 13:05:07 UTC 2022
Hello!
I think one suggestion that fixes stated problems was already proposed
before and I heard no arguments against going this route.
On Thu, Oct 20, 2022 at 6:30 PM Jim Laskey <james.laskey at oracle.com> wrote:
> Tagir,
>
> > On Oct 20, 2022, at 11:44 AM, Tagir Valeev <amaembo at gmail.com> wrote:
> >
> > Hello!
> >
> > As stated in JEP 430 text, the string template is a well-formed
> > expression of StringTemplate type. Also, toString() method of
> > StringTemplate prints a debug-friendly representation like
> > [fragments](values) which is not intended for actual use. I can
> > imagine that the following mistake may happen often, especially by
> > inexperienced developers, or developers with background in other
> > languages:
> >
> > int x = 10, y = 20;
> > System.out.println("\{x} plus \{y} equals \{x + y}");
> >
> > Output expected by programmer: 10 plus 20 equals 30
> > Actual output (successfully compilable): ["", " plus ", " equals ",
> > ""](10, 20, 30)
> >
> > As an IDE vendor, we can surely provide an inspection for some
> > well-known methods like PrintStream#println(Object) with a quick-fix
> > to add a STR. prefix. However, not everybody uses IDEs. Probably the
> > language itself could help here somehow?
> <snip>
>
> <snip>
>
> The problem here is we can’t have it both ways. If we treat it “like a
> string” in these cases then user will expect it to be a “like a string”
> everywhere.
>
> Another option would have been to make StringTemplate::toString generate
> UnsupportedOperationException, which would cause havoc for debuggers.
>
> As always, we are open to suggestions, but I think this is one of those
> cases where users “learn” to do the right thing.
>
>
One suggestion that fixes this problem is to forbid bare template strings
without policy-prefixes and instead introduce some policy that returns
TemplateString itself.
````
StringTemplate tmpl = TMPL."\{x} plus \{y} equals \{x + y}" ;
String s1 = tmpl.apply(STR);
String s2 = STR."\{x} plus \{y} equals \{x + y}";
assertEquals(s1, s2);
````
In this world the following can be observed:
````
System.out.println(STR."\{x} plus \{y} equals \{x + y}"); // Prints "10
plus 20 equals 30"
System.out.println(TMPL."\{x} plus \{y} equals \{x + y}"); // Prints
"StringTemplate{segments = ["", " plus ", " equals "], values = [10, 20,
30]}"
System.out.println("\{x} plus \{y} equals \{x + y}"); // COMPILATION
ERROR: error: unrecognized escape sequence '\{', policy is required for
template strings
````
--
Victor Nazarov
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-spec-observers/attachments/20221021/66bd2584/attachment.htm>
More information about the amber-spec-observers
mailing list