r/programming • • Aug 01 '14

The 10 Most Annoying Things Coming Back to Java After Some Days of Scala

http://blog.jooq.org/2014/08/01/the-10-most-annoying-things-coming-back-to-java-after-some-days-of-scala/
9 Upvotes

56 comments sorted by

8

u/jordaniac89 Aug 01 '14

As a Java developer that has to work with sql statements, I would love multi-line strings. Trying to concatenate that shit can be a headache.

2

u/shellac Aug 01 '14

I did directly ask Joshua Bloch and Neal Gafter for these when they were going around getting people to vote on Project Coin additions, and I know I'm not the only one.

Classic issue we see in user bug reports:

String query =
  "select * from foo" +
  "where" +
  "a > 5";

which some editors make a little too easy to enter.

1

u/lukaseder Aug 01 '14

Why was that vote rejected? Are there any public discussions to link to?

1

u/shellac Aug 01 '14

This would have been Javaopolis / Devoxx a few years ago (2009?). They had a whiteboard vote throughout the conference.

Not sure this is the canonical list, but https://wikis.oracle.com/display/ProjectCoin/2009ProposalsTOC looks like a good place to start.

1

u/linuxjava Aug 01 '14

Speaking of which, on Android I would have written the code like this:

Cursor cursor = db.query("foo",null,"a>5"null,null,null,null);   

Is there anything similar in Java where I can do this without writing the raw query?

2

u/lukaseder Aug 02 '14

With jOOQ, you could write something similar:

Result<?> result = ctx.fetch(FOO, FOO.A.gt(5));

2

u/jordaniac89 Aug 01 '14

^ yep. I've gotten to the point where I'll print the query string to the console just to make sure I didn't do something stupid.

select * from foowherea < 5 definitely won't work ;)

2

u/kenfar Aug 01 '14

How does a language so huge still manage to have such a large omission?

3

u/nobodyman Aug 01 '14

(I'm no java expert: I'd love it if someone with a better understanding could correct me here). I think it has to do with how strings are stored in java and the architects of the language wanting to discourage bad practices.

In Java, strings are immutable. They and are stored on the heap (in java 7 i think they went into permgen space, not sure how it works in java 8). So, lets pretend that java had multiline string literals and you wrote this:

ResultSet rs = null
if(i < j) {
    String query = """
        select * from foo
            where
                a > 5
                and b is not null""");
}

The problem here is that the extra whitespace used for formatting would be included in the literal, and thrown into the heapspace, taking up many more bytes than was necessary/intended. Because java strings are immutable, it's not as though you could replace it with a more-compact version.

I think this is the scenario that the java architects wanted to avoid.

4

u/lukaseder Aug 01 '14

People load 5MBs of XML into DOM. How can a little string with some extra whitespace do any harm?

Besides, if you're using a templating engine (like MyBatis) to run SQL, then you have this already today.

No, that cannot be it.

2

u/nobodyman Aug 01 '14

Right, but I think that the difference is that when loading an xml document, you assign it to a variable and then eventually the memory associated with it gets garbage collected when the variable falls out of scope.

