Open In App

Writing clean if else statements

Improve
Improve
Like Article
Like
Save
Share
Report

Using if else chaining some time looks more complex, this can be avoided by writing the code in small blocks. Use of conditional statement increases the code readability and much more. One best practice should be handling error case first. Below shown example shows how to handle error cases and simplify the if else logic.
Examples 1: 
updateCache()- It’s a method in which on the basis of some class level variables decision is taken for update main db. 
updateBackupDb()- It’s a method to update the DB. 
Using this type of if else is harder to debug and extend any feature in existing function. 
Before optimization 
 

Java




// A simple method handling the data
// base operation related task
private void updateDb(boolean isForceUpdate) {
 
  // isUpdateReady is class level
  // variable
  if (isUpdateReady) {
 
    // isForceUpdate is argument variable
    // and based on this inner blocks is
    // executed
    if (isForceUpdate) {
 
      // isSynchCompleted is also class
      // level variable, based on its
      // true/false updateDbMain is called
      // here updateBackupDb is called
      // in both the cases
      if (isSynchCompleted) {
        updateDbMain(true);
        updateBackupDb(true);
 
      } else {
        updateDbMain(false);
        updateBackupDb(true);
      }
    } else {
 
      // execute this if isUpdateReady is
      // false i. e., this is dependent on
      // if condition
      updateCache(!isCacheEnabled);
 
      // end of second isForceUpdate block
    }
 
    // end of first if block
  }
 
  // end of method
}


Observations : 
In below code the boolean variables has been identified and based on that 
code is broken into small blocks using if and return statement. 
1. If update is not ready then this is not required to enter in method 
just exit from this method. 
2. Similarly is force update boolean is false then perform the task in if statement 
– updating the cache and returning from this method. 
3. In the last step rest all task is done updating backup db and updating main db. 
After optimization 
 

Java




// A simple method handling the
// data base operation related
// task
private void updateDb(boolean isForceUpdate) {
 
  // If isUpdateReaday boolean is not
  // true then return from this method,
  // nothing was done in else block
  if (!isUpdateReady)
    return;
 
  // Now if isForceUpdate boolean is
  // not true then only updating the
  // cache otherwise this block was
  // not called
  if (!isForceUpdate) {
    updateCache(!isCacheEnabled);
    return;
  }
 
  // After all above condition is not
  // fulfilled below code is executed
  // this backup method was called two
  // times thus calling only single time
  updateBackupDb(true);
 
  // main db is updated based on sync
  // completed method
  updateDbMain(isSynchCompleted ? true : false);
}


Note- What major consideration is taken in above optimization version is simplify the if else based on the conditional statement. 
The benefit of this type of easy blocks of code is – for the next developer it is very easy to debug/understand/extend this method.
Example 2: 
Explaining this idea via existing JAVA API code example 
This code snippet is taken from Java Doc:- 
JDK sub string code JAVA API 
Existing code from above API- this is written perfect. 
After Optimization 
 

Java




public String substring(int beginIndex, int endIndex) {
 
  // My comment - Below are the example of
  // correct use of if else, checking
  // condition and returning from // methods,
  // this is not about throwing error ie
  // return or throw error or do something
  // else - the idea is braking if // else
  // chaining.
  if (beginIndex < 0) {
    throw new StringIndexOutOfBoundsException(beginIndex);
  }
 
  if (endIndex > value.length) {
    throw new StringIndexOutOfBoundsException(endIndex);
  }
 
  int subLen = endIndex - beginIndex;
 
  if (subLen < 0) {
    throw new StringIndexOutOfBoundsException(subLen);
  }
  return ((beginIndex == 0) && (endIndex == value.length))
      ? this
      : new String(value, beginIndex, subLen);
}


If any one use if else as shown in below example after modifying above logic, it will be very complex but at the end producing same result so i would not prefer to implement as shown below – 
Before optimization 
 

Java




public String substring(int beginIndex, int endIndex) {
 
  if (beginIndex < 0) {
    throw new StringIndexOutOfBoundsException(beginIndex);
  } else {
 
    // Again why this else block is used,
    // this need not to write, see above
    // correct implementation
    if (endIndex > value.length) {
      throw new StringIndexOutOfBoundsException(endIndex);
    } else {
 
      // This else is also not required
      int subLen = endIndex - beginIndex;
      if (subLen < 0) {
        throw new StringIndexOutOfBoundsException(subLen);
      }
    }
    return ((beginIndex == 0) && (endIndex == value.length))
        ? this
        : new String(value, beginIndex, subLen);
  }
}


After seeing above two examples it can be observed that error handling is done while entering in method. This is good practice to handle error condition first.
Overall if else can be used in small blocks based on requirement that will remove code complexity and code will be easy to use/debug/maintain/extend.
 



Last Updated : 05 Aug, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads