Java : Best Practices Checklist
Hello coding community, I thought of writing about the best practices I follow while coding in Java 8 and I make sure I tick all the below checkboxes before I create a Pull Requests, day to day.
The best practices listed below are quite generic and varies from company to company, org to org, team to team and developer to developer.
I don’t go in detail about each of the best practice as It would make this article unnecessarily long.
Take it as a generic checklist and follow best practices whenever possible.
- Always format the code:
⌥⌘L (in IntelliJ)
- Write
{@link --}
type Javadoc for methods, classes and variables - Declare an
Inner/ Anonymous class
instead of concatenating multiplestrings/classes
(Builder-Pattern
) - Prefer
event-based-queues
instead ofsynchronizing
data-structures across multiple-threads - Use
lambda expressions
andstreams
instead of anonymous classes and for loops respectively. - Try employing
synchronized data-structures
instead of usingsynchronized
keyword - Use
meaningful and informative names
forclasses, methods and variables
- Prefer
smaller
andsingle-responsibility
methods - Prefer
Thread
overThreadPool
for single-task execution (ex:consumer thread
) - Always execute
callbacks
usingseparate callback-executors
- Create
marker-interface
to identify set ofsimilar-classes
to poke around - Add
default-methods
inInterfaces
, avoiding code duplication inClasses
- Override
equals()
andhashCode()
methods inDTOs
referring to theirPRIMARY-KEY
, to avoid duplicates - Make
DTOs / Java-beans Immutable
by providing ONLYgetters and private constructors
- Use
Enums
for related, constant set of variables - Use
generics
for moretypeSafe
code - Make use of
Try-with-resources
andMulti-Catch exceptions
features - Use
CompletableFuture
for Asynchronous stuff - Use
Optionals
instead ofnulls
- Always override
toString()
inDTOs/Java beans
- Avoid passing or returning
null
values, by returningempty-array
orlist
(ex:Collections.emptyList()
) - Use
PreparedStatements
inside theDTO/ Java beans
to avoid the spaghetti code in Implementation classes - Write separate
Util
classes (ex:StringUtil
,MathUtil
....) - Don’t duck the exception, Instead
Create an exception, throw an exception
and handle it - Make variables
effectively final
wherever possible, as java optimizesfinal
declarations internally - Prefer
switch
statements overif-else
as Java better optimizes switch statements - Use
MappedByteBuffer class
for best gains withfile operations
whose content is a memory-mapped region of a file. - Use of
Lombok
makes code look elegant, resulting in a lot cleaner code
Stay tuned and I will try to write in detail about each of the above best practice.
Happy Coding and Engineering.!!
Resources: