Write readable code in java

Athula
3 min readDec 13, 2023

--

In this article we are going to discuss how we can write a program by making it readable and extendable.

Suppose you have given a requirement as below which is related to banking applications.

“In our system we will be getting user payment details from external system. Users can use different payment networks like VISA, MASTERCARD, MESTRO, CIRRUS, PLUS. Out of those, our system will add additional 2% interest for VISA and CIRRUS networks. In the future more payment networks will be eligible for this ….”

Let start writing a pseudocode for above requirement,

FOR Each PaymentDetail
IF networkType is VISA or CIRRUS THEN
Add 2% interest
END IF
END FOR

Our implementation will look like this,

Figure 1: First implementation

As shown in Figure 1 we have implemented the requirement. As in line 14 we check network type matches to VISA or CIRRUS. If so we add 2% interest to the amount and set as interest value again. This code block is working fine and we implemented the requirement.

If you read the original requirement carefully you may notice that in the future they are planning to add 2% interest on more network types. In such a case what we normally do is add one more OR condition to the if condition.

Figure 2: Adding more Network types

As shown in Figure 2 when time goes your simple method get more complicated and bit hard to read.

But, can’t improve our code to cater future requirements since requirement is saying there is chance of adding more network types. So we will move the section out which can modify in the future. New pseudocode will look like this,

FOR Each PaymentDetail
IF given networkType contains supported NetworkTypes THEN
Add 2% interest
END IF
END FOR

Our new implementation will look like this,

Figure 3: Improved by extracting

As in Figure 3 now you can notice that if we want to add more types we only need to change getSupportedNetworkTypes(). Advantage is core method remain un change. Also we can get idea about core method in abstract way.

If the network type is supported we calculate the interest rates.

And if we need to know what are the supported network types we can further go and check getSupportedNetworkTypes().

We can even think one step further. How about changing our pseudocode like this,

FOR Each PaymentDetail
IF networkType is supported THEN
Add 2% interest
END IF
END FOR

Our new implementation will look like this,

Figure 4: Final code

As in Figure 4 now we have move network type supported check also to different method. So our core method get much simpler and readable. Now you have luxury to extend your code based on future needs without affecting core implementation.

This is just a vary basic example. If you used to think in this manner when implementing code you can save lot of time in development and testing. Which will end up with quality product.

Cheers.. Happy coding.. 😊

--

--