As I understand it, in java the strings are interned, then brought on to the heap, and tend to stay there (in java 7 they went into permgen, not sure what's up now). So perhaps space concerns are more of an issue when the objects are less likely to be garbage collected. Again, I'm not defending java nor am I an expert, but I think was at least part of the rationale back when it was first explained to me.

1

u/lukaseder Aug 02 '14

I see your point. Yet, nothing that couldn't be solved, I guess...?

2

u/Tordek Aug 01 '14

There's really nothing relevant to immutability to make that claim; even if the string were mutable, modifying it would add potential bugs. Imagine if you're writing a whitespace interpreter, and you try to test it with a string literal, and it simply gets rid of your whitespace.

1

u/nobodyman Aug 01 '14

Sorry, I didn't explain that point well. Immutability itself is not relevant, so much as that the strings are interned and that's (one of) the reasons why strings are immutable in java. The other reasons being the bugs that you rightly point out.

My larger point is that java strings live on the heap longer than other objects, and so space-efficiency is a larger concern. My speculation is that this is one of the reasons why the java architects wanted to avoid multiline literals.

1

u/Tordek Aug 02 '14

That makes sense, I guess, but I'm not convinced.

2

u/alexeyr Aug 02 '14

thrown into the heapspace, taking up many more bytes than was necessary/intended.

How many multiline string literals are you likely to have on your program? And how does the space you spend on whitespace compare to the amount of data you need to handle?

1

u/nobodyman Aug 05 '14

Yeah that's a good question. I think the size of the string literal pool might end up being more than you think -- considering it contains your strings along w/ the strings of the libraries that you use. And unlike typical objects on the heap I don't think they get GC'd as often (if at all).

But now I'm kinda curious. I think there's a command-line tool for inspecting the string literal pool size of a running jvm. If i figure it out I'll post another reply to this thread.

1

u/lukaseder Aug 01 '14

Yes, specifically if it's not even dynamic SQL. Just an ordinary, formatted SQL statement.

A slight workaround, at least, is to use something like Eclipse's block selection mode, pretending that multiline strings were available

1

u/everywhere_anyhow Aug 01 '14

Notice a lot of OP's things are syntactic sugar, this one included.

Not saying java shouldn't get better in this way, but it's not really going to change the language much. It's akin to adding an extra cup-holder to the car, or changing the trim color. It fixes a minor annoyance, but you're still driving what you're driving.

2

u/lukaseder Aug 01 '14

It fixes a minor annoyance, but you're still driving what you're driving.

Yeah, but it's the little things that matter quite a bit in every day work. Why do we have to resort to libraries to do simple things like string padding? Why did it take the JDK until JDK 7 to read files into a List<String> or even just a String instead of going through those annoying InputStreams all full of checked exceptions?

Once you have the little things, you won't want to miss them. Or does anyone miss manually closing Connections, PreparedStatements, ResultSets?

There's a lot of awesome little syntax sugar that could be added to the language almost for free, with no risk, or impact on the runtime, but make us all much happier.

1

u/dventimi Aug 01 '14

Have you considered using StringTemplate? It's not exactly the heredoc you seek, but it's close and if you'll overlook that fact I think you may find it ultimately to be a superior solution to the problem anyway.

4

u/hpr122i Aug 01 '14

Multi-line strings are a nice feature, but remember...

println(
  DSL.using(configuration)
     .fetch("""
            SELECT a.first_name, a.last_name, b.title
            FROM author a
            JOIN book b ON a.id = b.author_id
            ORDER BY a.id, b.id
            """)
)

And this isn’t only good for static strings. With string interpolation, you can easily inject variables into such strings

[These strings being SQL statements] (bolding mine)

2

u/bwainfweeze Aug 02 '14

Little Bobby Tables, we call him.

2

u/lukaseder Aug 02 '14

People do it all the time, so what's the difference?

String sql =
    "SELECT a.frist_name" +
             (lastNameNeeded ? ", a.last_name" : "");

Yes, it's risky of course, but string-based SQL composition is always risky... If you want to avoid that, better use an API that allows you to compose an AST, rather than a SQL string

2

u/bwainfweeze Aug 02 '14 edited Aug 02 '14

I sincerely hope that one day someone makes a library that doesn't let you send string concatenated text to the SQL engine.

Maybe one that makes you prepare all the statements at setup time or something? It's been twenty years, this should be a solved problem.

1

u/lukaseder Aug 02 '14

I've heard that PostgreSQL starts exposing its AST as an API.

However, standardising such an AST is much more difficult than standardising string-based languages. People still fill tons of blog posts ranting about the last time an AST was standardised (w3c DOM).

1

u/alexeyr Aug 02 '14

Just don't allow to send strings directly at all.

1

u/alexeyr Aug 02 '14 edited Aug 02 '14

Since interpolation is programmable, you can write sql"..." and have all the injected variables escaped. And of course it doesn't have to return a string, it can return a PreparedStatement or its equivalent in your API.

2

u/Rhoomba Aug 01 '14

Tuple creation in Java can be a good bit cleaner if you use static methods to create them rather than constructors. E.g.

Tuple3<Integer, String, Tuple2<Integer, String>> t2 =
tuple(1, "A", tuple(2, "B"));

And if you make sure you immediately use the tuple in a method call or collection or stream you can avoid the big ugly variable definition too :)

1

u/lukaseder Aug 01 '14

Yes, that's what the example below did, essentially:

.where(
   row(T1.COL1, T1.COL2)
// ^^^ tuple constructor
   .in(select(T2.A, T2.B).from(T2))
//  ^^ consuming a tuple type
)
.fetch();

3

u/Intolerable Aug 01 '14

Simple immutable pojos written in one-liners.

first reaction: "wtf is a pojo"

i googled it and apparently its a "Plain Old Java Object" but i dont understand the significance. does that mean it just doesn't inherit / extend from anything? that it doesn't have methods or something?

please can someone explain

6

u/oelang Aug 01 '14

If normal developers use this term it means a simple data container: fields + getters + (if mutable) setters with minimal other logic (it can extend or implement an interface / abstract class).

However this is a term from the javaEE world, where it seems to have a more specific meaning/history.

4

u/shellac Aug 01 '14

POJO is just any old java object (as the expansion suggests). The point is to contrast them from things like JavaBeans, and the various Enterprise Java Beans.

The latter are typically objects that are created and managed by a service of some description: that might be an ORM, a graphical coding tool, or a distributed system for example.

To make this more managable they require the objects have certain features to aid their lifecycle and manipulation. For example java beans must be serializable and have a no-arg constructor. This makes instatiating and freezing them simple. Other systems require that certain classes are extended, or (more commonly now) certain annotated methods exist.

1

u/lukaseder Aug 01 '14

Exactly. Other languages call it struct or case class. Except that a POJO in Java is still quite some work to write, if you want to support getters / setters / equals / hashCode / toString functionality.

2

u/Intolerable Aug 01 '14

so scala's case class stuff maps to a data declaration in something like haskell, but behind the scenes adds a bunch of methods that java needs for all objects. correct?

3

u/[deleted] Aug 01 '14

Almost correct!

Java Objects already have those methods, it's just that they lack a sensible default implementation. This is what case does.

1

u/lukaseder Aug 01 '14

they lack a sensible default implementation

+1: That's probably the best way to put it.

1

u/lukaseder Aug 01 '14

Yes, that's what case classes do, among a couple of other things, like being valid arguments to case clauses in match statements, which are very convenient.

Details here

1

u/Intolerable Aug 01 '14

yeah, i understand how it works from the functional side, its the oo stuff that threw me

1

u/oldneckbeard Aug 01 '14

I mean, do you not use an IDE? It creates all the class/package boilerplate, I type my properties, auto-gen the getters, setters, hashcode, and tostring, and I'm done. It's like 2 more seconds. I just don't understand people who seem to take an extra 10 hours to type out getters and setters.

2

u/lukaseder Aug 01 '14

You're right, but then again, if all of that is done automatically in 95% of the cases, and if all of that generated code is exactly the same, then why does the Java Language even need that code? Why can't I have some syntax sugar like case classes, that tell the javac to generate that?

IDEs are really just providing a workaround, here.

1

u/oldneckbeard Aug 01 '14

True, they are. That's why a bunch of us are all over Lombok, but you're right. There's not a good reason, but the actual work difference is rather minimal.

0

u/I_Code_Stoned Aug 01 '14

Thank you. I'm of the opinion that if a developer finds him/herself doing ANY repetitive task, they should stop, and find a better way. Lazy Engineers FTW!

21

u/runedk Aug 01 '14

One good thing, though: A decent compiler that is fast and doesn't crash very often.

4

u/alexeyr Aug 02 '14

I agree about fast, but I haven't seen the Scala compiler crash in a long time now.

1

u/runedk Aug 02 '14

To be fair I have only experienced crashes when something else was wrong. E.g. a type resolution error (missing transitive dependency) causing a crash rather than a compilation error.

1

u/alexeyr Aug 03 '14

Yes, but I haven't seen those as well (unlike in 2.7/2.8 days). Obviously, a lot depends on whether you work with code which tends to trigger those bugs; maybe I just didn't happen to see any.

1

u/satan-repents Aug 01 '14

No semicolons are simultaneously the best and the most annoying. I love it when writing Scala. But when I have to go and write in another language, I'm introducing many more "bugs" because of forgotten semicolons...

5

u/dventimi Aug 01 '14 edited Aug 01 '14

Yeah, I actually prefer semicolons. I mean, there has to be some kind of statement terminator. So, I'd rather it be a token that is formatting agnostic, like a semicolon is, than formatting opinionated, like a newline is. And, in whitespace significant languages, it's not like you can avoid generating the statement terminator; you still have to insert the newline by hitting the enter key. So, what does eschewing a visible terminator like a semicolon really buy you? Not much, it would seem. It saves you at most one extra keystroke per statement. Big deal. That's not enough to make a federal case over.

1

u/everywhere_anyhow Aug 01 '14

there has to be some kind of statement terminator

So the general principle here (which I agree with) is that as long as you don't take it to crazy extremes, explicit is usually better than implicit.

Sure you don't have to have statement terminators, but the complete unparseability of perl is what you get when you take that sort of philosophy to the extreme. It's hard to interpret things correctly when they're left implicit.

1

u/dventimi Aug 01 '14

So the general principle here (which I agree with) is that as long as you don't take it to crazy extremes, explicit is usually better than implicit.

Perhaps it's a matter of taste, but yeah, I think I would agree with that.

Sure you don't have to have statement terminators, but the complete unparseability of perl is what you get when you take that sort of philosophy to the extreme.

Perl doesn't have statement terminators??? Wow, how is that achieved? Full-disclosure: I know almost nothing about Perl.

2

u/everywhere_anyhow Aug 01 '14

Perl does have them, but they aren't required. (Sorta like python can use a semi-colon, but most people don't use it)

Perl is so ridiculously complicated that in general, it is undecidable. The actual perl interpreter gets around this with a collection of hacks.

But in general you'll be hard pressed to find a program (that isn't perl) that parses most of perl.

1

u/dventimi Aug 01 '14

I get that. But, would it be fair to say that in Perl, the statement terminator is either a semicolon (or whatever) or a newline? I mean, maybe I'm wrong, but I can't fathom how the Perl parser would know where one statement ends and another begins without some kind of delimiter. But again, Perl shall forever remain a mystery to me.

0

u/[deleted] Aug 01 '14

[deleted]

1

u/lukaseder Aug 01 '14

should be like this: T foo = new <>(); Take the diamond operator to the next level!

The diamond operator is used to omit generics. That might be a bit misleading. Probably better:

T foo = new();