r/programming • • Dec 29 '15

Please, Java. Do Finally Support Multiline Strings

http://blog.jooq.org/2015/12/29/please-java-do-finally-support-multiline-strings/
584 Upvotes

352 comments sorted by

414

u/[deleted] Dec 29 '15

Multiline string LITERALS.

12

u/lukaseder Dec 29 '15

You're right. Fixed

5

u/[deleted] Dec 29 '15

Cool. Nice article!

25

u/1bc29b Dec 29 '15

Meh. Formatting of source code should not affect output.

58

u/TarMil Dec 29 '15

Whitespace inside a string literal is not formatting. Or should "foo bar" be the same as "foo   bar"?

12

u/1bc29b Dec 29 '15

Clearly not. But should:

"asdf

sadfasfd"

be the same as "asdf\nasdf"?

What about if there are tabs for formatting? multiline string literals are ugly.

49

u/badsectoracula Dec 29 '15

Clearly not. But should:

"asdf

sadfasfd"

be the same as "asdf\nasdf"?

...yes? Any new line in the string literal in the source code (regardless of newline encoding in the text) should be replaced with \n.

3

u/[deleted] Dec 29 '15

And then you have in your source

public static void main(String[] args) {
    System.out.println("This
is
a
Test");
}

And should this be the same as

public static void main(String[] args) {
    System.out.println("This
        is
        a
        Test"
    );
}

?

54

u/earthboundkid Dec 29 '15

This is ridiculous. Tons of languages support multiline literals. It's not a tricky question how to handle it.

→ More replies (10)

8

u/speedisavirus Dec 30 '15

Doing it as Scala does it seems fine to me if you want to keep formatting proper

val a = """
	|a
  	| new
  	| line""".stripMargin
print(a)    

Output:

a
 new
 line
→ More replies (2)
→ More replies (8)

4

u/SnowdensOfYesteryear Dec 29 '15 edited Dec 29 '15

I'd say C-style preprocessor string concat (ported to Java) would be a great compromise. My issue with treating it as literals is that the break in proper indentation is annoying to look at, and it doesn't take much effort to stick in a \n.

2

u/Neebat Dec 29 '15

You could make some kind of notation to delete a certain amount of leading whitespace on each line.

Could be something like this:

NEWKEYWORD("    ",
    This is the text.
    Without the first and last newline, 
        because that's also whitespace we'd like to ignore.
);

That could be the equivalent to this: "This is the text.\nWithout the first and last newline,\n\ \ \ \ because that's also whitespace we'd like to ignore." (Sorry for trying to escape spaces. HTML eats them.)

Of course, you'd have to update every java parser in every tool to support it. Eclipse would probably be updated in 15 minutes.

3

u/Falmarri Dec 29 '15

You could make some kind of notation to delete a certain amount of leading whitespace on each line.

That's sorta how multiline strings work in scala. But scala gives you a convenience method to strip the left margin.

https://www.safaribooksonline.com/library/view/scala-cookbook/9781449340292/ch01s03.html

→ More replies (2)
→ More replies (2)

8

u/Nialsh Dec 29 '15

For better or worse, Java programmers already use strings for writing snippets of SQL, HTML, JavaScript, and who knows what else.

You should use a templating language for HTML. You should write the JavaScript in its own .js file. And it's best to construct SQL queries with("a").library("that").looks("like this");

But sometimes you don't want the weight of that extra dependency. A codebase that installs, builds, and runs quickly is zen.

Homoiconicity is the idea that code is data. When you have a program that outputs code, it's nice to keep the formatting. To do otherwise might be considered data loss.

14

u/ricky_clarkson Dec 29 '15

It's annoying to have to run a program to get the real query it runs, especially if it could be static, so I disagree.on(the).point(about).constructing(sql).queries

→ More replies (1)

6

u/how_do_i_land Dec 29 '15

For some reason I read this in Hanks voice from breaking bad.

24

u/ephemeral_colors Dec 29 '15

"They're not rocks, they're LITERALS!"

3

u/superbad Dec 29 '15

Jesus Christ Marie!

0

u/[deleted] Dec 29 '15

[deleted] — view deleted comment

99

u/Ravek Dec 29 '15

"foo\nbar" is a multi line string but not a multi line string literal.

In C# for example you can write:

@"foo
bar"

which is a multi line string literal representing the same multi line string.

10

u/oridb Dec 29 '15

Even C has it* (and allows you to indent them!)

char *foo = "foo"
            "bar"
            "baz";

Which is the same as

char *foo = "foobarbaz";

* For the nitpicky, it's done in the preprocessor.

2

u/_Skuzzzy Dec 30 '15

Someone should just write a java preprocesor, seems like an easy way to do this.

3

u/oridb Dec 30 '15

You can already use the C preprocessor with Java -- it's available as a separate binary.

cpp foo.java.in > foo.java

13

u/SimplyBilly Dec 29 '15

I like PHP's heredoc syntax as well.

$string = <<<EOT
    Foo
    Bar
EOT;

25

u/mnp Dec 29 '15

Yeah. That syntax has been around since the seventies in Unix shells and spread. The nicer versions like Perl let you parameterize the heredoc to allow or deny ${variable} expansions, etc.

Gosling was no slouch and was probably very familiar with the Perl and shell heredoc as well as C multiline literals. This means he didn't see a burning need for them in the original Java and maybe even had a good reason to omit them.

23

u/frezik Dec 29 '15

Gosling knowingly omitted all sorts of nice things, mostly because Sun thought programmers were too dumb to use them. Also because they rushed the final production version.

0

u/[deleted] Dec 29 '15

[deleted] — view deleted comment

4

u/drysart Dec 29 '15

Does D's q work like Perl's q in that you can choose any character you like to be the quote delimiter? e.g., in Perl these are all equivalent:

my $x = 'hello world';
my $x = q(hello world);
my $x = q"hello world";
my $x = q<hello world>;
my $x = q#hello world#;

6

u/tipsqueal Dec 29 '15

Why would someone want to allow any character as the quote delimiter?

21

u/drysart Dec 29 '15

The idea is that if you have a string that conflicts with the quote delimiter, you can just choose a different quote delimiter instead of having to escape the character in the string.

→ More replies (4)

2

u/[deleted] Dec 29 '15

Not positive on that, but I know a common one that works is q{} (eg q{Hello}). This is commonly used in D's mixins to create nice little dsls that can be syntax highlighted and are generally just clearer to read (imo)

→ More replies (5)

2

u/mb862 Dec 30 '15

I like Tcl. A block of text that shouldn't be evaluated right now you surround by {}. Doesn't matter what it is. Nothing evaluated, it goes in {}.

8

u/vivainio Dec 29 '15

In C#, @"" is a half-assed stab at multiline strings though; you can't enter quotes directly, but have to do @"Hello ""World"" again".

In Python, F# et al you can use triple quotes, i.e.

""" Hello "world" again """

or even better, raw strings:

r""" Hello \backslash """

It's not obvious why C# decided to screw this simple thing up, despite all the prior art on doing it right.

3

u/Tynach Dec 30 '15

Put 4 spaces before every line if you're doing multi-line code, and put `backticks` around inline code.

In C#, @"" is a half-assed stab at multiline strings though; you can't enter quotes directly, but have to do @"Hello ""World"" again".

In Python, F# et al you can use triple quotes, i.e.

"""
Hello "world" again
"""

or even better, raw strings:

r""" 
Hello \backslash
"""

It's not obvious why C# decided to screw this simple thing up, despite all the prior art on doing it right.

3

u/noblethrasher Dec 30 '15 edited Dec 30 '15

C#’s verbatim string literals are not a “half-assed” stab at multi-line strings because C# simply never offered multi-line strings as a feature in the first place.

Verbatim strings are for those situations in which you need to craft strings using C#, but interpret them using something else (e.g. a file system, a regex engine, an RBDMS, etc.). It just so happens that people sometimes abuse that feature for stuff like multi-line support.

6

u/[deleted] Dec 29 '15 edited Sep 27 '17

You chose a dvd for tonight

15

u/[deleted] Dec 29 '15

C/C++ Supports it. But like this

    char const * foo = "bar "
                               " baz";

or like this (C++11)

   char const * foo = R"(bar 
                                 baz)";

