0%
Text and Strings: Multiline Blocks and New Methods

Text and strings

Text blocks, formatted, and the additions to String that replace a utility library.

10-15 min

Text and Strings: Multiline Blocks and New Methods

A fifteen-line SQL query written in Java 8 is a wall of quotes, plus signs, trailing spaces, and \n. The real cost isn't the typing: it's that the text becomes impossible to reread, and above all impossible to copy. You can't paste the query as-is into a PostgreSQL client to test it, nor paste the corrected result back into the code. Every round trip between the SQL editor and Java requires a manual rewrite, and that's exactly when the missing space between FROM commande and WHERE slips in.

The same problem hits JSON in tests. An expected twenty-line payload, escaped by hand, produces a literal where \" takes up more room than the data. When the test fails, you lose several minutes visually comparing two unreadable strings. Text blocks, introduced in Java 15, solve this problem in a more subtle way than it first appears: they don't just allow line breaks, they strip incidental indentation so the text stays aligned in the code without polluting the value.

Before: concatenation

// Java 8
String requete = "SELECT c.id, c.reference, c.total, cl.nom\n"
               + "FROM commande c\n"
               + "JOIN client cl ON cl.id = c.client_id\n"
               + "WHERE c.statut = ?\n"
               + "  AND c.date_creation >= ?\n"
               + "ORDER BY c.date_creation DESC";

Comments

Comments are powered by GitHub Discussions

Sign in with GitHub to join the discussion

Link copied!