Article

10 Subtle Best Practices when Coding Java

Topic: Coach Training and CertificationPublished January 30, 2018
No ratings yet586 viewsSign in to rate
This is a list of 10 best practices that are more subtle than your average Josh Bloch Effective Java rule. While Josh Bloch’s list is very easy to learn and concerns everyday situations, this list here contains less common situations involving API / SPI design that may have a big effect nontheless.rn1. Remember C++ destructorsrnRemember C++ destructors? No? Then you might be lucky as you never had to debug through any code leaving memory leaks due to allocated memory not having been freed after an object was removed. Thanks Sun/Oracle for implementing garbage collection!rnBut nonetheless, destructors have an interesting trait to them. It often makes sense to free memory in the inverse order of allocation. Keep this in mind in Java as well, when you’re operating with destructor-like semantics: • When using @Before and @After JUnit annotationsrn• When allocating, freeing JDBC resourcesrn• When calling super methodsrn2. Don’t trust your early SPI evolution judgementrnProviding an SPI to your consumers is an easy way to allow them to inject custom behaviour into your library / code. Beware, though, that your SPI evolution judgement may trick you into thinking that you’re (not) going to need that additional parameter. True, no functionality should be added early. But once you’ve published your SPI and once you’ve decided following semantic versioning, you’ll really regret having added a silly, one-argument method to your SPI when you realise that you might need another argument in some cases:rn3. Avoid returning anonymous, local, or inner classesrnSwing programmers probably have a couple of keyboard shortcuts to generate the code for their hundreds of anonymous classes. In many cases, creating them is nice as you can locally adhere to an interface, without going through the “hassle” of thinking about a full SPI subtype lifecycle.rnBut you should not use anonymous, local, or inner classes too often for a simple reason: They keep a reference to the outer instance. And they will drag that outer instance to wherevery they go, e.g. to some scope outside of your local class if you’re not careful. This can be a major source for memory leaks, as your whole object graph will suddenly entangle in subtle ways.rn4. Start writing SAMs now!rnJava 8 is knocking on the door. And with Java 8 come lambdas, whether you like them or not. Your API consumers may like them, though, and you better make sure that they can make use of them as often as possible. Hence, unless your API accepts simple “scalar” types such as int, long, String, Date, let your API accept SAMs as often as possible.rnWhat’s a SAM? A SAM is a Single Abstract Method [Type]. Also known as a functional interface, soon to be annotated with the @FunctionalInterface annotation. This goes well with rule number 2, where EventListener is in fact a SAM. The best SAMs are those with single arguments, as they will further simplify writing of a lambda. rn5. Avoid returning null from API methodsrnI’ve blogged about Java’s NULLs once or twice. I’ve also blogged about Java 8’s introduction of Optional. These are interesting topics both from an academic and from a practical point of view.rnWhile NULLs and NullPointerExceptions will probably stay a major pain in Java for a while, you can still design your API in a way that users will not run into any issues. Try to avoid returning null from API methods whenever possible. Your API consumers should be able to chain methods whenever applicable:rn6. Never return null arrays or lists from API methodsrnWhile there are some cases when returning nulls from methods is OK, there is absolutely no use case of returning null arrays or null collections! Let’s consider the hideous java.io.File.list() method.rnWas that null check really necessary? Most I/O operations produce IOExceptions, but this one returns null. Null cannot hold any error message indicating why the I/O error occurred. So this is wrong in three ways: • Null does not help in finding the errorrn• Null does not allow to distinguish I/O errors from the File instance not being a directoryrn• Everyone will keep forgetting about null, herern7. Avoid state, be functionalrnWhat’s nice about HTTP is the fact that it is stateless. All relevant state is transferred in each request and in each response. This is essential to the naming of REST: Representational State Transfer. This is awesome when done in Java as well. Think of it in terms of rule number 2 when methods receive stateful parameter objects. Things can be so much simpler if state is transferred in such objects, rather than manipulated from the outside.rn8. Short-circuit equals()rnThis is a low-hanging fruit. In large object graphs, you can gain significantly in terms of performance, if all your objects’ equals() methods dirt-cheaply compare for identity first:rn9. Try to make methods final by defaultrnSome will disagree on this, as making things final by default is quite the opposite of what Java developers are used to. But if you’re in full control of all source code, there’s absolutely nothing wrong with making methods final by default, because: • If you do need to override a method (do you really?), you can still remove the final keywordrn• You will never accidentally override any method anymorern10. Avoid the method(T…) signaturernThere’s nothing wrong with the occasional “accept-all” varargs method that accepts an Object... argument:rn1 void acceptAll(Object... all);rnWriting such a method brings a little JavaScript feeling to the Java ecosystem. Of course, you probably want to restrict the actual type to something more confined in a real-world situation, e.g. String.... And because you don’t want to confine too much, you might think it is a good idea to replace Object by a generic T:

Further reading

Further Reading

4 total

Article

How Coaching Turns Knowledge Into Change Walk into any bookstore or scroll through your favorite podcast feed, and you’ll see the same thing: endless tips, strategies, and “life hacks” promising transformation.rnWe devour them. We highlight paragraphs. We even try to practice what we’ve learned. But somehow, the big shifts never stick. Weeks later, the old patterns creep back in.rnSo why does it happen? Why do so many smart, motivated people keep getting stuck — eve

October 6, 2025

Article

grinding and cutting a variety of materials across numerous industries. Understanding their construction, types and safety precautions is mandatory for anyone working with these powerful tools. This article will explore the basics of abrasive wheels, offering insights into their components, maintenance and legal requirements to ensure both effective and safe usage. Exploring the Basics of Abrasive Wheels Abrasive wheels are critical tools in various industrial applications, f

March 6, 2025

Article

The internet we use daily, known as the surface web, represents only a fraction of the entire digital landscape. Beneath this visible layer lies the deep web and the dark web, where anonymity, privacy, and unrestricted information exchange thrive. Among the most well-known directories for accessing dark web content is the Uncensored Hidden Wiki . This article delves into the history, significance, risks, and access methods of the Uncensored Hidden Wiki, providing a comprehens

January 31, 2025

Article

If you're searching for exceptional piano classes near you, there are several excellent options in Toronto to consider. For those eager to learn the piano, finding a school or instructor that offers expert guidance, comprehensive lesson plans, and a supportive environment is key. Catering to both beginners and advanced players, many schools in the Toronto area provide tailored lessons to help students achieve their musical aspirations. What to Look for in Piano Lessons When

January 1, 2025