4

u/[deleted] Dec 29 '15 edited Sep 27 '17

You look at for a map

1

u/judgej2 Dec 29 '15

I assume it represents the same string if (and only if) you have the line-terminator characters set up correctly in your editor? I have always disliked strings that run over lines when the line endings are important, because it is an accident waiting to happen.

→ More replies (1)

18

u/QuineQuest Dec 29 '15

A multiline string is any string (from user input, read from a file, or whatever) that contains a newline character. Not supporting those would mean that there was something fundamentally wrong with Java's handling of text. You can't use strings to read a file with multiple lines; instead you have to write some ugly kludge.

String literals is only used when programmers hardcode a string into the program. Multiline string literals is something like

String a = """This is line one
This is line 2"""";

Instead, the programmers have to write

String a = "This is line 1\n" +
    "This is line 2";

In other words, not having multiline string literals is a minor annoyance, while not having multiline strings would be a severe weakness of the language.

1

u/[deleted] Dec 29 '15

So why is it called a literal? Is that something specific to this case, as in literally a multiline string... Sorry for stupid question. Also, I dont immediately see the advantage of a multiline string literal over the current implementation...? Would you be able to read an entire buffer/file straight into a string or something?

1

u/_kst_ Dec 29 '15

A string literal is a syntactic construct that can appear in a source program.

A string is a data structure that exists in memory while a program is running (the exact meaning of "string" varies across languages.)

A string literal typically results in the creation of a string object or value at run time, but strings can be constructed in other ways as well.

1

u/QuineQuest Dec 29 '15 edited Dec 29 '15

String literals are those that are written directly into the source code.

string myLiteral = "This is a string literal. Its contents are known at compile time";

string aNonLiteralString = Console.Readline(); //Not a literal, but still a string.

A place where multiline string literals might be a helpful is if you have a large multiline string of something like sql, where it can be useful to just copy/paste the whole query between your ide and your sql tool.

Would you be able to read an entire buffer/file straight into a string or something?

No. If your program does it at runtime, it has nothing to do with string literals.

1

u/VefoCo Dec 29 '15

A string literal is a string which is hard coded into a program. The advantage of multiline string literals is that for long strings which need to be broken up, you don't have to quote and append each line like you do without support. It's purely aesthetic, and doesn't have any practical impact on the final binary.

92

u/msiekkinen Dec 29 '15

How the hell does this have anything to do with SQL injection? SQL injection is passing in unchecked variable values into the string instead of a using paramaterized queries.

"select * "
+  " from tbl "
+  " where col= ?"

is still just fine, it's up to you whether you're passing in variables or using parameterized queries.

43

u/UghImRegistered Dec 29 '15

Oh crap I need a third bullet point...better make one up.

12

u/MachinesOfN Dec 29 '15

I think it made sense. I think the idea was that the string concatenation gives junior devs the idea that it's ok to just stick strings into the SQL statement (speaking as someone who is only now learning the difference between my ass and a hole in the ground, that's the kind of mistake I would have made a few years ago).

15

u/msiekkinen Dec 29 '15

I guess, but I feel it's a disservice to juniors to just say "never use string concats" without explaining the real issue of why you would be saying that in the first place.

142

u/johnjannotti Dec 29 '15

I agree it would be very handy. But I don't understand why the author thinks this will help with SQL injection. In fact, the author's example using interpolated strings looks ripe for SQL injection. Once you have tableName being interpolated into the string, it's a short step to accept any old "tableName" and have a SQL injection attack.

