6 ms·
This is irrelevant, but I just had my first Java experience yesterday. I decided to make an Android app, it's a simple remote control for hobby projects (Raspbe
by StavrosK 13y ago
This is irrelevant, but I just had my first Java experience yesterday. I decided to make an Android app, it's a simple remote control for hobby projects (Raspberry Pi/etc) that gives you a customizable UI with buttons that perform API calls. It'd be pretty simple to do in Python, which is the language I am proficient in, but Android development sounds fun so I wanted to get started in that.
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?
- peroo 13y agoVerbosity is Java's middlename. That said, 3rd party libraries can get you a long way.
- StavrosK 13y agoIt looks like it, I just wish that the most frequently used libraries were standard in the language. That said, it's really magical for me to write something that runs natively on my phone, so it's still lots of fun.
- bru 13y ago>What attracts people to the Java world? 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 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).
- StavrosK 13y agoI think the last two reasons are the most important ones, as the first to are relatively common. 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...
- troels 13y agoWell, in more forgiving languages, such as python, you are just implicitly being "hacky" as you put it. E.g. errors - if they ever occur - will happen in runtime. Java tries to move this to compile time, making them visible. It's a tradeoff really.
- StavrosK 13y agoNo, in Python you never silentrly ignore all exceptions (well, you can, but it's a big no-no). You can just opt to not handle them, but they'll crash your program. It's a tradeoff, as I know which exceptions are likely to become a problem and which aren't, and I can choose to handle the relevant ones and let it crash in the rare case that an exception I didn't think likely occurs. In Java, I have to handle malformed URL exceptions, even though I can see the URL in front of me, and if it's not malformed the first time, it'll never be. I see your point about runtime vs compile time, but my issue is with mandatory vs optional handling. I guess you can add "throws MalformedURLException" to let it bubble up, which is kind of the same thing, though (although you have to add all the exceptions you don't want to handle there, in that case).
- shawabawa3 13y agoThe reason is that Java is designed for enterprise, where "I know which exceptions are likely to become a problem and which aren't" cannot be trusted. With giant code bases and mediocre developers you kind of need to have checked exceptions or you'll have exceptions popping up in the most unexpected places. (I'm a Python dev and hate Java)
- spacemanaki 13y agoWhich API were you using? Java's HttpUrlConnection is notoriously badly designed [0] On Android (and elsewhere of course) you can use Apache's HttpClient instead which is a bit less horrible [1]. Part of this problem is checked vs unchecked exceptions, and some of the older APIs in Java use checked exceptions too heavily, IMHO. On top of that, I think all the Java IO stuff provides a pretty leaky abstraction over the system calls. 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/HttpURLConnection http://www.tbray.org/ongoing/When/201x/2012/01/17/HttpURLCon... [1] http://developer.android.com/reference/org/apache/http/client/HttpClient.html http://developer.android.com/reference/org/apache/http/clien...
- StavrosK 13y agoI started using HttpClient, but I saw a blog post that said that HttpURLConnection should be used by all new apps, so I went with that. I can't tell you about checked vs unchecked exceptions, as I just found out about them a minute ago. In the end, I used this excellent library: http://loopj.com/android-async-http/ 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!
- ryandvm 13y agoThe Android team has dropped support for Apache HttpClient. The party line is that if you are targeting Gingerbread or newer (and you should be), then use HttpURLConnection. http://android-developers.blogspot.com/2011/09/androids-http-clients.html http://android-developers.blogspot.com/2011/09/androids-http...
- meddlepal 13y agoDid you pull in a library to do the HTTP work or just use the raw HttpURLConnection? 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.
- StavrosK 13y agoI used this in the end: http://loopj.com/android-async-http/ http://loopj.com/android-async-http/, it exposes an interface that does not make me shudder, and I am guessing that is a very good thing. 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...
- Roboprog 13y agoA checked exception is one that the compiler forces you to write a check for. An unchecked exception ("the good kind") is one that you could write a check for if you want to. 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.
- StavrosK 13y agoI see, thanks. I have to say I'm not a big fan of checked exceptions, but it is what it is... Thanks for the information!
- yareally 13y agoIf Java turns you off, you could try Scala on Android. https://news.ycombinator.com/item?id=5873229 https://news.ycombinator.com/item?id=5873229
- StavrosK 13y agoI heard that that had very large startup costs due to the Scala VM (IIRC), which is unfortunate for what I'm making (a remote control app) :/
- yareally 13y agoI've used Java for a few years on Android differences for Scala past proguard are minimal for building and performance is the same as it's just compiled Java bytecode and then to dalvik
- StavrosK 13y agoOh, sorry, I just recalled that it was Clojure that I had heard about, so strike my above comment. I'm afraid I'm not familiar with Android or Java anywhere near enough to use Scala, as the learning curve would be much higher then. I will definitely consider it when I know a bit more about it, though, as it seems a much saner language.
- talloaktrees 13y agoAFAIK everything on Android runs on the Dalvik VM.
- yareally 13y agoYep, even Clojure does, but have never tried it really for Android, but it's just as possible as Scala. Jython has been possible in the past, but I haven't seen any recent projects updated to use it in the past 1-2 years.
- AYBABTME 13y agoJava is verbose. Tooling is great, however. 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.
- StavrosK 13y agoThanks for clarifying checked vs unchecked. Your comment makes perfect sense, and is what I expected. The thing is that I really don't like handling an exception higher than where it makes semantic sense (which is the actual call, in this case), so propagating higher is even less clean, for this specific example. I guess the problem here is the checked exception, but I can see the rationale, if it's impossible to optionally handle an unchecked exception.
- AYBABTME 13y agoWhat you could do is initialize the Url in a static block or in a `{{ }}` block and handle the exception there. You would still have the exception handling, but not in your logic, and the static block would ensure that if the Url is indeed malformed, the exception will throw as soon as the class is loaded in memory, instead of only when the Url is instantiated during in logic. 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.
- yummyfajitas 13y agoboilerplate...I'm wondering how people deal with this issue http://www.scala-lang.org/ http://www.scala-lang.org/
- victorf 13y agoChecked exceptions seem like a great idea, but I can see how the execution of them is irritating. If I were to do Android I would go directly to Scala, which looks pretty awesome.
- RivieraKid 13y agoWhat you described is mostly a problem of the standard library. Sometimes it's too low-level and it's better to use 3rd pary libraries for things like HTTP. There should definitely a way to create urls without having to check exception (ie. it would throw a RuntimeException that doesn't need to be checked). 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...
- StavrosK 13y agoHmm, yeah, I see what you mean. I think Go does a pretty good job of being a middle ground between Java and Python, it has the static typing with all the tooling advantages it brings, without the annoying need to be explicit about everything. I think you'll like it.
- RivieraKid 13y agoI quite like Go but I see it mostly as a C++ replacement, not Java or Python replacement. Java has far better tooling. It also has quite weak type system (no gnerics). Dart is closest to my ideal of a general purpose language.
- Roboprog 13y agoGo tooling will likely get better as time allows IDEs / plugins to be written. It remains to be seen if the Go language will grow significantly from one major release to the next, and how frequent any such changes will be. (it might stagnate, as well) Sun / Oracle have demonstrated the last 10 years that they do not intend to improve the Java language itself (COBOL with separate compilation, user defined types, field accessors and subclassing is good enough for all!), but will only keep rolling out new "Enterprise" libraries / frameworks.
- 13y ago
- RyanZAG 13y agoThe standard method for getting around this in the java world is to create 'sane' libraries (in the case of android http, something like http://loopj.com/android-async-http/ http://loopj.com/android-async-http/ ) and then just use the library. The strong point of Java is just how many libraries there are - you often don't need to touch the actual built in Java APIs. On the server side (non-android) this has gone even further through the use of new annotation based libraries that generally autodiscover classes in your code, removing a lot of boilerplate. 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.
- StavrosK 13y agoYep, that's what I ended up using, and it works very well. I especially like the interface (well, by Java standards).
- Yhippa 13y agoI feel something as commonplace as making a HTTP GET or POST should be standardized at this point. There are many implementations which still require a decent amount of boilerplate.
- RyanZAG 13y agoThe core java library has mostly been kept unchanged for a decade now (I think?). Java 8 is doing the largest change to it in a long time by changing the collections to work with lambdas. 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.
- sivanmz 13y agoJava is just not made for quick prototyping. In production, the URL will come from somewhere, not written by hand, so it would need to be checked anyway. Sadly there's no quick-prototyping mode in Java where you can say, just call this URL string an don't bother checking. 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 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.
- Gonzih 13y agoWelcome to javaland, where simple things take lot of time and lot of working time is spend doing java and not a real work. </sarc>
- gizmo686 13y ago>I'm wondering how people deal with this issue 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.
- rickmode 13y agoJava is old enough that the current best practices recommend using the language and libraries differently than originally intended. 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.
- Sandman 13y agoI'm really, really sorry that most of today's developers (it seems) consider checked exceptions to be a bad practice. Sometimes I feel like I'm the only person in the world still advocating their usage. I'm currently working on an application that uses libraries developed by people who had the same opinion about checked exceptions as you. Of course, their code still throws exceptions. Except now, I don't know whether a method I call can throw an exception and whether I should write code to handle it until it all blows up at runtime (more often than not - in production). So what do I do then? I write a try-catch to handle their exception. The exact same thing I would have done had they decided to throw a checked exception. Only now, I don't get any warning that I should handle possible exceptional behavior at compile time, I get it at some point during runtime.
- Teckla 13y agoI'm really, really sorry that most of today's developers (it seems) consider checked exceptions to be a bad practice. Sometimes I feel like I'm the only person in the world still advocating their usage. You're not alone. I find checked exceptions to be an invaluable language feature.
- doktrin 13y ago> 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?) 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. http://tmblr.co/ZJpjTubrVmRw http://tmblr.co/ZJpjTubrVmRw
- tomjen3 13y agoAndroidHttpClient has a executor method, which take your HttpGet object and a transformator and the default one will give you a string, which is the body of the request. 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).