Backend Development 22 min read

Comprehensive Java Best Practices and Essential Libraries Guide

This article presents a detailed guide to modern Java development, covering coding style, immutable data structures, builder patterns, dependency injection, null handling, formatting, Javadoc, streams, publishing strategies, Maven configuration, CI tools, repository management, configuration automation, essential development tools, and a curated list of widely used Java libraries.

Qunar Tech Salon
Qunar Tech Salon
Qunar Tech Salon
Comprehensive Java Best Practices and Essential Libraries Guide

Java remains one of the most popular programming languages worldwide, yet many developers overlook its strengths. With the recent release of Java 8, this guide compiles a practical checklist of best practices, tools, and libraries to help you write clean, efficient, and maintainable Java code.

Style : Move away from verbose enterprise‑style JavaBeans toward concise, immutable data holders. Prefer final fields and constructor injection to reduce boilerplate and improve readability.

Structure : public class DataHolder { private final String data; public DataHolder(String data) { this.data = data; } } This reduces line count by half and guarantees immutability unless explicitly extended.

Builder Pattern : For complex objects, use a static inner Builder that collects mutable state and produces an immutable instance. public class ComplicatedDataHolder { public final String data; public final int num; public static class Builder { private String data; private int num; public Builder data(String data) { this.data = data; return this; } public Builder num(int num) { this.num = num; return this; } public ComplicatedDataHolder build() { return new ComplicatedDataHolder(data, num); } } } ComplicatedDataHolder cdh = new ComplicatedDataHolder.Builder() .data("set this") .num(523) .build();

Dependency Injection : Use frameworks such as Dagger or Guice instead of XML‑based Spring configuration to keep injection logic in code and reduce boilerplate.

Avoid Nulls : Return empty collections instead of null, annotate nullable values with @Nullable , and leverage Java 8's Optional for potentially absent data. public class FooWidget { private final String data; private final Optional<Bar> bar; public FooWidget(String data) { this(data, Optional.empty()); } public FooWidget(String data, Optional<Bar> bar) { this.data = data; this.bar = bar; } public Optional<Bar> getBar() { return bar; } }

Immutability by Default : Declare variables and collections as final and use Guava's immutable collections (e.g., ImmutableMap , ImmutableList ) to prevent accidental modification.

Avoid Over‑populated Utility Classes : Prefer default methods on interfaces or small, focused utility classes rather than monolithic “misc” classes. public interface Thrower { default void throwIfCondition(boolean condition, String msg) { /* ... */ } default void throwAorB(Throwable a, Throwable b, boolean throwA) { /* ... */ } }

Formatting : Follow a consistent style guide such as Google Java Style; proper formatting improves readability and reduces errors.

Javadoc : Document public APIs with clear examples and avoid redundant comments that add noise.

Streams : Use Java 8 streams and lambdas for concise data processing. List<String> filtered = list.stream() .filter(s -> s.startsWith("s")) .map(String::toUpperCase) .collect(Collectors.toList());

Publishing : Choose a deployment framework (Dropwizard, Spring Boot, Play) that matches your project's complexity; simple JAR deployments are often preferable to heavyweight WAR/EAR bundles.

Maven & Dependency Management : Use a root pom.xml to centralise dependencies, apply the dependency‑convergence plugin to detect version conflicts, and manage artifacts via a repository (Artifactory or Nexus).

Continuous Integration : Automate builds with Jenkins or Travis‑CI, generate SNAPSHOT versions, and enforce code‑coverage checks (e.g., Cobertura).

Configuration Management : Automate environment provisioning with tools like Chef, Puppet, Ansible, or the custom Squadron solution.

Tools : IntelliJ IDEA – the most feature‑rich Java IDE. Chronon – time‑travel debugging for IntelliJ. JRebel – hot‑swap changes without rebuilding. Checker Framework – advanced type‑checking with annotations. Eclipse Memory Analyzer – diagnose heap dumps (e.g., via jmap ).

Libraries (selected highlights): Apache Commons (Codec, Lang, IO) – utility functions for encoding, strings, and I/O. Guava – immutable collections, caching, Joiner, and functional helpers. Gson – simple JSON serialization/deserialization. Gson gson = new Gson(); String json = gson.toJson(fooWidget); FooWidget copy = gson.fromJson(json, FooWidget.class); Java Tuples – lightweight tuple types for returning multiple values. Pair<String, Integer> func(String input) { return Pair.with(result, count); } Joda‑Time – robust date‑time handling (pre‑Java 8). Lombok – reduce boilerplate with annotations like @Getter , @Setter . public class Foo { @Getter @Setter private int var; } Play framework – lightweight MVC for REST services (alternative to Jersey or Spark). SLF4J – façade for various logging implementations. jOOQ – type‑safe SQL construction. Result<Record3<String, String, String>> r = create.select(BOOK.TITLE, AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME) .from(BOOK) .join(AUTHOR) .on(BOOK.AUTHOR_ID.eq(AUTHOR.ID)) .where(BOOK.PUBLISHED_IN.eq(1948)) .fetch(); Testing: JUnit 4, jMock, AssertJ – modern testing frameworks and fluent assertions. assertThat(some.testMethod()).hasSize(4) .contains("some result", "some other result") .doesNotContain("shouldn't be here");

These resources, together with recommended books (Effective Java, Java Concurrency in Practice) and podcasts (The Java Posse), provide a solid foundation for mastering Java development.

testingBest Practicesdependency injectionLibrariesimmutabilityBuilder Pattern
Qunar Tech Salon
Written by

Qunar Tech Salon

Qunar Tech Salon is a learning and exchange platform for Qunar engineers and industry peers. We share cutting-edge technology trends and topics, providing a free platform for mid-to-senior technical professionals to exchange and learn.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.