[string-templates] Accidental use of StringTemplate instead of string
Brian Goetz
brian.goetz at oracle.com
Thu Oct 20 16:32:00 UTC 2022
The goal here is to help users learn, through feedback, that a
StringTemplate is not a string, but a recipe for one, and if you want to
get that string, you have to cook it.
One way to help that along might be to have the toString look more like
that of a record:
StringTemplate{ segments = [ blah blah ], values = [ blah blah ] }
which will reinforce that you printed out a recipe and not the thing it
describes.
On 10/20/2022 10:44 AM, Tagir Valeev 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? E.g., uses of StringTemplate
> where the Object type is expected might trigger a warning. This is
> similar to array toString(), and every static analyzer has an
> inspection about this. Honestly, I don't know a good solution but I
> feel that it's not a good idea to introduce a new error-prone
> construct, which is compilable and runnable, could be mistakenly used
> and doesn't make sense.
>
> As we are here, is it planned to specify StringTemplate equals and
> hashCode? It's naturally a tuple of (fragments, values) lists, so
> equals and hashCode could be defined. Also, current draft [1] suggests
> that this is a non-sealed interface. Is it really intended to allow
> third-party implementations?
>
> Sorry if these questions were already discussed, I might skip some
> discussions. I would be happy to see the pointers to previous
> discussions.
>
> With best regards,
> Tagir Valeev
>
> [1]http://cr.openjdk.java.net/~jlaskey/templates/docs/api/java.base/java/lang/template/StringTemplate.html
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-spec-observers/attachments/20221020/42fd2147/attachment-0001.htm>
More information about the amber-spec-observers
mailing list