192 points · by za3faran · 3y ago · 237 comments
This isn't exactly what I laid out, of course, but I think it achieves the goals I was looking for, which is the real issue. In particular, having the default string interpolation be prefixed with "STR." is enough for linters and scanners to get a chew on (it's easy by scanner standards to track that a STR.-interpolated string got fed into a database query), and for code reviewers to develop an instinct to look at such interpolations more closely than they need to for a DB. interpolation. An STR annotation is not technically necessary for the former, if it were simply the default, but it is a big deal for the latter. I want people to have a chance to notice and think about their use of bare string interpolation for at least a fraction of a second as they type "STR." (or autocomplete it or whatever).
This does put a heavy burden on the libraries to implement it correctly, but if they do it's even safer than what I was thinking.
One thing though: Please for the love of the internet, for those of you writing interpolators, DO NOT write an interpolator that picks apart the values passed in through a \{ ... } and starts instantiating arbitrary classes via Java reflection. Just stay away from that entirely, OK?
Still props for the Java team for doing a good job.
Another example being overengineered streams. Parallel streams look really cool as a demo, but have been proven dangerous in their default configuration (they can exhaust the default thread pool).
Indeed. Please no more log4shell hell
Now we just need to combine this, the constants work that has been done over the last few years, and regular expressions, to make the regexp API so much nicer.
Over the 9 languages mentioned: 5 languages (inc. JVM ones like groovy and kotlin) are using `$`, 1 language (swift) is using `\`.
`\` is a pain to type on many keyboard layouts -- actually most but the US one. It seemed to me that `$` would have been a much more "conventional" choice.
This really makes me sad. It looks like the choice was made on purpose to be different.
Then being walled in by backwards compatibility
It's actually made worse because { and } also need special combinations.
To type \{X} I need to press
(⌥ + ⌘ + 7) (SHIFT + ⌥ + 8) X (SHIFT + ⌥ + 9)
I know this is something we need to live with due to historical reasons, but I would prefer that new syntax is made simpler.The ergonomic of \{X} is exactly the same on it as on my carbon x1, my keychron tls and four other keyboards I happen to have in my drawer.
Are You using modified Apple II like Rebecca Heineman or some kind of super small keyboard that looks like someone forgot to put all the keys in :) ?
Either way its on you not Java.
(Dont take this wrong way - this is an honest question - here in Poland almost all keyboard are backslash friendly and I would live to knowe where this is not the case)
So the Mac issue applies to 4 countries in the Nordics at least. Please note that traditional PC keyboards use a different layout for some characters and may in some cases have a dedicated key for backslash too, in case you Google Norwegian keyboards. It's one of those Mac vs PC things we are used to.
Before anyone starts suggesting connecting a PC keyboard to my MacBook Pro, keep in mind that I use the built in keyboard almost 50% of the time and having two different key mappings is a hassle
Regarding backslashes and other special characters, I never said it's on Java specifically, but the US centric culture in general. K&R used curly brackets when they designed C because they fit the US teletype character set of the 60s/70s, but that doesn't mean it's the best choice today.
I'm not suggesting we use special unicode symbols like arrows and emojis, but just pause for a minute and look beyond the US keyboard and see if we can find a solution that also works ergonomically for at least some non-US countries.
I press ⌥ + 8 for square brackets and SHIFT + 8 for parentheses.
It's probably not possible to find better alternatives for Mac keyboards that could be used for a language based on Lisp syntax.
The Mac keyboard simply doesn't have any dedicated keys that are not used for normal text, except for "@". For some unknown reason, they have a dedicated key for umlauts ("¨") that we don't use in our language. I guess I could map it to brackets, but SHIFT + UMLAUT returns a "^" that is often used in regexps and I don't want to lose that.
Windows keyboards has a different layout that is slightly more programmer friendly if you have a full sized keyboard. They do have a backslash key but lack the dedicated "@" key. Windows needs a dedicated backslash due to the file paths, unlike Mac. It is an acceptable tradeoff for Mac users, as non-developers are more likely to use "@" than "\".
Let's just say that there is a reason why I love my IDE that will automatically add closing curly brackets when it detects a block.
> For the syntax of embedded expressions we considered using ${...}, but that would require a tag on string templates (either a prefix or a delimiter other than ") to avoid conflicts with legacy code.
Can't the template processor expression itself function as the tag? Is STR."..." already legal now?
String info = "My name is \{name}.";
to be a compile-time error because it is missing the template processor (e.g. the `STR.` prefix). Since existing code like String info = "My name is ${name}.";
is valid, they can’t use that syntax, or any other syntax that is currently allowed, as otherwise they would lose the ability to make it an error.———
However, what they could have done instead is to use a syntax like
String info = "My name is "(name)".";
i.e. place the interpolated expressions outside of string literals. Slightly longer, but maybe more readable and typable, and currently invalid syntax. (The parentheses would be mandatory.)It seems just as difficult to remember/useless as lambda expressions that look fine as vanity one-line expressions and then get difficult to write for most programmers.
We don't really need vanity innovation in the Java world. I would have asked for priority on the FX replacement to Swing, or support for running on ESP32 IoT devices as replacement to the Arduino platform.
Instead we get some weird looking syntax for what is basically a non-problem.
¯\_(ツ)_/¯
Which are entirely unrelated projects to this one with very different engineers working on it. Those are easily parallelized, if you will. I don’t see why having progress completely elsewhere by different people is detrimental to these goals at all.
If any of you design a language or a DSL, please, please - avoid the backslash - for the reasons stated above. Hard to type, introduces unseen problems, most will hate it. It (backslash) is unbecoming, of anything elegant.
In current Java you would have to escape \, so only “\\{val}” could have existed before.
You want the lexer to be able to make the difference between a constant string and a template string and you want users to be able to read the code.
This JEP solves the former not the later.
FromSql($"EXECUTE dbo.GetMostPopularBlogsForUser {user}")
https://learn.microsoft.com/en-us/ef/core/querying/sql-queri...
…and they also always default to formatting with CurrentCulture instead of InvarintCulture. Apparently this was by-design as interpolated strings were never originally intended for generating machine-readable strings.
Finally, there’s no way to perform common “mini-templating” with a FormattableString, such as repeating regions, show/hide regions within a string, or little things like inflection (e.g. rendering “{0:N} items” or “{0:N0} item” when arg0 is 1 or not.
I’m happy to see Java (finally) gain a similar feature, but it, like C#,s, seems… limited in its abilities.
On the other hand, Java's GCs, JIT compilers, and observability features are more sophisticated than .NET's. We like adding stuff to our runtime, while C# likes adding stuff to the language.
That would cause a compilation error. `DbSet<TEntity>.FromSql(FormattableString sql)` [0] does not have a string overload. Therefore, if a user assigned the interpolated string to a SQL query to a `var` beforehand, then there would be an implicit conversion to a `string` [1] which will be a type mismatch for the `FromSql` call. The user would have to assign the interpolated string to a `FormattableString` instead of `var` for the program to compile. There is also no implicit conversion for a `string` to a `FormattableString`.
There is a `DbSet<TEntity>.FromSqlRaw(string sql, params object[] parameters)` [2] method that explicitly documents that it is vulnerable to SQL injection.
> You-the-user can make C#'s safe, you-the-library-developer can make Java's safe.
You-the-library-developer can make C# safe.
[0] https://learn.microsoft.com/en-us/dotnet/api/microsoft.entit...
[1] https://learn.microsoft.com/en-us/dotnet/csharp/language-ref...
[2] https://learn.microsoft.com/en-us/dotnet/api/microsoft.entit...
The one major difference is that, because Scala has macros and typeclasses, it can turn malformed interpolations for things like JSON or SQL into compile-time errors instead of runtime errors.
So we can have this super powerful, extensible string interpolation system using never-before-seen syntax as a language feature, not a standard library extension, but not unsigned integers?
I'll echo what other commenters have said: This looks powerful but ugly. I'll add to it by pointing out that "powerful but ugly" is what we've already got. So we gain the ability to move format arguments inline with the string contents if we're willing to use the `STR."\{}"` syntax? That seems like a lateral move.
The extensibility and power of string templates were a requirement; security experts quite simply vetoed adding string interpolation as it's just too dangerous, especially in server-side software, where Java is mostly used.
As to `STR.` -- which you won't need to use most of the time -- see my other comment: https://news.ycombinator.com/item?id=35013470
You (collectively) have this wrong; C, C++, C#, Rust, Go, et al. have it right. As long as we're just stating our beliefs outright instead of justifying them, that is. (That's not a request to justify your opinion; I'm sure it's been argued to death already.)
> security experts quite simply vetoed adding string interpolation as it's just too dangerous
Laughable. In an alternate universe where it didn't already exist, this could have been a JEP for StringBuilder and they would have vetoed that too.
> As to `STR.` -- which you won't need to use most of the time
Except for when you're trying to... make a String? Which is what ~everybody who ever asked for string interpolation in Java wanted to do?
What year would you estimate it will be when, at the average Java job, I can expect that most of the library APIs available to me which were often invoked with the form `func(String.format(...))` will have similar APIs that behave as JEP 430 template processors? Maybe after it's been full release for 3 years? 2, optimistically? Because during those years, in order to use this thing at all, people will be using `STR."\{}"`
As to your other points, like I explained to someone else here, even three decades of experience evolving a language that's achieved a measure of success is still no guarantee that every feature will work well, which is why most big new features, string templates included, are first released as preview (i.e. a feature that may change). That allows us to test our hypotheses against the problems people actually encounter rather than those we or others may speculate they'd encounter, and adjust the feature accordingly before it is finalised. To the best of my knowledge, all preview features have undergone some adjustment before becoming permanent, but usually the changes required were relatively small.
Also, we try to think more long-term, because in ten years no one is going to care or even remember if a feature arrived five or seven years prior.
So this feature has to wait for primitive classes, where it can be as simple as
primitive class unsigned {
int value;
}
(Though it would need operator overloading to be used as a+b, which is not really liked in Java designer niches (with many good reasons against it) :D )What disadvantages do unsigned ints have?
Unsigned types are also primarily useful when the types have very few bits -- like in bitfields -- but Java doesn't have those, and the uses of unsigned types in Java would be mostly restricted to interaction with native code and hardware, that not many do and for which we have other solutions. So some very dangerous disadvantages and not many advantages for a language like Java.
[1]: https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p14...
If anything, Kotlin is probably ahead of Scala now, adoption wise.
String name = "Joan";
String info = STR."My name is \{name}";
I don't love it, to be honest. `STR` is a bit much. Requiring the \ for the first but not second brace. I want string templates in Java, but this feels ugly. log.info."x: \{x}";
and similarly for other uses that don't produce strings but JSON, SQL etc. So STR would only be used -- hopefully rarely -- for old APIs that have not determined their own template interpretation strategy and only accept String.The use of the backslash is important to distinguish between a string literal and a template literal because "x: \{x}" is not a valid string literal today. Swift uses \(...), BTW.
If that's the hope, why have it automatically imported statically for all files?
Of course, $ is ideal because it's already everywhere and familiar.
I guess a typographer of a font designer would be helpful to find a good solution.
No, it is the escape symbol and works just like the escape symbol because it is the escape symbol.
The escape symbol \ means that whatever follows should not be treated literally but interpreted in some special way. So "\n" means "not the letter n but rather a newline", and "\u1234" means "not the letter u followed by the digits 1, 2, 3, 4, but rather the unicode character U+1234". And in exactly the same way, "\{...}" means "not the opening curly brace followed by some stuff and then a closing curly brace, but rather special semantics for the expression (not variable) within the curly braces".
> Of course, $ is ideal because it's already everywhere and familiar.
It is already everywhere, including in existing Java strings in existing Java code, and the semantics of that existing code must not change. The very fact that it is already everywhere means that it is not ideal in the context of retrofitting this feature onto Java.
What is the method call ? Agree with grandparent this looks too inconsistent for Java
STR.format(“”) would be more Java with import as Alias
StringTemplate t = RAW.”My name is \{name}”;
STR.process(t)I understand Java has a backwards compatibility issue that Kotlin does not though, which would make breaking changes to all the hard-coded strings containing `$` that would now need to be escaped. This is discussed in the JEP.
Backwards compatibility - simultaneously Java's strongest and weakest asset.
But to those who ever wish to have another language that's as successful as Java, I would suggest studying what it is that Java values, which might explain why is it that almost twenty years after having died at the hands PHP, and some years later being finished off again for good measure by Ruby, and then had its coffin nailed shut by Node, Java is still more lively than its supposed heirs.
A few circumstantial examples. If you look at the Matrix SDKs and implementations (https://matrix.org/docs/projects/try-matrix-now/), Java's presence is sorely lacking. The initial server implementation was written in Python of all things and the rewrite in Go. This is baffling as a Java implementation seems like a no-brainer to me.
In addition to working for a variety of corporations, I have also done some work for academic institutions, specifically in the library space. They have a lot of old tools from the 2000-2010ish range that are predominantly in Java. However, now, these institutions are primarily using Python and Javascript, and are even struggling to find Java developers to maintain their old infrastructure.
> To aid refactoring, double-quote characters can be used inside embedded expressions without escaping them as \".
I would expect for consistency that \"{expression}\" outputs an expression and \"\{expression}\" would not.
I don’t get your examples. The JEP meant that they can be used inside not, in-between, so:
\{ “a” + “b” + 3 }
could work.I maintain the lit-html template library which uses JavaScript tagged template literals to embed HTML in JS.
A key feature of JS template literals is that the tag receives the string fragments and values separately, and can return non-string results. This means we can escape values and validate template structure to prevent XSS attacks.
This approach in Java should lead to a lot more lightweight but safe DSL embeddings.
(I don't love the syntax, but... it's Java)
edit: the other critical feature of JS tagged template literals, that I'm not sure this has, is referential equality of the template strings passed to the tag function across multiple invocations.
This is required to be able to do one-time preparation work on a template and re-use that with different sets of values. Think a `SQL.` template processor that turns the strings into a prepared statement once and re-uses that for each query with different parameters.
edit 2: awesome, it does:
The fragments() of a StringTemplate are constant across all evaluations of a template expression, while values() is computed fresh for each evaluation. For example:In swift, there's some nice quasi-laziness you can add to function parameters, so that (say) a logging function that can fully skip evaluating a string sent to it with the `@autoclosure` syntax:
func log(message: @autoclosure () -> String, level: Level = .info) {
guard level >= configuredLevel else {
return
}
actuallyLog(message())
}
And call it like: log(message: "User is \(someExpensiveFunction(user))", level: .debug)
And if the configured log level does not include debug messages, `someExpensiveFunction(user)` doesn't get called.This works because @autoclosure lets you take a parameter that is "function returning String", but callers can just pretend they're passing it a String, without having to decorate it in a function. The compiled code will turn it into a closure behind the scenes, and thus it'll be evaluated lazily.
Not sure if there's any way to do something like this in Java with this proposal...
void log(Supplier<? extends String> messageSupplier);
log(() -> log.info"User is \{someExpensiveFunction(user)}");
The pattern of using Supplier to provide a lazy argument is pretty well-established afaict. new Object() { public String toString() { return
<actual expression here>
; } }
You can wrap that into a helper function that takes a lambda, so you can write STR."\{lazy(() -> <actual expression here>)}" Supplier<T>Since the string template interface is untyped (parameters are arbitrary Objects), having case distinctions based on the type parameter is fiddly. What if you pass an instance of a class that has a genuine toString() but also happens to implement Supplier<Foo> for some reason? Or if you pass a Supplier<Supplier<Foo>>, will it recurse? What if you pass a Callable or a Future? Will those work as well? This only creates the opportunity for opaque “magic” behavior.
Unlike many here I do like the choice of \{}, although personally I would have preferred \() like Swift.
I can’t wait.
Since class names start with a capital it fits. At least I think that was the reasoning they stated.
Why not Str? Perhaps they thought this would be less likely in existing code. I’m not sure I don’t think they mentioned the reason.
They could have also just put it on the String class. Again I didn’t see a discussion as to why that wasn’t suggested.
String.”Hello, \{name}.”
Seems like it would have been reasonable. But this is a proposal so it may change before officially joining the JDK.
StringTemplate t = RAW.”Hello, \{name}.”
STR.process(t);The syntactic sugar should be a feature then used used here rather than invent a special cased syntax for a feature
just use a conventional calling syntax. Java is a fairly verbose language with a highly verbose popular patterns
final var str = STR; StringProcessor INTER = (StringTemplate st) -> {
String placeHolder = "•";
String stencil = String.join(placeHolder, fragments);
for (Object value : st.values()) {
String v = String.valueOf(value);
stencil = stencil.replaceFirst(placeHolder, v);
}
return stencil;
};
‘fragments’ should be ‘st.fragments()’ here I believe to make it compile. String name = "Joan";
PreparedStatement query = @SQL "select * from users where firstname = \{name}";It would be more readable to have all the values in their respective place in the SQL string, rather than have a bunch of question marks followed by all the values bunched together at the end. e.g. this:
PreparedStatement query = SQL."SELECT * FROM users WHERE firstname=\{firstName} and lastname=\{lastName} and email=\{email}";
rather than: query = client.prepare("SELECT * FROM users WHERE firstname=? and lastname=? and email=?",
firstName, lastName, email);In addition to that, not every database needs prepared statements for safe queries e.g. "Parametrized queries" in PostgreSQL (available in libpq as PQExecParams and exposed in many other higher level languages)
You apparently didn't learn any lesson from PHP. The impossibility of the database engine to distinguish a code from a data character is what lead to SQL injections in the first place.
It doesn't matter whether you replace the template expression with a ? or with $1. The database receives the parameters outside the SQL query and treats them as user input either way.
Scala:
val info = s"My name is $name"
Why does Java ALWAYS use unnecessary verbosity? I don’t get it. They’ve had years to learn from succinct languages. val info = "My name is $name"
All strings are templatable in Kotlin. No need to have different types of syntax for that. What purpose does this s or STR. prefix serve serve? Seems completely redundant to me to have that.I'm mostly developing in Kotlin btw., but usually when Java introduces its take on a feature that has existed for a while in other languages, they improve on it. One such example: handling whitespace/indentation in multi-line strings in Kotlin vs Java. In Kotlin you usually have to call .trimIndent(), in Java the defaults are sane so you don't have to.
And I indeed missed the bit about a pluggable template engine. Just one question related to that: why? I don't see the big use case for this. Maybe a bit less flexibility and a more sane syntax would be better?
Java: var info = STR."My price is $\{price}_";
Scala: val info = s"My price is $$${price}_"
Anonther feature I would like to see added is operator overloading so we can do away with ugly method calls for BigDecimal arithemetic.
> STR is a public static final field that is automatically imported in every Java source file.
public static final ValidationProcessor $ = ….STR;
$.“My name is \{name}“First, the lesson of Log4Shell have not been learnt. Allowing more libraries to do formatting, what can go wrong ?
And String.format() is slow because every values are boxed. This JEP repeats the same mistake with the templates.
As to boxing, the built-in template processors, STR and FMT, don't do boxing (they use MethodHandle mechanisms similar to those used by lambdas) -- FMT is ~40x faster than String.format, I'm told -- but that capability hasn't been exposed as an API yet. As with other features, we try exposing basic usages first, and more sophisticated ones later.
I don't have the same definition of security (i've read the JEP). Unlike TypeScript, you can not type the template values.
> built-in template processors, STR and FMT, don't do boxing ...
but all the others user-defined template processors (think a logger) are second class citizens and will do boxing.
Efficient String interpolation is hard without macros, that's why it's a macro in Rust.
This JEP tries to solve a harder problem, user defined template processors but do not provide the tool to make them efficient and never will. Are you suggesting that there is a JEP about macros in the making ?
Not quite. It is hard without some compile-time computation, but what's compile-time for languages relying on AOT compilation (and requires macros or compile-time introspection as in Zig), happens at runtime in Java because that's when the optimising compilation happens, and Java has a user-exposed mechanism for defining call-sites (https://docs.oracle.com/en/java/javase/19/docs/api/java.base...). It's just that, as with most of our new features, we expose a simple API first and a sophisticated API later. No need for macros.