27 ms·
An Opinionated Guide to Modern Java Development, Part 1
- netcraft 13y agoWhat about dependency injection in modern java - is Guice or spring still the de facto standard?
- exabrial 13y agoI agree... can't live without Dependency Injection (one of the reasons I refuse to move off of Java). I've been using CDI and TomEE for small simple stuff (it just works). Can't stand Spring Framework anymore. It set out to replace the bloatware of Java EE 1.5 but it ended up becoming what it was meant to replace.
- jmgtan 13y agoYou should give the latest version a try. Spring implemented JavaConfig, which allows you to avoid XML altogether. Coupled with the ComponentScan annotation, it can't get any simpler.
- bsaul 13y agoGenuinely curious : i've been playing with dependency injection, and really never got to understand the true use of it. I mean, what's the point of being able to replace an implementation outside the source code itself ? You'd still have to extensively test the thing and recompile it... Is there more to it than just being able to replace a class by its mock up, for unit testing ?
- volune 13y agoIMO dependency injection encourages making very deep object graphs. constructor argument passing can be cumbersome, but jumping into new code it is much more clear, and it encourages you to write flatter code structures. i go without.
- snikeris 13y agoI think the point is that you don't want to be instantiating (and thus configuring) a dependency at the site where it is used. The code in class Foo should be limited to implementing Foo, not instantiating and configuring its dependency Bar.
- wtetzner 13y agoSo why not just pass its dependency as a constructor argument?
- snikeris 13y agoPassing a dependency as a constructor argument is dependency injection: http://en.wikipedia.org/wiki/Dependency_injection#Constructor_injection http://en.wikipedia.org/wiki/Dependency_injection#Constructo...
- wtetzner 13y agoRight, my point was more "why do you need a framework to call constructors for you?".
- UK-AL 13y agoThat's what IoC containers do, or via setter. However a IoC container can automatically create, and send through the object based convention(IMessageQueue -> MappedTo -> MessageQueue) or configuration (IMessageQueue -> MappedTo -> APMQMessageQueue).
- oh_sigh 13y agoNot to sound snarky, but you should read any introduction to dependency injection. The benefits are generally covered very thoroughly, and what you said is not usually considered a benefit.
- kyberias 13y agoWikipedia article on dependency injection, section titled "Advantages", _first_ bullet: "The result is more independent clients that are easier to unit test in isolation using stubs or mock objects that simulate other objects not under test." Would you like to try again?
- oh_sigh 13y agoThe OP said "I mean, what's the point of being able to replace an implementation outside the source code itself." Where, in what you posted, does it reference being able to replace implementations outside of the source code itself? Would you like to try again?
- deleted 13y ago[deleted]
- rymndhng 13y agoIt depends. One thing that I thought is an interesting feature of Spring, is that it allows the framework to inject code between your dependencies like decorators. This allows them to do aspect-oriented-programming transparently. And I think there's some interesting ideas here. For example, you can mark the interface of a class as @Transactional, and all your implementations will get the behavior.
- UK-AL 13y agoI think that's the interception way of AOP? Unity IoC in c# also does this. The IoC container will return transparent proxy(Not the original object), which then calls the underlying method(after doing the AOP behaviour).
- Glide 13y agoBe careful of using these though. I had an obscure bug using dynamic proxy (castle dynamic proxy2) a while ago in a WPF application. I was proxying to an interface so it created a proxy object in between that in the actual class so it was eating my C# event. Changing the proxying from an interface to a subclass fixed it. Boy that was a fun one to figure out.
- twistedpair 13y agoWhen you've got a complex graph of objects and dependencies between them, DI can easily take care of instantiating an A and feeding it to a B that requires an A and so on and so on. In our projects we'll have a DebuggerFooImpl, a MockFooImpl, and a ProdFooImpl. Spring's AppConfig classes then can create the proper object at startup based on environment profiles and no consumers have to do any more than ask for the Foo object to be injected into them, isolating them from any environment awareness/coupling. There are other benefits from DI as well, but the above at the low hanging fruit, isolating the complexity of object creation from the object's consuming classes.
- Terr_ 13y agoIt tries to disentangle two different problems: 1. Does my class work appropriately? Does it encapsulate/hide/abstract the right behavior? Does it function correctly with other classes that implement certain inferfaces? 2. Is my network of classes correctly defined so that I can use them all together in a particular way? http://programmers.stackexchange.com/questions/92393/what-does-the-spring-framework-do-should-i-use-it-why-or-why-not/92672#92672 http://programmers.stackexchange.com/questions/92393/what-do...
- ddeck 13y agoThere are definitely more advantages than just the unit testing side. The Google IO talk on Guice does a pretty good job of explaining the benefits: https://www.youtube.com/watch?v=hBVJbzAagfs https://www.youtube.com/watch?v=hBVJbzAagfs
- AnimalMuppet 13y agoIt occurs to me that dependency injection has this strange similarity to functional programming. I mean, clearly, you're playing with objects instead of functions, and they can have state, and so on, so it's not functional. But still, there's a similarity in how you're breaking things apart. Spring: Maybe the problem is that Jave EE 1.5 was a reasonably good solution for the problems it was trying to solve? Maybe you can't do radically better and still actually solve the problems?
- UK-AL 13y agoWhat web framework can use that works with CDI, and standard EE stuff that is request-repoonse based?
- veeti 13y agoI only do Java on Android, but Dagger (https://square.github.io/dagger/ https://square.github.io/dagger/) might be a nice lightweight alternative.
- ddeck 13y agoDagger is definitely more appropriate for Android applications and was developed specifically to address the issues with using something like Guice on mobile. That said, I love Guice and use it exclusively as it has a superset of features and startup performance is irrelevant in my area. As Christian Gruber from the development team put it: Dagger is a joint effort by Square, Google, some individual contributors from other places such as Nextflix, and is descended conceptually from Guice - specifically from MiniGuice. It addresses some key challenges our users faced with Guice. From Square’s side (/u/swankjesse can clarify this) it was the need to get high-performance, low-startup dependency injection on Android. From our side, it was that and the desire to trim the API weight of dependency injection, to reduce the user confusion that comes from reflection and bytecode generation in stack traces and debugging environments, and to get early validation of your graph’s wiring. Dagger is a substantial direction shift for Google, and we are investing time and resources in it. Guice will always have a superset of features compared to Dagger, though we do have projects using Dagger on the server and in stand-alone java apps. But Dagger is not as evolved in terms of the surrounding "scaffolding" code (servlet support, etc.) as Guice, and won’t be for quite some time. Additionally, some teams will need or want some advanced Guice features that will never make it in to Dagger. [1] [1] http://www.reddit.com/r/java/comments/1y9e6t/ama_were_the_google_team_behind_guava_dagger http://www.reddit.com/r/java/comments/1y9e6t/ama_were_the_go...
- pron 13y agoI'll address that in part 3. Basically jsr330 is a good standard, and it's implemented by Guice, Dagger and Spring
- peterarmstrong 13y agoIf you're planning at least 3 parts, have you considered turning this tutorial into a Leanpub book? It's the perfect start to one... (Disclosure: I'm a Leanpub cofounder)
- pron 13y agoI don't know. I'll give it a try.
- peterarmstrong 13y agoCool. Let me know how it goes!
- jebblue 13y agoI try to avoid it as much as possible. It's confusing at least to me and makes maintaining code over a long haul an arduous dull process. I'm getting to the point where I prefer straight JDBC over Hibernate too. It takes longer to code but I've seen speed increases of several times over Hibernate in those situations. JDBC code is just linear but I feel it's easier to maintain in the long run.
- edwinnathaniel 13y agoSpeed is not the only concern when it comes to JDBC vs ORM (JPA/Hibernate). The more complex the data model, the more one needs to know the inner working of JPA. I've shared my struggle understanding how JPA works even for a medium-level complexity of the JPA entities. Some of the problems I've encountered using JPA: - The whole EntityManager act as L1 cache occasionally tripped me when writing Integration-Tests - The relationship direction (owning, etc) can be confusing to learn - Reference vs Lazy vs Eager load Having said that, HBM2DDL is a nice tool that can work as maven plugin such that changes on the JPA entities can resulted the DDL to be updated properly thus maintaining consistency between Java Data Model and the DB schema.
- JustSomeNobody 13y agoThankfully I am seeing more and more comments like this. I really think we off the deep end with all this. Simple is key.
- EdwardDiego 13y agoI agree. Hibernate has become a downright liability at times in our codebase. These days I only use it in new code for query parameterization and result row transforms into models. Speaking of which, if anyone knows of a good library for query parameterization alone, let me know...
- ZitchDog 13y agoJDBI is quite good: http://jdbi.org/ http://jdbi.org/
- craigching 13y agoMy preference for DI is Declarative Services in OSGi. OSGi is a nice specification for creating modular Java systems.
- osi 13y agoi've seen a resurgence of 'new'
- bsaul 13y agoI'm back to java after having an unsatisfying experience 2 years ago with Spring MVC, (this time i use the "play framework"), and it seems to confirm my intuition that the language itself is really just fine. The problem lies more in bloated frameworks and corporate culture where everything needs to be standardized, regulated, and the purpose of a mandatory non-free training session. Add to that the fact that every single topic is covered by at least 3 or 4 libraries, and you get a more complete view of the situation.
- twistedpair 13y agoHow's Play! compare to Spring? I'm working on a bloated Spring whale (1.5M LoC, 485 Spring XML config files) and wondering if something like Play! can do it better, or if complexity is simply a beast that will inevitably turn any project into a turgid mass. I ask since friends at Google will laugh at a bar if you even say "Spring," but I'm curious what else can do it all (Guice/Gin?). Perhaps nothing can and the trick is to simply have small, cohesive projects linked by common REST (et al) API's and to merely skirt complexity entirely. However, for workflow and state management, you'll inevitably need some common integration point.
- pdevr 13y agoNot sure what version of Spring you are using, but the newer versions allow you to annotate your way out of the need to have so many XML files. Code bloat is a different beast. Unless the company decides to refactor and redesign the whole thing, you probably have to live with it, like the rest of us.
- ramkalari 13y agoPlay is simpler compared to Spring but idiomatic Play code also requires you to learn reactive programming, something you probably won't do in Spring MVC.
- neverminder 13y agoI while ago I had to choose a JVM based MVC framework to work with and originally I was looking at Spring. Needless to say it's a Mount Everest of frameworks, so by looking for alternatives I've stumbled upon Play. I decided to go the whole way and use Scala with it. Never looked back since. Typesafe stack offered me a rock solid Scala/Play/Akka/Slick stack with type safety, scalability, immutability, concurency that few others have (if any).
- monkmartinez 13y agoI have come full circle in a way. I started learning Java in school and built a few, small things for Android and the desktop. Then I was "all like;" I am going to learn the hotness which was(is?) Node. Node is what it is and I didn't really care for it. Then I moved on to Python and I really like it. Python is awesome for many, many things but GUI applications are not one of them. I have since returned to some Android development and I am diving into a CRUD web app in Java. Simple stuff, but it needs to be fast. Looking forward to part 2 and more!
- ryanobjc 13y agoA lot of people love to hate on Java, but it's a surprisingly dynamic language and there is a ton of great testing, networking, and many other libraries available. One of the things I appreciate about Java is the ability to take large teams and just have their stuff work together, without having unhuman discipline around super subtle rules (eg: C++) Also, IntelliJ is a must have!
- a8da6b0c91d 13y ago> super subtle rules (eg: C++) C++11/14 is in practice not that much more difficult to write well than Java. It's not 1998 anymore. The language is larger and more complex than Java, but it's also a lot more expressive and powerful, not to mention faster.
- TillE 13y agoYou still have to read Effective C++ to avoid shooting yourself in the foot, but after that C++ isn't much more difficult than Java or C#. The compile times remain annoying, though.
- UK-AL 13y agoIts having the knowledge of what subset of features do you stick too, because C++ is quite large feature rich language. There are often many ways of doings things.
- jeffbr13 13y agoOne of the reasons I love programming in Python so much is the focus on idiomatic code and 'one obvious way to do something' means that unfamiliar codebases or APIs are easier to read, and patterns for common tasks are seen again and again.
- pjmlp 13y ago> C++11/14 is in practice not that much more difficult to write well than Java. It's not 1998 anymore. While I agree with you and C++ belongs to my favorite languages, the truth is that most corporations still use C++98/C++03 and they aren't going to improve their compilers any time soon. On our Java projects we still get requests for Java 1.4. The enterprise is a very slow moving snail.
- kodablah 13y agoOne of my opinions these days on javadoc is that you should be minimalist. Have nothing to say about the return type? Don't add @return. Same for @param. Just a sentence about the method/field/class? Just a single line /* * ... */ is fine. Have nothing of value to say on a method/field/class (e.g. a getter), don't add javadoc at all. I'm growing weary of large files with tons of redundant javadoc lines to make some checkstyle/pmd rule happy.
- nollidge 13y agoYeah, I'm of the opinion that if you need a class/method comment to explain what it takes in or spits out, you probably named it badly.
- AnimalMuppet 13y agoYes... mostly. I worked with a guy who, for every comment, asked "how can I eliminate the need for this comment?" Usually the answer is to name something better. But sometimes you really need a comment, not because something is named badly, but because, even with the right name, there's something not obvious about it.
- nollidge 13y agoAgree completely, that's why I said "probably" :) EDIT: Comments are useful for explaining things like: 1. Non-obvious side effects 2. Code that's working around a bug in a 3rd party library 3. Code that calls into some non-intuitive 3rd party API 4. Citing your work (e.g. "adapted from stackoverflow.com/blah123") 5. Why you used pattern A instead of the more standard pattern B
- benjaminpv 13y agoSeconded. I always bristle when I see javadocs that include things like 'returns an object of [x] type that...' You're dealing with strong types, the signature provides all this information already. That, combined with good variable names, should do a lot of the documentation for you. If you wanna document a method, document what problem it solves. Document any gotchas (or better yet, redesign them out o_~). Don't just repeat what reading the method's signature already tells me.
- DennisP 13y agoThe position of things like Netty and Undertow at the top of the techempower benchmarks has me a little intrigued. How much hassle is it to write websites with servlets like that?
- pron 13y agoA bit of a hassle, but Comsat will make it dead-easy (right now Comsat runs on top of any servlet container, but it will also run directly on top of Netty/Undertow). Take a look at our Comsat web actors: http://blog.paralleluniverse.co/2014/01/28/web-actors-1/ http://blog.paralleluniverse.co/2014/01/28/web-actors-1/
- bhauer 13y agoUndertow provides a Servlet container, so if you are already using a Servlet-based framework, the level of effort is fairly minimal. Though, Resin remains a very high-performance Servlet container as well in our benchmarks and if you need a broad set of Servlet features, Resin may be a better fit. Another option is WildFly, which is the new JBoss application server that uses Undertow below the hood. We are presently adapting our in-house framework to use Undertow natively (without the Servlet layer) and the effort to do so has been low, all things considered. If you're comfortably working with the internals of your framework, you may be able to do the same without a great deal of pain.
- lmm 13y agoI've had a great experience building web APIs (i.e. returning JSON rather than HTML) in Scala with Spray; it requires you to think a bit more about when things happen (because everything is async), but it's lovely and smooth to use (there's this routing configuration DSL that looks almost like a config file, but then you realize it's all Scala so you can use things like for/yield with it). In terms of actual websites I understand Play is migrating to run on top of Spray, but I'm not aware of any mature frameworks for doing it right now.
- java-lang 13y agoIt is easy to write performant web applications without servlets using Vert.x which is also based on Netty. It also scored highly in the benchmarks.
- agibsonccc 13y agoIt's ironic, I'm slowly trying to move my development over to scala. I'll likely integrate gradle in to my stack (still use maven =/ mainly because I know all of its weird quirks) What have people's experiences with gradle been? I'm not a huge fan of groovy hence why I stayed away from it.
- bpodgursky 13y agoIMO Gradle has made huge improvements the past couple years (when I first started using it a few years ago it was incredibly unstable) but if you are a semi-power user of Maven I think you're going to find yourself frustrated using gradle still for a couple reasons (I've looked into this for my work recently, moving away from Ivy). Note I haven't extensively used Gradle, this is just from research: - Intellij has incredible Maven support, and by this point almost all the bugs have been worked out. Gradle support is improving, but our company has dozens of modules, a mix of Java / Clojure source code, and depends heavily on Intellij automatic source linking working correctly, dependency propagation working 100% successfully, etc, and it's really easy for small bugs to become blockers. Last I checked there were still a number of pretty frustrating bugs related to this - The Jenkins maven plugin is great, and the Gradle one is mediocre. For example, it does not even handle automatic triggering of downstream builds (this is absolutely critical for us https://issues.jenkins-ci.org/browse/JENKINS-19941 https://issues.jenkins-ci.org/browse/JENKINS-19941) - Gradle pretty decent plugin support by now, but is not yet as exhaustive as what you'll find with Maven (there's a maven plugin for basically everything now) - This may have been resolved, but I had issues configuring getting Gradle to update snapshot dependencies, which was really important to us. In the end I decided to migrate to Maven to avoid these headaches. I think I will try to use Gradle for personal projects, but I don't feel comfortable migrating our company stack there yet.
- agibsonccc 13y agoReally appreciate the insight, this is what I have found as well. Especially using intellij, it's still hard to beat. I'm always on the look out to use new stuff, but I'd rather wait a bit.. If I go hybrid JVM, I will likely just use SBT instead.. I think I'll keep an eye on gradle and see if it matures though. One of the reasons I still use maven is like what you mentioned: the tooling, I don't find myself using xml most of the time (despite knowing it like the back of my hand anyways)
- zwieback 13y agoI'm using Java for the first time because of Android. I had played with Java when it first came out but have stayed with C/C++/C# for almost everything. I have to say that my Java experience isn't as unpleasant as I thought it would be. I always thought C# is what Java should have been but after learning a little idiomatic Java the reality is quite okay, really.
- nmjohn 13y agoThe way you phrased that sounds to me like you've been programming for a significant amount of time. If that is the case, the Java of today offers so much that a younger Java did not, and I suspect you would have had a more unpleasant with the java of 10 years ago.
- kasey_junk 13y agoIn a lot of ways C# is still a much superior language than Java, but the JVM (I'm thinking HotSpot) is tremendously better than the CLR.
- pjmlp 13y agoI follow Grail and now Truffle development since the days of the Maxime VM. Looking forward to the day the reference JVM becomes a meta-circular one.
- peterashford 13y agoAnyone looking at where "enterprise" Java went - the whole J2EE monstrosity - would have run screaming. But the basic language is actually quite good and has been for a long time.
- cpprototypes 13y agoI like the changes in Java 8, but I'm concerned about Java fragmentation between Oracle/OpenJDK and Android. It seems Android is stuck on Java 1.6 (since Dalvik is not "true Java" and is more like a VM that happens to implement a language very similar to Java 1.6). There's now a huge gap between 1.6 and 1.8. It's not just syntax like lambda and default methods. It's also the supporting API changes in collections (streams) and others. Dalvik was based on Apache Harmony which is a dead project and will never get the Java 8 API changes implemented. Does anyone know if Google is going to do something about Java 8 and Android?
- eloisant 13y agoThere's always been some fragmentation between Dalvik and "real" Java. A lot of libraries don't work out of the box on Android.
- spullara 13y agoThere is a good reason that Sun didn't want this to happen and tried to stop it in court — successful against Microsoft, failed against Google. If I remember right, most everyone on here was rooting for Google to win and continue to fragment the language.
- _pmf_ 13y agoThe question is what Oracle would lose by licensing real Java to Google at reasonable conditions. Mobile non-Android Java is deader than dead.
- pnathan 13y agoI appreciate the modern Java style espoused here, it's much further away from the horrible overdesigned & pointless configuration style I often see with Java. However, the author doesn't really understand why C++ and dismisses it quickly. The short answer is C++ gives control and abstraction on demand, an unusual combination. Java trades control in exchange for GC.
- pjmlp 13y ago> The short answer is C++ gives control and abstraction on demand, an unusual combination. Ada, Modula-3, the Oberon language family as well. But they lacked a proper OS vendor support and faded away. Ada seems to be raising up, thanks to GNAT and continuous security issues with C and C++. At least from its increasing presence at FOSDEM.
- pnathan 13y agoWell, yes. And more than a few other languages that got left in the dustbin of our history. But as for today... I actually am personally very keen on seeing where Rust goes here, but it isn't 1.0 yet (which will be the signal for me to start writing in it seriously ).
- pjmlp 13y agoMe too, alongside D, .NET Native and the Graal/Truffle compilers.
- benjaminpv 13y agoIronically the Java ecosystem could stand to use some garbage collection of its own: there's a ton of old, outdated info out there that both colors people's impressions of the language and teaches new players a whole manner of bad habits. I appreciate what this article's going for and hope there'll be follow-ups. I use Java daily and though there's undoubtedly room for improvement (I'm looking forward to when tooling better supports stuff added in Java 8), I think a lot of the negativity that surrounds it is undeserved. There's definitely bloated XML-infested frameworks out there but the core's a real workhorse.
- Terr_ 13y ago> old, outdated info out there I'd love it if the JDK had a "learner mode" that disabled interned string literals. Then newbies experimenting with `assert(str1 == str2)` wouldn't leap to false conclusions.
- lmm 13y ago== should never have been used for that method, which is very rarely what you want. The right thing is probably to deprecate == on nonprimitive types, replacing it with a longer name that's clearer about what it means.
- pjmlp 13y agoSome pruning is planned for Java 9, at least is was announced so at Java One last year.
- lmm 13y agoThe #1 thing you need to make Java usable is to abandon the JavaBean conventions. When every field requires 8 lines of boilerplate it's no wonder the code looks ugly (YAGNI, and if you do need it it's two keystrokes in your IDE to "encapsulate field"). public final fields are fine, and can get your data classes something close to readable. I'd stick with maven for the build rather than Gradle; it's completely declarative and all the tools understand it. Learning a new language just to configure your build tool seems excessive.
- exabrial 13y agoCouldn't agree more. Use public, protected, private fields as they were meant to be used. I only dip into JavaBean anymore if I need a readable but non-writable field.
- karlmdavis 13y agoFor me that's almost all fields: I try to make just about everything immutable by default. Makes reasoning about concurrency much simpler.
- lmm 13y agoFor immutable you can just use public final fields. I assume GP must be talking about fields that are mutated but only by the object itself, where outside code needs to be able to read but not write.
- laureny 13y agoNot a single mention of Guice or even dependency injection? Seems like a gaping omission in a guide that claims to be about "modern" Java.
- venomsnake 13y agoDependency injection and any othee type of code indirection is evil imo. Anything that breaks the ability to find your way in a codebase with something other than grep brings more pain in the long run than it saves.
- Terr_ 13y ago> the ability to find your way in a codebase It's a tradeoff between two different kinds of clarity. Yes, it's harder to see the "whole wiring" without better tools... But it makes small, encapsulated classes much easier to reason about and develop! You can focus on assuring: "My `Foo` can interact with a supplied `Bar`" rather than dealing with all sorts of crap about what implementation of `Bar` it gets or how that `Bar` instance is configured.
- rat87 13y agogrep is a that good even for for c++ or dynamic mojo. Java is statically typed and has many ides and tools that understand code structure.
- rat87 13y agoisn't that good
- maaaats 13y agoJust grep for "extends InterfaceBeingUsed" and you'll find the implementation just fine.
- revscat 13y agoDependency injection has seen its day. The gains promised by DI/IoC containers tend to be outweighed by the complexity they introduce. I'm looking at you, Spring.
- tieTYT 13y ago> But the modern Java developer uses Gradle I'm a little skeptical of this. More like the developer in the future uses Gradle. Usually when I go to a project's home page, I see documentation on how to include the Maven dependency, not the Gradle dependency. It's pretty obvious how to convert one format to the other, but my point is I think most people are using Maven.
- pjmlp 13y agoGradle is mainly being pushed by Grails and Android development. I don't know of any other project using it. We are always doing Maven or Ant. If Gradle is the future I hope it gets improved, I gave up on Android Studio given its dependency on Gradle and how it drags my dual core with 8 GB to its knees when compiling.
- pron 13y agohttps://github.com/search?q=gradle&type=Code&ref=searchresults https://github.com/search?q=gradle&type=Code&ref=searchresul... I also know that Netflix use Gradle for pretty much all their Java stuff.
- revscat 13y agoSouthwest Airlines uses it.
- sadris 13y agoAnd Minecraft Forge.
- heavenlyhash 13y agoPersonal anecdote, I stopped trying to develop for MC Forge in version 1.7 because the gradle build they switched to was unbelievably slow and difficult to use. After several days of poking it, I still couldn't understand why asking gradle for a simple list of available tasks was taking >10 seconds, and when I tried to give my workspace to a friend on another computer, I discovered I had totally I failed to get a list of coherent commands that I was 100% sure could reproduce my workspace on a new machine, because of large amounts of scattered hidden state I had failed to detect. Part of this might be poor build config design, but gradle certainly helped enable a lot of poor behavior and certainly doesn't impress me with its performance for trivial tasks.
- leorocky 13y agoI love Java, especially Java 8. But as the article points out, what frustrates me is threading. You can't do much without quickly running into threading issues. I played audio files in a game I made and it created up to 2,000 threads and crashed. Once I wrapped audio in an explicitly created thread this issue magically went away. Any kind of UI, timers, file I/O and network activity also involves threads. The really horrible thing about these threads in Java is how hard it is to not share memory across them, because if you do terrible things happen. In other platforms you don't have to involve threads unless you want to, and you definitely aren't boxed into a situation where it becomes easy to accidentally share memory across theads. I like Go's way of handling this. node.js is single threaded but the event loop makes it possible to do non-blocking IO without crazy Jave thread issues. Using synchronized, atomic properties and locks is not the right way to do these things as your code gets really complicated when trying to do basic things. That gets me to my other pet peeve with Java. Just how much boiler plate there is to do basic things like opening up encrypted TLS TCP connections. Tons of cruft. Anyway, having said that, I love Java and use it, but these things need addressing. I like Scala's Akka, I hope Java comes around and improves the horrible thread situation. I will have to check out Quasar. I know I just need to become more familiar with threading in Java in general. I'm actually pretty new to Java.
- stcredzero 13y agoUsing synchronized, atomic properties and locks is not the right way to do these things as your code gets really complicated when trying to do basic things. One point being made in the op is that you don't have to. Of course, you may be constrained by how the libraries you want to use are structured, but I don't think this is necessarily the case. What if you used the op author's actor framework?
- dk8996 13y agoThere is nothing wrong with Java Threads, it gives you low-level access which can be complicated and cumbersome but, when mastered, can be powerful. I believe that Akka uses Java Threads underneath the covers.
- Terr_ 13y ago> basic things like opening up encrypted TLS TCP connections IIRC that's sort of a special-case: It's painful because the designers wanted to weave-in policies and integration with sys-admin stuff on the host OS. There's an impedance mismatch between how Enterprise IT wants to handle that versus what a lone-developer would like to create.
- tieTYT 13y agoThat pluggable type system looks amazing. One thing that's weird to me is how java included a new Optional type (seems similar to Haskell's Maybe), but the compiler (afaik) doesn't prevent you from setting an Optional field to null. Something about that doesn't feel right. (Side Note: Optional isn't serializeable. Also... what's the best practice for using Optional when I'm using JPA? Can it be used in my Entities?) I believe Jetbrains/Intellij-IDEA has created annotations for @NotNull/@Nullable, but afaik these just create warnings in the IDE. Maybe you can configure IDEA to mark these as compiler errors, but I don't know if my peers using netbeans/sublime/whatever would be able to notice when they write code that IDEA will refuse to compile. I want compilation to FAIL in these cases.
- steveklabnik 13y agoIt's certainly a bit strange, but it's how Scala works as well. I wonder if it's for backwards compatibility reasons, given that everything is nullable already. Have to give it more thought though.
- the_af 13y agoIndeed, Option in Scala has the same problem. I understand null is needed for backwards compatibility, but it makes Option the poor man's Maybe...
- virtualwhys 13y ago> Indeed, Option in Scala has the same problem eh? scala> val safe = Option(null) safe: Option[Null] = None
- adamwbarr 13y agoscala> val x = Some(null) x: Some[Null] = Some(null)
- virtualwhys 13y ago
- kyberias 13y agoWhy do people seem to think "opinionated" is a virtue these days?
- zenbowman 13y agoAn excellent question. Opinionated: conceitedly assertive and dogmatic in one's opinions. It generally refers to people who assert their opinion without making a sound argument for it. I consider it a huge negative. Another vice that many consider a virtue is when they consider themselves to be "real" - this is generally code for lacking any self-discipline and being unable to control emotion.
- lmm 13y agoBecause, particularly in Java-land, if you're not opinionated you end up providing a FactoryFactoryFactory. A beginner is in no position to weigh up the pros and cons of the different build tools available, so it's better for a guide to simply make a recommendation and explain that one than to give the beginner a confusing choice.
- Daishiman 13y agoTwo reasons that come to mind: - Java is such a massive ecosystem that you need someone to guide you through the complexity and to show you the diamonds among the piles of dung. - You're being honest. Really, my impression of Java has been so bad because of people that want "industry standard" and "enterprise" things that I welcome fresh perspectives from people in the field. Ultimately, if someone points out that a certain statement is they own opinion it's easier for you to judge it in a broader context, so even if you still disagree you don't feel like you're being misled.
- kazagistar 13y agoIts better to have one opinion then ten conflicting ones. Its also easier to learn how to do something from an opinionated source then one that tells you to do "whatever you want", without providing you with good ways of evaluating the choices and intelligent defaults.
- jebblue 13y agoGood article, lots of opinions but the title forewarns. For me, Eclipse is still very good and if anything, more stable than in earlier years. I've tried NetBeans and the free IntelliJ but though those are fine, Eclipse is better for me. The real trick is to _not_ store your code in the workspace (which is ironically where the project wizards default to unless you change it). Store your code in as an example, svn for Subversion, git for Git, etc. Use the workspace as just a shell to manage Eclipse preferences and such.
- bradleyjg 13y agoAs an eclipse user this suggestion intrigues me, but I'm not sure what the workflow would actually look like. Do you have a pointer to an article or something? Thanks.
- jebblue 13y agoSorry no link, co-workers and as "smrtinsert" said, Git or for me having both Git and Subversion projects makes life easier keeping source separate from the workspace.
- bradleyjg 13y agoDo you use the link source tab of the "Java Build Path" to point to the project directory in the source control directory?
- jebblue 13y agoNope, never used that. For Git it's straightforward, I have one Git repo per project I manage with Git. just use Import Project. The code remains where it is at. For SVN, I use Checkout and uncheck "Use default workspace location" and specify the location of the code.
- smrtinsert 13y agoI do this, or have started to since I've been using git more. I also do it with large projects. Only my truly disposable projects are in the workspace.
- Terr_ 13y agoSomething that really resonates with me from the linked PDF ("Blue-collar language") published in 1997: > What I found most interesting in watching people use Java was that they used it in a way similar to rapid prototyping languages. They just whacked something together. I was initially surprised by that, because Java is a very strongly typed system, and dynamic typing is often considered one of the real requirements of a rapid prototyping environment. [...] you find out fast when something goes wrong. Despite working in JS and Python, sometimes I feel more comfortable hacking something up in Java, because every missing method or undefined variable is an unavoidable short-term TODO.
- eranation 13y ago> But enough writing Go in Java. Let’s try Erlang. Nice
- cs02rm0 13y agoQuasar is an open-source library made by us Quite enjoyed the article until that got jammed in there.
- anthonye 13y agoModern Guide to Java... using our tools.
- wil421 13y ago>But the modern Java developer uses Gradle...there are quite a few things that are quite, though not very, common, but still require dropping down to imperative Groovy. This is the first time I have heard of Gradle, but why would I use a build tool that requires me to learn Groovy. If I already know Java I wont be learning something new just to build a Java project. I find a lot of development tools/frameworks make me learn B just to get started with A, its really frustrating for someone with limited experience IMHO.
- nsxwolf 13y agoI wouldn't say you need to actually learn Groovy to get going with Gradle. The example build.gradle files are fairly self-documenting, and you'll be modifying them more than writing them from scratch. Easier to read than a pom.xml, for sure.
- wil421 13y ago>Easier to read than a pom.xml, for sure. In that case I will have to check in out on a side project. My current projects at work are using Ant or Maven and I dont really like sorting through the pom.xml especially if someone else set it up.
- darylteo 13y agoWhat if I told you that Java code is perfectly compilable in Groovy and learning the required amount of Groovy isn't that much anyway? There's even a JavaDoc that you can reference at any time. And even now in Java 8, you have Lambdas... well guess what? Groovy uses Closures everywhere, and the syntax is similar too. So it really shouldn't be black magic.
- wil421 13y agoWhat if I told you I am not a very experienced java programmer and learning something new wouldn't really help me become a better java programmer. That and my employer uses Java and randomly chooses PHP sometimes for no apparent reason.
- spopejoy 13y ago> In this example, Java is rather annoying, especially when it comes to testing the type of a message with instanceof and casting objects from one type to another. Using instanceof is an antipattern 99% of the time, easily avoided with proper API design. In this case a simple enum type would help with appropriate getType() method on the event; or a polymorphic event API with dedicated method types for each event (LifecycleEvent marker interface with ExitEvent subtype containing onExitEvent(ExitMessage m), etc), or ... or ... Writing an intro to Java + touting your company's API + blaming Java for yourco's API problems: seems like bad form. Which reminds me: can someone explain how actors is any different than using messages and queues for concurrent programming? Unless it also implies "magic translation of messages to method calls" which makes me uncomfortable (bad memories of CORBA/Web services)
- EdwardDiego 13y ago> or a polymorphic event API with dedicated method types for each event Exactly!
- sivanmz 13y agoAgree that instanceof is wrong and discredits the article. I'm not sure if this is what you meant, but here is how polymorphism along with the double dispatch pattern would work: NaiveActor#handleLifecycleMessage will need to delegate to the event subclass, which will in turn select the appropriate method on NaiveActor. Example of subclass of LifecycleMessage: class ExitMessage implements LifecycleMessage { @Override void handle(BasicActor actor) { actor.handleExitMessage(this); } } In NaiveActor: @Override protected void handleLifecycleMessage(LifecycleMessage m) { m.handle(this); } @Override protected void handleExitMessage(ExitMessage m) { if (Objects.equals(m.getActor(), myBadActor) { System.out.println("My bad actor has just died of '" + m.getCause() + "'. Restarting."); spawnBadActor(); } return super.handleExitMessage(m); } It's been my experience that many developers resort to instanceof or enum type flags because they don't believe polymorphism actually works in real world situations such as this.
- elchief 13y agoWhat did the Eclipse team do so wrong to fall so fast? Also, what are Maven's fatal flaws? I don't consider XML a flaw.
- lightblade 13y ago> ...simplicity of Maven... Did I read that right?
- eranation 13y agoThe biggest take I have from this post is that apparently they have created go-like lightweight threads for the JVM with Quasar (http://docs.paralleluniverse.co/quasar/ http://docs.paralleluniverse.co/quasar/) which is really interesting. If I understand correctly, Quasar uses bytecode instrumentation to enable user-mode threads for the JVM, and they claim they did benchmarks that show X6 to X12 better performance than native JVM threads: http://blog.paralleluniverse.co/2014/02/06/fibers-threads-strands/#benchmarking-fibers http://blog.paralleluniverse.co/2014/02/06/fibers-threads-st... This is really something that caught my attention.
- pjmlp 13y agoThe initial JVMs already had Go like threads, aka green threads, with red threads being OS ones. The language specification does not require a specific implementation and with time all JVMs moved to red threads. There are a few JVMs around that still support green threads as threading model.
- pswenson 13y agoI'd like to hear thoughts on CheckedExceptions in part 2. IMO, they are a disaster - most projects degrade into all methods having a "throws Exception" clause. But I'm not sure if there is any consensus on how the CheckedException haters like myself work around them. I use Runtime exceptions everywhere, but it's a pain/boilerplate to convert them.
- mike_hearn 13y agoNot all checked exceptions are bad. The main problem is that the core Java libraries tend to use them too aggressively and now of course cannot be changed. You really have to be sure that the caller MUST handle a particular occurrence and anything else is a bug to make an exception checked. But, I do find it helps me feel more confident in my code. Everyone hates writing error handling code, but at least with checked exceptions you can see whether it's been done properly or not. But in Java 8 for the times when I want to disable it, I just use the following code: public interface UncheckedRun<T> { public T run() throws Throwable; } public interface UncheckedRunnable { public void run() throws Throwable; } public static <T> T unchecked(UncheckedRun<T> run) { try { return run.run(); } catch (Throwable throwable) { throw new RuntimeException(throwable); } } public static void uncheck(UncheckedRunnable run) { try { run.run(); } catch (Throwable throwable) { throw new RuntimeException(throwable); } } public static void ignoreAndLog(UncheckedRunnable runnable) { try { runnable.run(); } catch (Throwable t) { log.error("Ignoring error", t); } } Then you can write Foo result = unchecked(() -> getAndMaybeThrow(a, b));
- pron 13y agoWell, there's not much to discuss about checked exceptions. The general consensus in the Java community that it was a very good idea in theory, that hasn't worked out well in practice. New API designs usually don't introduce new checked exceptions. Those that are there - are there, and new ones aren't being added, so there is really not much to argue over.
- heavenlyhash 13y agoI quite like checked exceptions. They're actually one of the few things that keeps me writing java for more projects instead of switching more of my time to golang -- golang takes the far opposite approach, and with either returning error codes, or using golang's borderline untyped panic (yes, yes, you can panic typed errors... but it's an incredible PITA to try to construct an error type hierarchy and impossible do terse typed catch blocks with it) doesn't scale well for projects more than about 4ksloc in my experience. Exceptions signatures, like anything else, need aggressive refactoring to remain a useful part of an API. Always remove throw declarations that aren't needed. Always refactor the exception type hierarchy as your project evolves to keep it sensible. The worst of typed exceptions I've felt recently is the JGit API (don't get me wrong, JGit is an amazing piece of work; but its sharpest parts are the error handling). There's inchoate masses of IOExceptions from some pieces, JGitAPIExceptions in others, and none of them compose nicely so that when I do large amounts of work I can summarize the error handling up to a few types of conceptually similar problem. And several JGit commands throw checked exceptions for what are essentially fuck-ups in builder patterns, which have been compile-time issues every time I run into them, thus a source of huge irritation (these are prime examples of where you should use unchecked exceptions). On the other hand, the project I was using that same JGit API in has been one of the best examples of why typed exceptions can be a good idea. This project grew out of a python->java rewrite, and so in the original translation used completely unchecked exceptions as a holdover from the python form. (Why rewrite? It needed to go cross-platform and I needed a stable git api; libgit2 still couldn't clone at the time, so it was jgit or gtfo.) And as I kept working on the project and writing test cases... time and time again, converting things to typed exceptions and refactoring the exception hierarchy paid huge dividends in code quality, huge improvements in API consistency, and raised the quality of tests and final product alike because similar error cases ended up with similar exception types, and tended towards similar handling as I refactored similar exceptions types into one... #wining. tl;dr being irritated by methods that claim to throw too many exception types is good and healthy. The fix isn't to toss checked exceptions out the window: the fix is to take the pain, and use it to fuel a good API with a tightly controlled and easily understandable set of failure modes.
- hugofirth 13y agoAnother great Java resource (though admittedly the current edition is focused on Java 7) is "The Well-Grounded Java Developer" by Evans & Verburg [1]. [1]: http://www.manning.com/evans/ http://www.manning.com/evans/
- ninjazee124 13y agoI went from Java to Scala and am back to Java 8, and couldn't be happier with my choice. We are also using the latest Spring 4 framework which plays well with Java 8. A lot of the Spring + Java haters haven't really looked at all the improvements have happened to both Spring and Java recently, either that or they just like to bounce off what they read online without any actual experience. It's a solid stack for a backend, and I have built the whole platform on in without a hitch.
- loup-vaillant 13y ago> depending on the exact usage, a large Java program can be slightly slower, as fast, or a little faster than a comparable C++ codebase This is probably true but… Does anyone here have any data to back that up?
- longp0ke 13y ago> Java is a blue-collar language – the working person’s trusty tool – adopting only tried and true idioms, and adding features only if they solve major pain points. "adapting only tried and true idioms", what the actual fuck. am i reading...
- pit 13y agoDoes anyone here do Java development sans IDE -- like, say, with Emacs?
- darylteo 13y agoWhen I taught programming I made my students do all their programming in notepad++/sublime text.
- deleted 13y ago[deleted]
- nvarsj 13y agoI have to agree with the first comment on the blog. Gradle is strictly worse than Maven - it's basically Ant reinvented with Groovy. It leads itself to poorly maintained, complex build files, and the only good parts are the bits that use Maven under the hood (so just use maven ;-)). It's also slow. Also, if you seriously want to use an Actor framework in Java, you should use Akka - the lead devs really know their stuff, and are active in Java concurrency circles (JSR-166).
- jg03 13y agoYou always know to expect a dreary, look-my-language-is-modern-too article when "opinionated" features in the title. This one didn't disappoint.
- ivan_gammel 13y agoOddly, this resource is blocked in Russia, so I was not able to read the article from my ipad. WTF with this country. Anyone knows if I can penetrate Great Russian Firewall on ios?
- AmrMostafa 13y agoIf you have come to this post expecting to read something related to modern Java for the web, and have come back unsatisfied, then here is something to make up for that: yeoman's jhipster generator: http://jhipster.github.io/ http://jhipster.github.io/ Presentation: http://jhipster.github.io/presentation/ http://jhipster.github.io/presentation/
- 0800899g 13y agomodern java
- hyp0 13y ago+1 for markdown inline docs. A simple, obvious, useful idea I hadn't seen before.