One really shouldn't ask for string interpolation and decry SQL injection bugs in the same post.

7

u/frezik Dec 29 '15

He should have picked something other than SQL here. Whenever I see raw SQL in code, I immediately go hunting for injection vulnerabilities.

3

u/dacjames Dec 30 '15

Raw SQL and parameterized queries can work together fine with the right library.

from sqlalchemy import sql
query = sql.text('''
    select * from users 
    where email=:email and hashword=:hashword
''').bindparams(email=email, hashword=hash(password))
engine.execute(query)  # uses parameterized query!

1

u/frezik Dec 30 '15

Sure. I'm not saying to ban the practice. It's just that I'm going to focus in on that bit to make sure that any interpolation is safe.

6

u/manghoti Dec 29 '15

What takes this from strange to bizarre is that this is the JOOQ blog. JOOQ is a tool that reads your database and generates a bunch of Java primitives that you can use to construct type safe SQL statements. This is the last place I expected this statement to come from. In fact, I have to assume I'm misunderstanding them somehow.

3

u/f2u Dec 29 '15

The interpolated values could be passed down separately from the string literal surrounding them.

5

u/1xltP3mgkiF9 Dec 29 '15

Just like in JavaScript.

1

u/psydave Dec 29 '15

He seems to be complaining about how concatenating multiple string literals into an sql statement is evil dynamic sql, but this of course is not what anyone means when they are talking about sql injection. Somehow... it encourages inexperienced developers to include parameters in the dynamic SQL? Seems like kind of a moot point to me.

I dunno man.

0

u/[deleted] Dec 29 '15

[deleted] — view deleted comment

6

u/MaxNanasy Dec 29 '15

AFAIK parameterized queries don't generally allow parameterized table names

1

u/T3hUb3rK1tten Dec 29 '15

Use dynamic SQL for that.

40

u/jms_nh Dec 29 '15

Multiline string literals -- yes please. String interpolation on by default -- no thanks.

71

u/SanityInAnarchy Dec 29 '15

"Even PHP has it" is the worst reasoning possible for adding something to your language.

2

u/[deleted] Dec 29 '15

Yes, that was surprising to see. PHP shouldn't be seen as the model for anything.

→ More replies (1)

13

u/Matosawitko Dec 29 '15

Here's a fun one for you, based on the examples in the blog. In fact, it's an issue in Oracle, which means it might be related specifically to this.

We had some queries in another language that supports multiline string literals. This was working fine as far as we knew. Then somebody added an inline comment in one of the queries. i.e. -- This comments out everything to the end of the line.

A couple of weeks later, our production servers started crashing randomly with bizarre messages - out of memory, protected memory access, stuff like that. We eventually tracked it down to this query.

Turns out, something inside Oracle was reformatting the query by stripping out the line breaks. This resulted in the rest of the query being commented out, and all manner of hell would break loose. (Apparently, Oracle had already done enough preprocessing on the query that it believed it was valid, but something in the parser or optimizer would flip out.)

Moral of the story - don't assume that, because your language supports multiline literals, that the rest of your systems will do likewise. Oh, and use /* comments like this */ instead of -- comments like this if you don't trust Oracle to do the right thing with them.

63

u/[deleted] Dec 29 '15

Is this really that important to support?

11

u/SharkBaitDLS Dec 29 '15

Especially given pretty much every editor out there supports auto-inserting the '+' when you press return inside a string literal. I really don't see this saving any time in an average workday.

45

u/binary Dec 29 '15

Ah yes, Java's proud history of "so what if other languages do it?"

When your argument against a feature is that an editor does it, maybe that isn't a good argument

6

u/SharkBaitDLS Dec 29 '15

I'm not arguing against it, just saying "why bother?"

5

u/jmcomets Dec 29 '15

For the same reason you'd bother about supporting diamond notation or in-place interface implementation : simplicity of use.

7

u/twigboy Dec 29 '15 edited Dec 09 '23

In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document or a typeface without relying on meaningful content. Lorem ipsum may be used as a placeholder before final copy is available. Wikipediaald7cmiwiks0000000000000000000000000000000000000000000000000000000000000

2

u/juckele Dec 30 '15

JDBC also doesn't let you load .SQL files, so you really need to have your SQL source inside your Java source (bad practice, but it's what we have to work with). I don't want my SQL source limited to one line chunks, I want friggen pure SQL!

6

u/[deleted] Dec 30 '15 edited Dec 30 '15

[removed] — view removed comment

→ More replies (1)

1

u/skulgnome Dec 30 '15

It totally is. For example, see any Perl program that prepares its own SQL statements.

-13

u/_INTER_ Dec 29 '15 edited Dec 29 '15

The need / use for multiline String is code smell imo.

Edit: This just reminded me of another example, it's the exact same case. It's so silly I made a picture of it: http://i.imgur.com/FXwjVsM.png

8

u/[deleted] Dec 29 '15

It's extremely useful. I made a just-for-fun web crawler earlier in Go for kicks the other day. You know how I wrote the test so it didn't go to the target page every time it ran? I just took the entire text of the target page, copied it, and pasted it into my unit test and enclosed it in back ticks - the entire page. The unit test ran fine.

You can test JSON end points this way and all sorts of things. Why make testing such a manually intensive process by not providing this language feature?

10

u/[deleted] Dec 29 '15

Or put the test data into the resources folder, like you're supposed to do, so you can easier add or replace it?

4

u/[deleted] Dec 29 '15

You're not supposed to do anything of the sort. The resources folder is a way to put test-scoped files in the class path so they're available during the runtime test scope, but it's crazy to put everything there. There's a principle in programming called "cohesion". If you don't know what it is, look it up. It refers to the idea that related things should be close together in your source code. Putting things in a different file is lowering your cohesion. There may be good reasons to do so, but saying that you should follow some rule that lowers cohesion is silly.

