175 points · by sleepyhead · 13y ago · 128 comments
Creating the UI was easy enough, but making an HTTP response was hell. The simplest HTTP GET took around 30 lines of code, and the compiler kept complaining about unhandled exceptions (I know the URL is fine, it's a fixed string I can see, it's not going to throw MalformedURLException, I don't want to catch it, thank you. What? I can't compile without it?). Wrapping the calls up in try/catch blocks was easy enough (if a bit verbose), but now the variable only existed in that scope.
I know I'm new enough that I can't form an opinion about the language, but I know that something that has as simple an interface as an HTTP GET call shouldn't take 30 lines of boilerplate to do. I'm wondering how people deal with this issue (I'm guessing it's a lack of a good standard library?). What attracts people to the Java world? Is it the tooling (Eclipse was, admittedly, very good about auto-fixing my mistakes). Is the verbosity just "the way it is", or am I doing something wrong?
One area in Java that is still incredibly annoying, however, is the ubiquitous getter/setter pattern that bloats all Java code for zero benefit to anyone.
The main goal behind the standard Java library (from what I have gathered) has always been to provide a mid-level API to most possible functionality in an OS so that library developers can develop simple Java libraries that work across all platforms supported by Java. The big changes to the JRE libraries in the early years of Java was really what caused all of the big problems Java has had. Since the JRE stopped evolving, (server side) Java has really thrived with most code being very easily deployable anywhere and everywhere in the enterprise.
If you're going to program in Java, you should use libraries for commonplace tasks, and you should use an IDE to autocomplete package names and 'run' blocks. If you do this, Java really does work very well. For huge classes of coding tasks, the excessive boilerplate and compile time checks / exceptions can make it possible to tell very quickly if code is correct or not even without tests which is a major boon for code review purposes in enterprise.
Ultimately what I'm trying to say is that Java really does work very well and has come a very long way in creating a very productive environment for large projects, and it's why Java is so popular and heavily used even when at first glance it looks terrible.
For exceptions, there are two types. Checked exceptions and runtime exceptions.
* Checked exceptions need to be explicitly handled in your code, or it doesn't compile. * Runtime exceptions can just happen, you don't need to check them. I personally don't really like the runtime exceptions because they can hide in thousands of place and throw when you don't expect it. However, you don't need to check them so it makes for less verbose code... but it's like putting your head in the sand.
To reduce verbosity of exception handling, I find a pseudo-solution is to just propagate the exception up the stack and deal with it later. It depends for what exception, but for instance, a MalformedUrlException for which you KNOW the Url is fine, can be checked much higher in the call stack. You will save yourself the local verbosity, which hides meaning, and really if the Url is malformed, you might not want the app to keep running; if it's hard-coded you should expect it to be right. It's in the same spirit of Go's `regexp.MustCompile(string)` that makes a compile error if the hardcoded string you give it is not a valid regex.
That being said, Java is a daily pain, but the extensive tooling makes it usable.
If I am writing live code, I...want to write code. I don't want something to do it for me. If its in a language I am comfortable with I can generally write it more effectively than a tool in a toolbox and know how to fix it when it breaks.
Maybe I am just a control freak.
So somewhere up in your class, you'd write:
private final static URL someUrl;
static {
try {
someUrl = new URL("http://something.com/");
} catch(SomeException e) {
crashAndLogSomehow(e);
}
}
You would thus know right when you load your app, before distributing it, whether an exception can happen. In your code, you wouldn't have the try/catch block hiding the real meaning.Java 7 also lacks very useful features like lambdas, mixins, nested methods etc.
However, Java is a good choice for many projects, because it has fantastic tooling, lots of libraries and it's relatively fast. The tooling is really a huge advantage of Java. When I refactor Java code in Eclipse, I sometimes wonder how would I do this when it was Python (which I use for smaller projects).
I wish there was a language combining the pros of Java & Python...
Dart is closest to my ideal of a general purpose language.
Portability, security (automatic memory, static typing, etc.): you cannot bore a hole in your feet when shoving a nail. And backed by a huge company. Relatively fast. More reasons there: http://c2.com/cgi/wiki?WhyJavaIsGreat
>exception-related problems
A common hack it to wrap your code in a dumb try/catch block at the uppermost level. That way there is no scope-related problem and the compiler won't complain. Ofc that should only been done in a situation such as yours, not in "real life" (i.e. "entreprise world" for java).
Unfortunately its extreme object-orientation, lack of type inference and polymorphism, lack of first-class functions and anonymous functions, and awkward error handling, make it quite painful to actually write (at least without code completion and automatic refactoring), while encouraging a number of poor design choices and serious source code bloat. It's too high-level to be useful for systems or game programming, but it's not expressive enough to be very productive for programming at a higher level of abstraction, and it's useless for scripting. So, it's mostly used for building enterprise web services. And Android apps.
Like Smalltalk, Eiffel, C#, VB.NET
> It's too high-level to be useful for systems or game programming
True if you are speaking about AAA games or writing kernels, for everything else lots of people seem to be quite successful using it.
> So, it's mostly used for building enterprise web services. And Android apps.
And in embedded environments powerful enough to run it, like windmills, electricity control meters, missile radar controls, blue ray players, J2ME mobiles, ...
I plead with you to check out http://jmonkeyengine.org and see for yourself
How does dependency injection throw type safety out the window? You can only inject types that are a subtype of the declared type. Overridden methods can't extend the types of checked exceptions that are thrown [1]. I fail to see the hole in the type system here.
I'm not a Java programmer, but I use dependency injection all the time in other language, including dynamic languages like Ruby. I find it very helpful for isolating bits of code and making extendable interfaces. I'm genuinely curious if there's a major weakness lurking in DI that I haven't discovered yet. Please help me remove my blinders.
[1] http://stackoverflow.com/questions/5875414/method-overriding...
About the try/catch, it sounds like something that'll come back to bite me in the ass, so it's a bit unfortunate that I have to pick between being verbose and handling exceptions that can never occur, or being terse and hacky...
try {
*your stuff*
} catch (WhateverYouDontWantToHandleException e) {
throw new RuntimeException(e);
}
Then at the outmost level of your code somewhere you catch RuntimeException and tell the user a general error occurred or something. You will still get the root exception so you can log with stack trace and eventually implement some specific exception handling for it if necessary.The only reason why large shops are attracted to the Java world is because the endless supply of low cost developers and a tooling ecosystem which helps such developers survive in that ecosystem.
That is the No 1 reason every manager I've know has ever given for using Java.
For new developers that want to do more than trivial things in Java, reading "Effective Java" will help you avoid many of the pitfalls in the language.
As an example, the current best practice around exceptions is that checked exceptions were a mistake. Don't use them in new code. For code that must deal with checked exceptions, you can create your own general exception class derived from RuntimeException, then use a try/catch block to throw your own runtime exception that wraps the checked exception. (But do this smartly; for cases like IOException with web stuff, it is sometimes easier to add "throws IOException" to all your related methods than to exhaustively catch and rethrow.)
As a second example, do not use the JDBC library directly. It is very poorly designed and direct usage can very easily lead to resource leaks. Use something like Spring's JDBC templates or roll your own. (I generally find Spring to be a bloated mess, but the JDBC template stuff is very useful.)
But perhaps the best bet is to use a more modern JVM-based language (of which my favorite is Clojure), though use of these alternatives on Android may be problematic.
You're not alone. I find checked exceptions to be an invaluable language feature.
I had a somewhat long discussion with a colleague about this over the past year, and we looked at all the error cases in the C standard library and came to the conclusion the Java API was probably throwing checked exceptions in one or two corner cases where it should throw unchecked runtime exceptions. I'd be curious what other people think about this. I think specifically, I was asking him (a more Sr. engineer who has used Java heavily and considers it basically good) why closing an IO stream in a finally block throws another checked exception.
In short, I don't think you're doing anything wrong.
[0] See this, but I should caveat this with saying it's a bad API as designed to be consumed by an application. http://www.tbray.org/ongoing/When/201x/2012/01/17/HttpURLCon...
[1] http://developer.android.com/reference/org/apache/http/clien...
In the end, I used this excellent library: http://loopj.com/android-async-http/
It's asynchronous, but it still required the work to be done in an AsyncTask, which is odd to me (why spawn a thread to spawn another thread?), but it wouldn't work in the main thread, and Android was good enough to tell me about it.
I'm glad that I'm not doing anything wrong, but I'm also sad because I was hoping I was doing something wrong. Thanks for your reply!
http://android-developers.blogspot.com/2011/09/androids-http...
I think that checked exceptions are a failed experiment in language design. They basically force you to leak abstractions all over your code, reintroducing a lot of the pain of error codes.
public String setCache(String key, String value) throws CacheUnavailableException,CacheWriteException {
try {
...
} catch (SocketException e) {
throw new CacheUnavailableException(e);
} catch (SomeMemcacheException e) {
throw new CacheWriteException(e);
}
}
This will allow library clients to catch exceptions that mean something to them, not exceptions that only make sense if you know how the library is using memcache.In production code, no matter the language, you have to guard against these issues. The nice thing about typed objects (immutable, anyway), is that once constructed and validated, they do not require tedious validation at every method and client they are passed into. That actually results in less boilerplate, and less test writing.
So just remember, Java always assumes your code is production-bound and requires upfront planning and checking. That's why it's unpleasant to prototype with.
Checked exceptions bugged me as well when I was first introduced to Java. I honestly still don't like the fact that exception handling is enforced at the compiler level. It feels intrusive.
I did write a short blog post on the subject, which may be helpful. As a disclaimer, I'm not a full time Java dev.
Using an IDE in Java is almost a necessity. With that, people mostly just get use to it.
I recently had to return briefly to Java (also for android). All I had to do was recursively chmod a directory. This is something that once seemed simple to do in Java, and indeed it is still simple. However now when I write that code I am painfully aware of how unnecessarily long and complicate it is. However, the larger project involve cross compiling python with c-extensions (and external c dependencies), so I do appreciate the relaxation that comes with Java boilerplate.
I agree checked exceptions are annoying, though I have kind of grown to like them since they force me to think about failure cases.
You're going to hate this answer, but honestly, after you do Java for awhile the lines of code just become noise you don't notice... it's like reading and writing XML by hand; kinda sucks, but eventually you just stop noticing.
I should read about checked exceptions more, I don't currently understand the difference between checked and unchecked.
I don't hate that answer, I was just hoping it wouldn't come to that :P Getting used to a language to get one's job done is fine, but it's not something that would cause one to fall in love with said language...
You probably want to have at least one exception "catch" block somewhere, such as within a message/event handler loop, but checked exceptions force you to write the error catch at the place where a routine is called, and MANY such checks for other calls, rather than at one place at the top of an operation.
While this might make sense in a GUI/AWT/Swing app, it does not make sense in a batch processing app (or web app). In that case, there is no user to get a dialog box, you simply log "it did not work due to ..." and move on. Checked exceptions make you write a bunch of extra code.
That is about 4 lines, and a try finally statement around that and a try catch statement around that again and that is all that is required. 15 lines maybe, a bit more if you want to move it of the main thread (but then you are, IMHO no longer just doing a get request).
Lady Java - https://www.youtube.com/watch?v=Mk3qkQROb_k
The Streaming - http://jz11.java.no/trailer_video.html
Java 4-Ever - http://jz10.java.no/java-4-ever-trailer.html
There are some great talks from last year's conference there as well, many of them in English. The one by Tim Berglund about Git is great!
Object fields = Data Division; Bean = Copy Book
Practices that actively discourage functional style programming in favor of procedural style programming with widely scoped variables.
I'm glad Java is more widely used than C++, but it's a hard language to really love, despite being (mostly) how I earn my living.
Another example is the inability to just read a local file into a string with a simple API call. It's this way, again, because in production the program has to reason about paths and file systems and can't make assumptions about the validity (or size) of the file you just want to load and play with.
In production code, no matter the language, you have to guard against these issues. The nice thing about objects (immutable, anyway), is that once constructed and validated, they do not require tedious validation at every method and client they are passed into. That actually results in less boilerplate, and less test writing.
So just remember, Java always assumes your code is production-bound and requires upfront planning and checking. That's why it's unpleasant to prototype with.
I know the video is a joke, but that was harsh. I think there are quite a few good open source languages that only took about 5 years or so to get going with a decent runtime library. What takes years is to get adoption of new tools from the grass roots up, more so than implementation.
What if the button software was written in Java and did, in fact, nothing. Perhaps with a nice 40-something line stack trace in the log file. Meanwhile, a completely new worm targeting the Java platform crashed most of the infrastructure.
Guy...
You don't just rewrite code that's been through the FDA approval process. It doesn't work like that. If you want to replace a java or c based medical imaging viewer... you can... but you have to prove it won't kill anybody. Or make any doctors cut off the left leg instead of the right one because a transform is flipped due to a DICOM attribute being interpreted incorrectly. Or that RTP calculations are still correct, and the PET/CT fusion is registering correctly. You can't get Radiation dosage calculations wrong by even a tiny amount.
And you have to prove all of that to the FDA and sign thousands of sheets of documentation swearing to it. And the standard fine print in that documentation makes you criminally liable if a bug is found.
And that's just 1 tiny industry that java is used in.
Multiply that difficulty by every life and death or money based industry and you begin to get an idea of what a monumental task getting rid of java would be. Think oil extraction and exploration systems... uh... no excuses there... they MUST work. Think industrial control systems... software for nuclear facilities, or even software for a simple coal based energy plant, can't just be thrown together. People in a city or area depend on these facilities to meet their energy needs.
Maybe I'm misunderstanding you... what is your definition of "wouldn't take long"?
I took three years of it in community college and could probably pick it up again in a hurry. If I did pick it up again, I could probably easily double my current (very reasonable) salary.
But I'll be damned if I go back to writing COBOL, and I know a great many programmers like myself who feel the same way. And (modesty aside for a second here) they tend to be the better programmers.
So you're left with the "for-the-paycheque" programmers writing COBOL, and the programmers who couldn't find a job they cared about more.
That's who's going to be rewriting all those mission-critical COBOL apps once people want to start expanding into more modern languages.
I spent £100 on Geecon last year.