Coding Best Practices for Java Apps
Anshul Bansal
Posted on November 16, 2020
Introduction
Coding best practices are always helpful in ensuring the code quality, performance, and consistency.
In this article, I'll share a few coding best practices to follow while developing Java Applications that I use in my daily coding.
Before jumping to that, I'd recommend readers follow my other write-up that will set the stage for us:
Code Review Checklist for Java Beginners
Anshul Bansal ・ Jan 5 '20
Now, we're all set to take a look at a few best practices:
Follow the OOPs principles - Abstraction, Encapsulation, Inheritance, and Polymorphism
Use Design Patterns like Singleton, Decorator, Factory, and Builder-Factory for reusable, robust, and maintainable code
Leverage the Project Lombok library to reduce boiler-plate code
Use Java Stream APIs and Lambda expressions to process collections of objects
Leverage Lambda expressions to perform functional programming in Java
Leverage Generics for cleaner code and less duplicity
Use the Collections class for performing general operations on a collection
Use the LocalDate, LocalTime, and LocalDateTime classes to work with Date/Time.
Consider Optional in place of null
Prefer Atomic variables and Concurrent Collections over Synchronization
Proper Error/Exception handling
Leverage ExecutorService for Asynchronous operations
Move the business logic to Services for reusability
Keep controllers thin - only for handling request/response
It's a better idea to reduce Database interactions
If using ORM technology like Hibernate, use Lazy/Eager fetching techniques wisely
Use a database connection pool for the handling of DB connections
Leverage batch insert/update for bulk transactions
May use asynchronous programming for long fetched queries
Try not to block the main thread for long execution task - try asynchronous programming instead using the FutureTask and CompletableFuture classes
Enable logging using SLF4J
Unit test the code using testing frameworks like JUnit
Document API specifications using Swagger 2
Summary
In this short article, we've seen a few pointers for coding best practices as well as a few tips and tricks to follow while developing Java Applications.
Please let me know your thoughts and share the best practices you follow in the comments below.
Thanks for reading!
Posted on November 16, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.