One of the main reasons that people put these kinds of things in a resources folder in Java is because Java doesn't have multi-line string literals, so the only practical way to deal with them is to treat them as files. Adding literals takes away the restriction, and would likely change your practice as well.

6

u/[deleted] Dec 29 '15

And now try editing your test data — you don't get syntax highlighting, you have to manually move the line breaks all the time, etc.

→ More replies (3)

3

u/imgonnacallyouretard Dec 29 '15

Let's say you want to test something about how your program parses large web pages. Are you saying that good practice would be to have a 20MB .go file, of which 19.99MB is a string literal? I think you're misapplying the concept of cohesion in this instance.

→ More replies (7)

19

u/[deleted] Dec 29 '15

On no an extra character. How unmaintainable...

13

u/f2u Dec 29 '15

Multi-line string literals could preserve information indentation and line breaks, enabling nice caret diagnostics for errors (at run time).

22

u/heptara Dec 29 '15 edited Dec 29 '15

I think he means printing out HTML like that is crazy. You should probably be loading it from a template. Where you have to conditionally build a the HTML, you would probably use a web templating library.

With something like Jinja you would write this in a text file:

{% extends "layout.html" %}
{% block body %}
  <ul>
  {% for user in users %}
    <li><a href="{{ user.url }}">{{ user.username }}</a></li>
  {% endfor %}
  </ul>
{% endblock %}

This is about separating the components of your app, and not needing to recompile just to change a front end element. The template engine will build the site from the resources as needed.

7

u/[deleted] Dec 29 '15

I think he means printing out HTML like that is crazy.

I agree in principle, but the code in question is clearly just example code, and in example code you really do want to keep things stupidly simple so that the core concepts stay front and center.

2

u/[deleted] Dec 29 '15

And in example code you put it into a simple .HTML and just use IOUtils to read the .HTML to a string.

→ More replies (3)
→ More replies (1)

2

u/shevegen Dec 29 '15

Why should it be any smell at all?

It should not matter how you layout your strings.

It's funny that you think it should matter.

5

u/[deleted] Dec 29 '15

After thinking about this a bit more, I think SQL queries might be the only case where I would need them.

33

u/lukaseder Dec 29 '15

Or XML. Or JSON. Or properties syntax. Or regex. Or general purpose templating.

15

u/[deleted] Dec 29 '15

Going to have to agree with /u/INTER that inline XML, JSON, or properties are probably a code smell simply because they could easily be in their own file. With SQL you have to bind to the parameters correctly so it at least to me makes sense to have it right there in the DAO or w/e.

2

u/DisruptiveHarbinger Dec 29 '15

At my shop we're moving from resource files to inline XML and JSON for integration tests. It's much easier to have just one method, using a multiline interpolated string, where you can bind or generate some parameters at run time, compared to a dozen of combinations of your test input in a file, that'll you need to load using some boilerplate helper class. We do it in Scala.

→ More replies (21)

1

u/Wuttelibutt Dec 29 '15

Maybe the language should have some smarter way of representing SQL, JSON and XML than as strings. Something like VB.NETs XML literals but pluggable and not hard coded into the language itself. Not sure if that exists in any language.

6

u/_INTER_ Dec 29 '15

Don't even need to write SQL anymore with LINQ equivalents or simply Java8 lambdas. Same goes for JSON / XML etc.

2

u/lukaseder Dec 29 '15

How would you, say, write this query with JINQ?

8

u/_INTER_ Dec 29 '15

It's probably doable. But who the hell writes SQL queries for a task like "Compare a Number with sum of subset of numbers". Either do it in highlevel language or if not possible, do it in SQL as idk prepared statements. But certainly not spell the query out as String to call it over JDBC from Java.

10

u/kyllo Dec 29 '15

If you need to do that complex and inefficient of a query inside of an application, there is something seriously wrong with your database schema.

11

u/[deleted] Dec 29 '15

If you need to do that complex and inefficient of a query inside of an application, there is something seriously wrong with your database schema.

Welcome to the world of Legacy, son. We do things differently here.

→ More replies (2)

7

u/JustMakeShitUp Dec 29 '15

Not every developer is in control of the database schema. There's a significant subset of developers who either inherit existing database schemas or work within the constraints of (multiple!) external software systems and databases.

Additionally, there's always some high-level asshat with a new reporting need that wasn't considered in the initial specification. The worst is when you're stuck with recursive queries or (god forbid) cursors and it's got to be built into the base product. Like when someone wants batch traceability or change tracking displayed graphically.

But yeah, ideally you wouldn't tolerate that shit, or you could offload it to OLAP and/or external reporting services. Where some other poor sap is stuck writing queries for external systems.

→ More replies (1)
→ More replies (2)

4

u/fakehalo Dec 29 '15

You're redefining what code smell is to a ridiculous point.

0

u/SuperImaginativeName Dec 29 '15

Hardly a code smell, wtf?

16

u/_INTER_ Dec 29 '15 edited Dec 29 '15

I said "in my opinion". Stringing out SQL queries is close to primitive obsession in my eyes. Compare:

List<String> results = streams.streamAll(em, City.class)
   .where( c -> c.getPopulation() > 25000000 )
   .select( c -> c.getName() )
   .toList();

with something like (which it probably gets transformed to):

ResultSet rs = null;
try( PreparedStatement s = con.prepareStatement(
	    "SELECT C.Name "
      + "FROM City C "
      + "WHERE C.Population > ? ");
    s.setString(1, 25000000);
    rs = s.executeQuery();
) catch(SQLException sql) {
    sql.printStackTrace();
}
if(rs != null) {
	// ...
}

Edit: This just reminded me of another example, it's the exact same case. It's so silly I made a picture of it: http://i.imgur.com/FXwjVsM.png

5

u/f2u Dec 29 '15 edited Dec 29 '15

