Member-only story

Remove If -Else from your code

Gain Java Knowledge
3 min readDec 8, 2023

--

Sometimes, our code is full of if-else condition. so it is not easy to understand it y another colleagues.

So, as a beginner, or experienced, should make your code more sophisticated and readable.

The first thing we need to try is removing if-else from our code. Here are some advice.

Option 1: Early return

Suppose there is the following code:

public boolean isValid(String userName) {
boolean isValid;
if (userName != null){
if (userName.equals("Tom")) {
isValid = true;
} else {
isValid = false;
}
} else {
isValid= false;
}
return isValid;
}

This is the kind of code that we generally use to return early, removing the unnecessary else.

public boolean isValid(String userName) {
if (userName != null && userName.equals("Tom")) {
return true;
}
return false;
}

This approach is generally only suitable for simple structures and we can return early to get rid of some of the unnecessary if-else.

Option 2: Enumeration

Suppose there is the following code:

public String getLabel(int status) {
String label = "";
if (1 == status) {
label = "Padding";
} else if (2 == status) {
label = "Paid";
} else if (3 == status) {
label = "Success";
} else if (4 == status) {
label =…

--

--

Gain Java Knowledge
Gain Java Knowledge

Written by Gain Java Knowledge

The Java programming language is one of the most popular languages today. Stay up to date with news, certifications, free learning resources and much more.

Responses (3)