Practical Tips to Write Readable Code in Java

Few practical tips to make your Java code more readable

pratik Raghuwanshi
Javarevisited
3 min readMay 27, 2020

--

Hello programmers,

As per my thinking every person who knows any programming language is programmer, but there is a Bigger difference between writing a code and writing a readable code.

Readable code is something which easy to maintain, easy to read, easy to debug, simple to reuse, small in size, properly refactored, perfectly documented and there is proper commenting etc.

So lets start with some simple and interesting practices which make your messy code to readable code.

1. Try to Use of Streams instead of Loops

Best Advantage of Streams are readability, JAVA 8 comes with exciting surprises one of the best and useful surprise is Streams. Stream provides lots of method for user which help us to reduce no of lines of our code, we take a simple example.

Suppose I have a class Person with basic details like Name, Age, Contact number, Address etc. so I created a class named as Person with all this fields with their getter setter and one no arg constructor and the problem statement is I want Persons whose age is above 40, In traditional way we will do this in following way.

Here persons is list of type Person having data For Persons

It is 6 lines of code we can make it to just one-liner code with readability, yes it is possible with Streams.

Here stream’s filter method filter out person whose age is greater than 40 and collect them in a list

2. Try to Refactor your code as much as possible

Refactoring is a important technique to make your code more maintainable, It is really messy and tidy when you write your whole logic in one method. Thumb rule of refactoring is function should have one and only one purpose. when we split our big code in small small chunks of function it is easy to debug and to test and it is helps to avoid code duplication in our application.

3. Documentation and commenting

“Commenting is an Art of express purpose of your code”

Actually Documentation and commenting are two sides of one coin, the purpose of both are similar, just to describe your code, A new programmer in your firm or in your domain can be able to understand the purpose of your function just by reading documentation reading above it. documentation is nothing but a block-level comment written above your function or class to describe use of your function or class.

An inline comment is useful when there is some tricky logic written in your function.

At last, the conclusion is simple, your code readability depends on just some of the points which are the length of your code, code refactoring so it will become easy to maintain and debug, and last but not least commenting and documentation.

Thanks for reading!

--

--