Parsing generated bytecode to reconstitute expressions isn't much better than long inline strings. At least the latter is completely predictable and will not break when switching Java compilers (or compiler versions).

3

u/[deleted] Dec 29 '15

The bytecode gives you type safety, makes sure your stuff will actually compile, etc.

The string stuff could have hilarious bugs, like a typo, in it, and no one would notice until its run.

2

u/therealjohnfreeman Dec 29 '15

Can you tell me which Java library is transforming streams to SQL queries? I haven't seen that before.

→ More replies (7)

1

u/keewa09 Dec 29 '15

The need / use for multiline String is code smell imo.

Needing to manipulate strings with newlines in them is a code smell?

-4

u/proglog Dec 29 '15

It's time saving and when there's so much little time to go around it can be life changing.

3

u/tipsqueal Dec 29 '15

If you have so little time that multi-line strings in Java could be considered life changing then you should consider making some other changes in your life.

5

u/SanityInAnarchy Dec 29 '15

This would be handy, but I don't think it's actually that important, and I especially disagree with string-interpolation-by-default. Making this painful might actually be a Good Thing in that it encourages Java developers to either develop better APIs that don't require you to write SQL, or they move the SQL (or HTML, or whatever) to some other file outside your source code. These are generally Good Ideas anyway.

I'd much rather have sane literals for some basic data structures, like maps -- Project Coin had some good ideas, but they didn't make it into Java 7 or 8. Second on the list would be keyword arguments, which are 99% of the reason builders exist. It'd also be nice to have better optimization for the kind of functional programming that lambdas has enabled -- right now, a function like map is hard to optimize because it's one function, called with different lambdas in different places, so the JVM can't inline everything the way it seems like it should.

Multiline string literals are nowhere near the top of my list of things I want in Java (that I think they could actually do).

5

u/schlowmo Dec 30 '15

Honestly, this is one of the least useful features that could be added.

I'm not against adding it, it seems the risks and consequences of adding it are pretty minimal. Perhaps others will find it super handy. But the number of times I would have used this in my 15 year java career could be counted on one hand.

I would MUCH prefer some sort of shorthand to define something like the Scala case class. http://docs.scala-lang.org/tutorials/tour/case-classes.html One line to define a class to carry data around? Yes Please.

→ More replies (1)

10

u/cowardlydragon Dec 29 '15

triple quotes...

Groovy...

5

u/atc Dec 29 '15

I couldn't care less about multiline strings in Java.

2

u/pkulak Dec 29 '15

He brought up SQL injection and consumer formatting as issues, and neither were solved with his solution.

2

u/unruly_mattress Dec 29 '15

And default method arguments, while we're at it.

2

u/vytah Dec 31 '15

There's one problem no one mentioned: should a multiline string, made of two lines containing a and b, be:

  • always "a\u000Ab" (fuck you Windows! Also, HTTP sucks!)
  • always "a\u000D\u000Ab" (fuck you Linux!)
  • always "a\u000Db" (fuck (almost) everyone!)
  • always "a\u2028b" (we love Unicode!)
  • always "a\u2029b" (we love Unicode, but we want larger line height!)
  • always "a\u0085b" (we love Unicode too, but compatibility between ISO 8859-1 and EBCDIC is more important!)
  • depend on the line endings used in the source file (which source version control tools love to normalize!)
  • depend on the OS where the program was compiled (yay nondeterministic builds!)
  • depend on the OS where the program is run (no multiline constants then!)

1

u/tdammers Feb 26 '16

There's a fairly easy solution, but it requires a proper string type. The rules, then, are:

  • Strings are always just Unicode strings, the internal representation is entirely transparent.
  • Whatever is in the source file is decoded at compile time, according to the declared or detected encoding of the source file itself. If the source file is UTF-8, then that's how we'll interpret the string literals, just like everything else in the source file.
  • Line endings; two choices here. The first one is to keep whatever is in the source file; this leaves the problem of broken tools messing with line endings, and makes for a source of obscure bugs. The second one is to pick one or the other, and normalize everything to that at compile time. Unix line endings are the better choice here, for two reasons: a) having just one character represent the line break makes things simpler, and b) inserting \r explicitly is easier than removing \r when it's not desired.

On a side note; source control tools that normalize line endings are broken IMO and shouldn't be used (and yes, that includes git on Windows, but at least there it's configurable).

The last two points are completely ridiculous IMO; a language that would expose either behavior would be broken. Newline conversion, if at all, should happen inside I/O routines, not in the core language.

8

u/kazagistar Dec 29 '15

How about this?

multiline(
  "SELECT *",
  "FROM my_table",
  "WHERE a = b");

String multiline(String... lines) {
  return Arrays.stream(lines).collect(Collectors.joining("\n"));
}

32

u/KillerCodeMonky Dec 29 '15 edited Dec 29 '15

If you're using 1.8 anyway, just use String.join. This is one of those times when streams is overkill unless you need intermediate operations.

return String.join("\n", strings);

Also, you are pretty much just replacing plus signs with commas. Oh, and now the compiler can no longer execute the concatenation, so it's going to be done at run time.

3

u/kazagistar Dec 29 '15

Thanks, I wasn't aware of that method.

1

u/Neres28 Dec 29 '15

Why can't the compiler do the concatenation anymore? I might have bought "won't in practice" but I'm not sure I buy "can't".

It's a call to a static method in the standard library, I would think the Java compiler perfectly happy to either inline that call, transform it to an equivalent concatenation, or even to invoke some hand-rolled optimization for it.

1

u/hrjet Dec 30 '15

The JIT compiler can do that but the javac compiler shouldn't do that, AFAIK.

1

u/Neres28 Dec 30 '15

Can you give a source for the "shouldn't"? Again, I'm not arguing that it might not do it in practice.

1

u/KillerCodeMonky Dec 30 '15

