r/programming • u/MarkusWinand • Dec 29 '15
Please, Java. Do Finally Support Multiline Strings
http://blog.jooq.org/2015/12/29/please-java-do-finally-support-multiline-strings/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
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
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
Dec 29 '15
[deleted]
6
u/MaxNanasy Dec 29 '15
AFAIK parameterized queries don't generally allow parameterized table names
1
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.
→ More replies (1)2
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
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
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
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
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
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
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
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).
→ More replies (1)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
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
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)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
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
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.
→ More replies (21)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.
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
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)→ 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)4
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
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.
→ More replies (7)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.
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
5
2
u/pkulak Dec 29 '15
He brought up SQL injection and consumer formatting as issues, and neither were solved with his solution.
2
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
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
javacwill actually perform the concatenation of string literals forfinalfields. See my other comment for examples.3
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
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 usestrcatto 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
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
s1ands2must 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
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
Dec 29 '15
Sounds like you should set up some script to insert a backtick when pressing a button.
7
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 [] {} () `.
→ More replies (50)3
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 (7)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
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)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
1
Dec 29 '15
[removed] — view removed comment
2
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 Rossumhttps://mail.python.org/pipermail/python-ideas/2007-January/000054.html
Better take that lesson to heart.
3
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
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
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 NULLand not
SELECT TOP 100 *
FROM Users
INNER JOIN Logins
ON Users.UserID = Logins.LoginID
WHERE Logins.Logout IS NULL1
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
1
1
1
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
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
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
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
1
1
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
1
1
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
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
0
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
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
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
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
Dec 29 '15
[deleted]
→ More replies (1)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.
0
Dec 30 '15
[deleted]
1
414
u/[deleted] Dec 29 '15
Multiline string LITERALS.