Java Hacks— Part 1

Aftab Shaikh
3 min readJul 16, 2024

--

A wise man once said “Your code should be so simple that even a fool can understand it”

Java is not the language that I love, mostly because you have to write a lot of code to do simple things :( But after spending a year or so coding in it I got to know some very useful tricks that can make developer’s life easier. So let’s see what are these tricks:

Constant First for equals

When you are checking equality on two objects and one of them is Constant value. Then it’s better to call equals method on the Constant Value. This will avoid NullPointerException.

e.g:

private Boolean isFemale(User user) {
return FEMALE.equals(user.getGender());
}

If you had gone with user.getGender().equals(FEMALE) then this could throw a NPE if user.getGender()returns null.

Similar approach should be used with Boolean types. Consider following block of code where isActive is of type Boolean.

if (user.isActive()) {
// body
}

The above might give NPE if isActive returns a null. Because, isActive returns a Boxed type Boolean. Java will try to convert it to primitive type boolean by calling .booleanValue method of Boolean class. So, the better way to do this will be.

if (Boolean.TRUE.equals(user.isActive())) {
// body
}

Early Exit — Avoid nested ifs

If your code has multiple levels of nested control structures (if/else, loops etc.) then that’s a code smell. It’s very hard to read and understand the code which has more than one or two levels of nesting. And there’s always a way to reduce the nesting.

Consider below code to transfer the money from one account to another:

TransactionResponse transferMoney(User debitor, User creditor, Long amount) {
if (isValidAmount(amount)) {
Long availableAmount = userService.getAvailableAmount(debitor);

if (availableAmount >= amount) {
return transactionService.transferMoney(debitor, creditor, amount);
} else {
throw new InsufficientFundsException("Insufficient funds");
}
} else {
throw new AmountInvalidException("Amount invalid");
}
}

This has two levels of nesting but this will easily grow as more validations are added. The same thing can be achieved without any nesting:

TransactionResponse transferMoney(User debitor, User creditor, Long amount) {
if (!isValidAmount(amount)) {
throw new AmountInvalidException("Amount invalid");
}

Long availableAmount = userService.getAvailableAmount(debitor);
if (availableAmount < amount) {
throw new InsufficientFundsException("Insufficient funds");
}

return transactionService.transferMoney(debitor, creditor, amount);
}

All we had to do was invert the conditions and throw exceptions early. This technique is know as Early Exit. It’s very useful in reducing the nesting.

String.format

Use String.format method for your String Concatenation operations. It’s more readable and manageable.

// Instead of this
String name1 = user.getFirstName() + " " + user.getMiddleName() + " " user.getLastName();

// Use below version
String name2 = String.fromat("%s %s %s", user.getFirstName(), user.getMiddleName(), user.getLastName());

Factory methods for creating Collections

Use factory methods like List.of(), Set.of() and Map.of() to create objects of respective collections. The code becomes more concise and readable.

// Instead of this
List<Integer> numbers1 = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);

// Use below technique
List<Integer> numbers2 = List.of(1, 2, 3);

Use Arrays.asList() instead of List.of() where the elements that you pass could be null. Because List.of, Set.of and Map.of throws NPE if any of the element is null.

String.join

Use String.join method for you String concatenation operations. This can be a very useful method in various scenarios. Consider a simple example of generating name from firstName, middleName and lastName where middleName and lastName can be null or empty. I have seen a lot of developers write something like below

static String generateName(String firstName, String middleName, String lastName) {
String name = firstName;

if (!(middleName == null || middleName.isEmpty())) {
name += " " + middleName;
}

if (!(lastName == null || lastName.isEmpty())) {
name += " " + lastName;
}

return name;
}

So much code for such a small thing. Instead, you can use below technique with String.join.

static String generateName(String firstName, String middleName, String lastName) {
return String.join(" ",
Stream.of(firstName, middleName, lastName)
.filter(n -> !(n == null || n.isEmpty())).toList());
}

There are other variants as well of String.join. Explore them!

Final Thoughts:

The above practices are very easier to adopt and will make a very big impact in increasing the readability of your project code. Try them out. I am planning to write more about such simple techniques in Java, so stay tuned!

--

--

Aftab Shaikh
Aftab Shaikh

Written by Aftab Shaikh

Application Developer @Thoughtworks

No responses yet