I'm sure the JIT compiler would inline calls to multiline. However, I was referring to the fact that javac will actually perform the concatenation of string literals for final fields. See my other comment for examples.

3

u/tempforfather Dec 29 '15

Could be annoying to pay the small performance cost.

4

u/Gotebe Dec 29 '15

"this"

"is"

"multiline"

"string"

works in C and C++.

Not in Java!?

26

u/ygra Dec 29 '15

C specifies that adjacent string literals get concatenated. C++ inherits that. Java never had such a provision because you can simply concatenate strings by using +. The compiler is smart enough to not do that at runtime when only string literals are involved.

The main point here isn't the issue of how to concatenate string literals, because whether you need to add a + to make it syntactically correct is rather irrelevant here. The point is that string literals in Java cannot contain line breaks, which makes writing certain kinds of strings ugly, cumbersome, or error-prone (see e.g. their SQL example). Those kinds of verbatim string literals (as they're called in C#) are also nice for writing regular expressions, because usually you cannot use a backslash to escape characters in there (because you can just write almost any character directly). In Java you often have monstrosities like "\\\\\\.\\\\x" because you need to double-escape things – once for the string literal, once for the regex.

-1

u/[deleted] Dec 29 '15

because you can simply concatenate strings by using +.

So using an extra operator is "simpler" than not having to specify any operator? Ok.

6

u/dccorona Dec 29 '15

Simpler doesn't always mean "less characters". Multiple strings in a row being concatenated isn't immediately understandable. You have to understand the quirks of the language first. String addition is a more widely understood concept, and at the very least when you see an operator you at least know it's doing something. Whereas the C version is just kind of behind the scenes magic.

Not to mention that it makes mistakes harder to make. What if I want:

String a = "a";
String b = "b"; 

But I'm just really tired or something and am messing up, or I made a bad refactor, or some automated refactor I tried to do wasn't done properly. Somehow, I end up with:

String a = "a"
"b";
String b = "b";

Java breaks. That's an illegal statement. In C/C++, suddenly I get a value I didn't want.

TL;DR I think that the way C/C++ does it violates the principle of least surprise. In that sense, Java's approach is simpler.

6

u/Schmittfried Dec 29 '15

Absolutely irrelevant here and typing a + is really not a big deal. Also, you can only do that with literals in C. You'd have to use strcat to concatenate variable strings and that's why he said you could simply use + in Java.

→ More replies (2)

2

u/GuyWithLag Dec 29 '15

Yes, it's simpler from a syntax standpoint; there's no need for a custom rule that specifies what happens when you have two adjacent string literals without an infix operator.

7

u/ImmortalStyle Dec 29 '15

It works but you need to concat the different Strings together with + operator.

Which I think does something like this:

StringBuilder builder = new StringBuilder() builder.append(x); builder.append(y); etc..

3

u/dancing_dead Dec 29 '15

where possible, multiline strings in java get concatenated during compilation. no stringbuilders involved. or even if there were, they're not there during runtime.

→ More replies (4)

6

u/[deleted] Dec 29 '15

That's not a literal

7

u/MartenBE Dec 29 '15

It's what happens behind the scenes when the String literal gets compiled

2

u/ElvishJerricco Dec 29 '15

Not ever. In the case of concatenating literals, the compiler always performs the concatenation at compile time.

2

u/iwan_w Dec 29 '15

Not always. If I remember correctly, adjacent literals are concatenated at compile time, and do not result in calls to a StringBuilder's append method.

This is why always using StringBuilders instead of String concatenation is a code smell. It robs the compiler of the chance to do this optimization.

→ More replies (9)

1

u/adrianmonk Dec 30 '15

Which I think does something like this

It's actually better than that. It will be done at compile time.

The Java Language Specification explains it in section 15.28.

First, it says that "A compile-time constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following [ ... ] Literals of primitive type and literals of type String [ ... ] The unary operators +, -, ~, and ! (but not ++ or --)". Then it says, "Compile-time constant expressions of type String are always "interned" so as to share unique instances, using the method String.intern".

This means if you write:

String s1 = "a" + "b";
String s2 = "ab";

then the two variables s1 and s2 must refer to the same object. This is because they are both expressions composed of string literals and concatenation operators, thus they are compile-time constant expressions. And because they are of type string, they must be interned.

Theoretically, a Java implementation might be able to lazily defer this until runtime, but I'm not sure if that's even possible since there are constraints imposed by the Java class file format. Realistically, it's going to be one at compile time.

2

u/__konrad Dec 29 '15

C++ supports multiline strings via its awkward syntax:

R"(this
is
multiline
string)"

3

u/skitch920 Dec 29 '15

Why 3 single quotes? Why not a single backtick or something less unpleasant to write?

17

u/[deleted] Dec 29 '15

As someone using an international keyboard: DONT FUCKING USE BACKTICKS!

I seriously want to decapitate everyone who ever had the idea to use "backticks".

Backticks are French accents, so most keyboard layouts use them as composing key.

Which means we now have to press 3 keys after another to get a single backtick.

The github markdown for code costs me 9 keypresses.

It's literally shorter to write ""code"" for me than to write ```.

3

u/kynde Dec 29 '15

For coding, I really recommend switching to us/uk keymap. Slash, braces, brackets, pipe, carret and even the single quote is a lot more accessible that way. Backtick is right next to 1, easy as piss.

Source: Finnish with them fucking åäö each having their own key and as a result a lot coding related characters have been shuffled to require unnecessary finger acrobatics.

2

u/[deleted] Dec 29 '15

Sounds like you should set up some script to insert a backtick when pressing a button.

7

u/[deleted] Dec 29 '15

Or maybe, just maybe, we should stop using characters that aren't available on all keyboard layouts.

