10 ms·
Java Feature Spotlight: Text Blocks
- dudul 6y agoI don't hate Java. It was my 2nd or 3rd language, and the one I first used professionally. But O-M-G, this feature exists in most mainstream language and has for the past decade at least. This is nuts to me how behind Java is. Is it only due to the backward compatibility? Or is there some crazy red tapping every time something is added?
- fenk85 6y agoYeh if you want to use Java from 10 years from now minus alot of garbage and questionable decisions in Java look into Kotlin which is also 100% interoperable with Java libraries so you can lean on decades of code. We switched from Java+Spring to Kotlin+Spring and havent looked back in a few years now, for backend microservices
- vips7L 6y agoJava doesn't add features unless they're absolutely sure they want to support it for eternity and for something like text blocks why take the risk unless you're absolutely sure? Text blocks aren't something I see myself even using frequently.
- stickfigure 6y agoI whine about (lack of) text blocks every day when editing multiline SQL statements. The extra quotes and +s and spaces are really irritating.
- bootlooped 6y agoAt a previous job we started using Groovey files to store queries because of this.
- vips7L 6y agoMaybe I'm lucky but this is infrequent for me. There are better tools for most queries: https://ebean.io/docs/query/background/typesafe https://ebean.io/docs/query/background/typesafe https://www.jooq.org/ https://www.jooq.org/ http://www.querydsl.com/ http://www.querydsl.com/ https://scala-slick.org/ https://scala-slick.org/
- noisem4ker 6y agoIf you're using JPA, add the Criteria API to the list.
- stickfigure 6y agoI find these tools only work well for simple queries. For anything complicated, you spend N units of time figuring out how to make the query, then 4N units of time figuring out how to represent it in the metalanguage (often hacking around it with custom functions and operators). They are especially bad with exotic operators like postgres' JSONB columns. I ended up ripping jooq out of an app over this. There's an argument that they bring type safety to SQL, but Intellij actually validates your string literal SQL against the schema, so the benefit is marginal.
- jpgvm 6y agoIt's a combination of things. Java is slow moving by the very nature of the contributors to the language and runtime favouring slow methodical advancement. Additionally Java has a longer history than most of backwards compatible software that contributes to a higher burden of testing before making changes to the core language. Finally there is the community itself which favours high performance and reliability and prefers where possible to make use of libraries rather than change the language or runtime itself. That isn't to say Java isn't evolving or that the JVM itself is stagnant. The introduction of the Java module system allowed the JRE itself to become a much lighter dependency. Things like Project Loom seek to bring Erlang-like fiber/green thread support to the JVM and will probably land in a release soon. Also the release cadence has been changed so new releases are now landing much more frequently which is increasing the pace of development.
- pulse7 6y agoAbsence of non-essential features doesn't put a product behind other products... If Apple skips non-essential features it is seen as advantage...
- augustnagro 6y agoI'm thankful that Java hasn't become a mess like C++. The virtual machine and stdlib continue to see innovation, while the ease of implementing JVM languages like Scala and Kotlin mean that Java can let these new languages innovate, and pick the best features when they're proven (with improved performance normally too). You can see this with Lambdas, and now with Records and pattern matching
- pron 6y agoMost evolution on the platform is in the VM and tooling rather than the language, and the language is conservative and slow-moving by design (it was part of the "charter" back when Java was created). This has worked very well. OTOH, Java programmers look in astonishment at how far behind most other platforms are in GC, compilation, and observability.
- jhomedall 6y ago- Once you add a feature, you have to support from now until forever - Almost every feature added makes every feature that comes after it more expensive to add
- strictfp 6y agoI much prefer Cs solution to this problem; you can write multiple literals in sequence and they will be concatenated: char* text = "hello" " dear" " sir"; This is great, because it doesn't make leading whitespace significant on the lines which the text block spans. The Java approach, which seems similar to the Python approach, looks really silly when you are defining a literal in a nested scope; def hello(): def world(): text = """hello world""" print text
- Normal_gaussian 6y ago> This is great, because it doesn't make leading whitespace significant on the lines which the text block spans. I think you might want to go and reread the article, they are using "determining lines" to remove leading whitespace. I think I would find this approach much more readable than Cs
- strictfp 6y agoThe thing is that this is too much magic. You end up wasting time getting your literal right. Whereas Cs solution is simple and just works.
- looperhacks 6y agoThe difference between Python and Java is that the following (Python): text = """hello world""" will contain the intendation before world, while in Java: String text = """hello world""" will be equivalent to "hello\nworld".
- deleted 6y ago[deleted]
- masklinn 6y agoFWIW the Java snippet seems to be a syntax error instead, the JEP explicitly defines the opening delimiter as three double quotes, any amount of whitespace, and a line terminator. The closing delimiter can, however, be on the same line as the final content (in order to suppress the trailing newline for instance).
- chhum 6y agoInteresting to see how Swift-inspired this feature is.
- pulse7 6y agoJava has been inspired by many other languages... and continues to take good features and ideas from other languages...
- masklinn 6y agoIt seems to be using a somewhat similar concept it calls "incidental white space", in order to limit the embedding of leading whitespace (unlike Python which just stores the entire triple-quoted string as-is), but is more permissive: Text content can be indented less than the trailing delimiter, which I understand is an error in Swift String html = """ ..............<html> .............. <body> .............. <p>Hello, world</p> .............. </body> ..............</html> .............. """; The trailing delimiter can also be on the same line as the final content, which suppresses the final (new)line: """ line 1 line 2 line 3""" translates to "line 1\nline 2\nline 3" whereas """ line 1 line 2 line 3 """ translates to "line 1\nline 2\nline 3\n" I believe this requires escaping the newline in Swift instead (nb: according to the JEP this would also work in Java).
- _old_dude_ 6y agoSlash at the end of the line serve the same purpose in Java
- masklinn 6y ago> Slash at the end of the line serve the same purpose in Java As I wrote in my comment, yes.
- imglorp 6y agoMore likely from Kotlin. The only difference is % instead of $. They also grabbed Kotlin's data classes (records in java). Lots of cross pollination.
- nnq 6y ago...this is what Java gets instead of smth actually useful like structs/records/dataclasses with pass-by-value semantics?
- pulse7 6y ago...pass-by-value is also coming and it will be called "inline objects". See: http://cr.openjdk.java.net/~briangoetz/valhalla/sov/01-background.html http://cr.openjdk.java.net/~briangoetz/valhalla/sov/01-backg...
- deleted 6y ago[deleted]
- enitihas 6y agoJava is getting other things, text blocks don't have to be excluded due to those 1. Records are already there AFAIK 2. Structs (Value types) will come as part of Valhalla 3. Records are the impl of dataclasses 4. Pass by value is already there for primitive types. Valhalla might bring that to structs also. Java is also getting a lot of good stuff like coroutines(Loom), and Panama(seamless FFI).
- nnq 6y agoThanks for making me curious... Cool new developments, didn't touch Java in a while! > Records are the impl of dataclasses This is ofc backwards/reverse of any sane logic that would start with value types and after invent references (eg. in this case probably would've mean introducing a new composed-primitive type)... but then again, it's Java, at least they got the strings being immutable part right from the start.
- bathtub365 6y agoIt seems strange to embed content in code in this way. You lose syntax formatting if it's structured content (HTML, JSON, etc) and also require recompiling if the content changes. I understand doing it if you're prototyping/hacking things together but it seems like a lot of effort was put into building this feature.
- enitihas 6y agoIf you use a good IDE like IntelliJ, you don't lose syntax formatting, and can edit the fragment even with autocompletion. IntelliJ is good enough to do this even right now without text blocks in Java, when let's say a HTML snippet is constructed using string concat.
- masklinn 6y agoIt's extremely convenient to embed content which is not single line but which you'd be embedding either way e.g. text with some amont of formatting, or literal SQL queries. It's also useful for small amounts of structured content e.g. if you don't yet need to rely on a full-blown templating system for your HTML, or to POST small amounts of static JSON or somesuch. > You lose syntax formatting if it's structured content Jetbrains's IDEs do content-sniffing and formatting and coloration of embedded content (though it breaks down somewhat quickly if you start doing string formatting within the block).
- stickfigure 6y agoIntelliJ not only handles syntax formatting of code in string literals, but validates SQL against the db schema and performs identifier completion. It's more convenient and safer to put SQL (or other text) inline next to the code that uses it rather than "some other file" that can fall out of sync.
- bathtub365 6y agoI guess I don’t have this problem because I don’t work on CRUD apps.
- deleted 6y ago[deleted]
- nickmqb 6y ago> Avoid mixing spaces and tabs in the indentation of a text block This has some implications. For example, I can imagine someone editing a text block and inadvertently using a different indentation type (tabs/spaces) from the other existing lines, which would then change their program in a non-obvious way. I'm myself an author of a programming language with a non-standard approach to whitespace (called Muon), so this is a topic I've thought about quite a bit. Interesting that the Java team considers this an acceptable tradeoff. I'm looking forward to seeing how this plays out in practice as a data point.
- enitihas 6y agoThis is a nice feature to have, no doubt, but won't make much difference for an IntelliJ user. What I am most eagerly waiting for is Loom, that will bring fibers to the JVM, and make the arguments in favour of server side JVM even more stronger.
- eklavya 6y agoThat, value types and tail call elimination and I am just set forever I think. All are coming.
- Scarbutt 6y ago'Text Blocks' took many years and you still need pass a flag to use it, I can't imagine how much time Loom will take. Maybe move to Kotlin coroutines?
- enitihas 6y agoI really like Kotlin, but text blocks were never the pain point for me in Java. The best thing Kotlin brings to the table is explicit nullability, which makes it so much easier to reason what can be null or not. Loom and Kotlin coroutines are not the same though. Loom will bring real fibres to the JVM, which maybe Kotlin coroutines can use. Kotlin coroutines should also benefit from Loom.
- Scarbutt 6y agoYep, but if you want/need more efficient concurrency today...
- nickbauman 6y agoAm I the only one who really dislikes coroutines?
- nickbauman 6y agoLooooong after the other languages have done it, Java comes around to doing it. Seriously, the best thing about Java is the JVM where you can choose a better language than Java to program with it and get all the benefits of the JVM.
- JMTQp8lwXL 6y agoIf you want to use any language, what makes the JVM important? Just use whatever that tech stack uses. Node uses v8, for example.
- nickbauman 6y agoI don't think you can compare V8 with the JVM. For starters, last time I checked, V8 is still single threaded, isn't it? Also it seems like future versions of JS are embracing things that make it look like they're envying Java, which seems like it's going in the wrong direction.
- t0astbread 6y agoYou can do parallel computing in Node and the browser using workers. Also what features do you mean that "envy Java"?
- nickbauman 6y agostatic typing seems to be on the horizon (facepalm)
- t0astbread 6y agoWell yeah, Microsoft developed TypeScript to resemble C#'s type system so naturally it will look a bit like Java? TS is far from being the de-facto standard though (maybe because it's centred around OOP?)
- nickbauman 6y ago
- yashap 6y agoThis seems a little too magical for Java - normally indentation doesn’t have programmatic meaning like this in Java. I prefer the Scala approach: https://alvinalexander.com/scala/how-to-create-multiline-strings-heredoc-in-scala-cookbook/ https://alvinalexander.com/scala/how-to-create-multiline-str... Just seems more obvious/clear.
- cletus 6y agoSo this is a long overdue QoL feature but the whole whitespace elision thing is unwelcome and unnecessary (IMHO). What's wrong with What You See Is What You Get? This is a perfect example of added complexity to solve a complete non-problem just based on probably the unsubstantiated aesthetic view of a handful of key people. Stop. Just... stop. Even stripping trailing whitespace is... risky. Why is the language trying to decide what whitespace is significant? Or even trying to divine the mind of the developer at all? I didn't realize there was a raw string proposal in Java 12 using backticks (bleh). By now I'm pretty used to languages that use double-quotes for interpreted strings (including escape sequences, at a minimum) and single-quotes for raw strings. This is an incredibly useful feature. Of course, Java uses single-quotes for character literals so that's out, otherwise I'd like to see """ for interpreted and ''' for raw. Anyway, let me point out just one reason why this is terrible: source control. Consider: String s1 = """ <outer> <inner>foo</inner> </outer> """"; Now change this to: String s1 = """ <outer> <inner>foo</inner> </outer> """"; It's only one line change but you have in fact changed what the previous lines do. And of course (which the article mentions).... tabs! I really want the option of pasting text into a block like this and knowing that's what I'll get. I don't want to process it usually (eg escaping characters).
- vbezhenar 6y agoHow do you propose handling the most common case, when I don't want leading indentations? String s1 = """<outer> <inner>foo</inner> </outer>"""; is ugly.
- kevingadd 6y agoIt's how C# does it. You can always put in a leading newline and strip it via an API call, or put the """ at the start of the next line.
- dfinninger 6y agoPython has the textwrap[1] module in the standard library. Calling “textwrap.dedent()” on the docstring (multiline string) will strip white space to the least-indented line inside the text. I’m personally a fan of having an easily-accessible method to call. That way you get indented text blocks and no “magic” formatting (at least, you explicitly opt-in to the magic formatting). [1] https://docs.python.org/3/library/textwrap.html https://docs.python.org/3/library/textwrap.html
- atulatul 6y agoThis comment is not about text blocks as such but the write up by the author. (Brian Goetz... If you are here, when do we see the next edition of the book, please?). It is not simply 'here's a new language feature'. I find it quite informative regarding what, why, how and why not etc. His articles explain what went into the decision making. Something on the lines of discussions in Effective Java by Joshua Bloch. His article on records: https://www.infoq.com/articles/java-14-feature-spotlight/ https://www.infoq.com/articles/java-14-feature-spotlight/
- dlandis 6y ago> To disentangle the incidental and essential indentation, we can imagine drawing the smallest possible rectangle around the XML snippet that contains the entire snippet, and treating the contents of this rectangle as a two-dimensional block of text. This "magic rectangle" is the contents of the text block, and reflects the relative indentation between the lines of the block but ignores any indentation that is an artifact of how the program is indented. Well, I'll withhold judgement somewhat until I eventually use this feature for a little while, but based on the description this is simply too complex, which is disappointing. Who exactly was asking for the "magical rectangle" approach, anyway? Or incidental vs essential indentation? They did too much. And given how long people have been waiting for simple multi-line strings, and how many other languages already have them, I'm not sure how this got messed up.
- bokchoi 6y agoI prefer seeing the multi-line string trimmed to the current indent level. I wouldn't call it messed up.
- deleted 6y ago[deleted]