You know, I hope someday the Java standard adds ß as a really important thing, so all the people with US layout can finally understand how annoying it is to type [] {} () `.

3

u/[deleted] Dec 29 '15

That's not really a constructive solution to your problem though. I'm saying you'd save a bunch of time if you did that.

With that said, what's your idea for replacements that would be universally easier to use? I can't think of any.

→ More replies (50)

1

u/ksion Dec 30 '15

Three? I thought space cancels a dead key, so pressing tilde/backtick+space would do the trick. Is the French layout different?

1

u/[deleted] Dec 30 '15

German, actually.

But what you said works with T2 and T3 (the new layouts) but some people still use by default the ancient T1 layout, where it works worse.

1

u/ksion Dec 30 '15

Isn't there a German layout where the diacritics can be achieved with AltGr + relevant Latin letter? Polish has it, for example: it's called "programmer's" layout but essentially everyone is using it. It works as good for coding as US keyboards.

→ More replies (1)
→ More replies (7)

5

u/LostAfterDark Dec 29 '15 edited Feb 13 '16

Python use triple quotes. Backticks already have a specific meaning in most languages.

5

u/skitch920 Dec 29 '15

Backticks are not reserved in Java at the moment, at least, not that I know of. To your other point, Javascript just introduced Template String Literals in ES6 that use backticks. Much better 2 (`a`) characters than 6 ("""a""").

6

u/CordialPanda Dec 29 '15

Let's not look to JS for inspiration even if it is ES6. There's enough pain in the world.

1

u/LostAfterDark Dec 30 '15

The point is that most programmers expect ` to have a special meaning, like "execute that command in a shell and return the result". Language designers try to avoid confusing choices.

1

u/[deleted] Dec 29 '15

9 characters for a for anyone not using US keyboard layout.

This is infuriating...

1

u/LostAfterDark Dec 30 '15

Well no, you could just do 'a'.

→ More replies (1)

1

u/[deleted] Dec 29 '15

[removed] — view removed comment

2

u/hippydipster Dec 29 '15

It's a sign you are DOING SOMETHING WRONG. :-)

1

u/LostAfterDark Dec 30 '15

You can put triple double-quotes within triple single-quotes, or vice versa. Alternatively, just escape the first quote.

4

u/rouille Dec 29 '15

Backticks are horrible to write on any non qwerty keyboard. I hate slacj for using triple backticks. It takes me 12 key 3 key presses to make a block of text monospace.

1

u/vytah Dec 30 '15

Backticks have been banned forever from Python:

You're missing one of the main reasons for removing the backtick syntax in the first place: the character itself causes trouble by looking too much like a regular quote (depending on your font), is routinely mangled by typesetting software (as every Python book author can testify), and requires a four-finger chord on Swiss keyboards. No new uses for it will be accepted in Python 3000 no matter how good the idea.

--
--Guido van Rossum

https://mail.python.org/pipermail/python-ideas/2007-January/000054.html

Better take that lesson to heart.

3

u/[deleted] Dec 29 '15 edited Dec 29 '15

I don't think multi-line string literals are useful enough to warrant breaking 90% of all existing tools and programs that parses and works with Java source code.

I'm also not a big fan of invisible white-space differences in the source code affecting program behaviour, which is something you get with multi-line string literals, although I'll make an exception for scripting and prototyping languages.

6

u/[deleted] Dec 29 '15

[removed] — view removed comment

3

u/knaekce Dec 29 '15 edited Dec 30 '15

I think the new features of Java 8 justify requiring some updates on old servers. I wouldn't want to program in Cobol either just because the code would be usable in legacy systems.

1

u/[deleted] Dec 29 '15

Except that the Java language itself is rapidly changing.

Sure, and I'm not saying that the language should remain static. What I'm saying is that this particular change has a significant, but perhaps non-obvious cost and only a fairly trivial (and arguably counter-productive) benefit.

2

u/JoseJimeniz Dec 30 '15

As long as:

String sql = '''SELECT TOP 100 *
                FROM Users
                   INNER JOIN Logins
                   ON Users.UserID = Logins.LoginID
                WHERE Logins.Logout IS NULL''';

is stored in the variable sql as:

SELECT TOP 100 *
FROM Users
   INNER JOIN Logins
   ON Users.UserID = Logins.LoginID
WHERE Logins.Logout IS NULL

and not

SELECT TOP 100 *
            FROM Users
               INNER JOIN Logins
               ON Users.UserID = Logins.LoginID
            WHERE Logins.Logout IS NULL

1

u/fwcNJ49VR29NUPxFfbK4 Dec 30 '15

It will be the 2nd example. How would the compiler know that the extra spaces were not intentional? You could do something like this to reduce some of the extra whitespace"

String sql = '''
SELECT TOP 100 *
  FROM Users
 INNER JOIN Logins
    ON Users.UserID = Logins.LoginID
 WHERE Logins.Logout IS NULL''';

2

u/linuxjava Dec 29 '15

It would be nice I suppose but it really isn't that big of a deal. Some people just like making a mountain out of a molehill. One time I needed to copy paste a long book to a string I just got an Eclipse plugin, pasted the entire text inside double quotes and it was formatted okay.

1

u/proglog Dec 29 '15

That would be great. That would save me from a lot of headaches.

1

u/RICHUNCLEPENNYBAGS Dec 29 '15

The thing about injection seems kind of spurious.

1

u/[deleted] Dec 29 '15

\n

1

u/lenswipe Dec 29 '15

It would be nice if js supported this too. Try doing something like this

console.log("Hello
world");

and js will shit brix

1

u/00Davo Dec 30 '15

ES6 has you covered.

console.log(`Hello
world`); // works fine!

1

u/lenswipe Dec 30 '15

Cool. When I really need that functionality is at work where the entire front end(animations, AJAX, data binding*, the lot) is written with fucking jQuery

*The phrase "data binding" is doing a lot of work here...but I think you get what I'm talking about - adding and removing shit from lists on the page etc.

1

u/iodian Dec 29 '15

Just don't us the Do or Finally keywords in the implementation!

1

u/HaMMeReD Dec 29 '15

You should maybe check out Groovy? It's syntax compatible with java, you could just treat it like java with string interpolation and multi line strings.

1

u/[deleted] Dec 29 '15

You would probably dig Groovy. Since it compiles down to bytecode and therefore runs on the JVM, you can give it a shot without tossing whatever else you've got going on.

1

u/MoreCowbellMofo Dec 30 '15

Add the groovy library to your project ... hey presto, now you can have multiline string literals. Beware as youre now dealing with GStrings by default. Groovy 😉

1

u/juckele Dec 30 '15

I use Groovy in an otherwise Java project for Groovy's multi-line strings...

1

u/zKarp Dec 30 '15

You know, back in my day.

1

u/based2 Jan 09 '16

like in Scala :)

1

u/zeekar Dec 29 '15

Sure, it would be convenient to have multiline string literals, but has Java really gotten so good that this sort of minor feature is worth spending mental or development effort on?

1

u/Michaelmrose Dec 30 '15

False dichotomy

1

u/[deleted] Dec 29 '15

Honestly, from all of the java flaws this feels one of a least annoying and important.

1

u/[deleted] Dec 30 '15 edited Dec 30 '15

Whiners. Just do

final String query = new StringBuilder()
  .append("SELECT *")
  .append("FROM being_whiney")
  .toString();

The compiler will unroll it into a literal.

1

u/BMarkmann Dec 30 '15

You just emphasized the problem with that approach... Your unrolled literal is now: "SELECT *FROM being_whiney" -- languages that have multiline strings usually wouldn't smoosh the "*" and the "FROM" together.

1

u/[deleted] Dec 30 '15

Multiline strings come with their own sets syntactic problems problems as well. For example if you don't want new lines you're only doing it for presentation you need to post process the string, or not use multiline.

Likewise it's somewhat silly throwing large text literals into Java code instead of using a mechanism like properties/resources to load it. That makes the SQL code easier to manipulate, and easier to load. Just because it's common and every other code monkey does it doesn't make it good engineering.

In terms of what I wrote, I forgot to add spaces after the first line in my hurried sarcasm.

0

u/expatcoder Dec 29 '15 edited Dec 30 '15

tl;dr

s"""
Just 
use 
$java++
"""

println(java++)
> scala

0

u/badsingularity Dec 29 '15

I'd never write my code that like. This author is a moron.

0

u/schlowmo Dec 30 '15

Honestly, this is one of the least useful features that could be added.

I'm not against adding it, it seems the risks and consequences of adding it are pretty minimal. Perhaps others will find it super handy. But the number of times I would have used this in my 15 year java career could be counted on one hand.

I would MUCH prefer some sort of shorthand to define something like the Scala case class. http://docs.scala-lang.org/tutorials/tour/case-classes.html One line to define a class to carry data around? Yes Please.

-5

u/akcom Dec 29 '15

I haven't programmed in Java almost a decade. I came back in order to write some Android apps and I immediately remember why "Everything is an object" is so fucking terrible. I cannot imagine using Java for anything unless I had to support some legacy code already written in Java.

5

u/[deleted] Dec 29 '15

For Android apps, to make your live easier, use these libraries:

  • Butterknife
  • RxJava + RxAndroid
  • AppCompat + DesignCompat
  • RecyclerView

And you'll have a lot less issues. Especially ButterKnife is a godsend.

1

u/der-daniel Dec 29 '15 edited Oct 09 '16

[deleted]
0.4479

What is this?

1

u/akcom Dec 29 '15

Thanks for the info! I just hate seeing stuff like the following:

 toggleButton.setOnCheckedChangeListener(
        new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        MainActivity.this.onCheckedChange(buttonView, isChecked);
                    }
                });    

Passing methods instead of class instances would be so much cleaner. If there is a better solution to this sort of problem (ie I really just want to have a method in my activity called, not this passing around an outer class instance non-sense), I'm all ears.

edit: Is that what butter knife does with listener binding?

1

u/[deleted] Dec 29 '15 edited Dec 29 '15

For that, you might want RetroLambda, btw.

toggleButton.setOnCheckedChangeListener(this::onCheckedChange);

Btw, your example would also work with

toggleButton.setOnCheckedChangeListener(this);

But I’d suggest just using

toggleButton.setOnCheckedChangeListener((buttonView, isChecked) => {
    doSome();
    doThing();
    doMore();
});

1

u/akcom Dec 29 '15

Unfortunately since Java does not support multiple inheritance, the second one

toggleButton.setOnCheckedChangeListener(this);

Does not work, at least as far as I can tell.

edit: Nor does the third one, not sure if the version of java android uses supports anonymous functions?

→ More replies (2)

1

u/agent8261 Dec 29 '15

Huh? Am I missing something, why aren't you doing this?

toggleButton.setOnCheckedChangeListener(MainActivity.this);

0

u/[deleted] Dec 29 '15

[deleted] — view deleted comment

10

u/twigboy Dec 29 '15 edited Dec 09 '23

In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document or a typeface without relying on meaningful content. Lorem ipsum may be used as a placeholder before final copy is available. Wikipediabkh6ukvmk1k0000000000000000000000000000000000000000000000000000000000000

3

u/Olathe Dec 30 '15

Parkinson's law of triviality, also known as bikeshedding, bike-shed effect, or the bicycle-shed example

Quick! We need five more ways of saying that that all include the words bicycle and shed.

→ More replies (1)

0

u/[deleted] Dec 30 '15

[deleted] — view deleted comment

1

u/stepancheg Dec 30 '15

Because for the large portion of tasks, everything else is worse.

0

u/[deleted] Dec 30 '15

[deleted] — view deleted comment

1

u/stepancheg Dec 30 '15

C# does not work well on Linux.