📜  编写干净的 if else 语句

📅  最后修改于: 2022-05-13 01:55:14.864000             🧑  作者: Mango

编写干净的 if else 语句

使用 if else 链接一些时间看起来更复杂,这可以通过将代码编写成小块来避免。条件语句的使用增加了代码的可读性等等。一个最佳实践应该是首先处理错误情况。下面显示的示例显示了如何处理错误情况并简化 if else 逻辑。
示例 1:
updateCache() - 这是一种基于某些类级别变量决定更新主数据库的方法。
updateBackupDb() - 这是一种更新数据库的方法。
使用这种类型的 if else 更难调试和扩展现有函数中的任何功能。
优化前

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
}


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);
}


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);
}


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);
  }
}


观察:
在下面的代码中,布尔变量已被识别并基于它
使用 if 和 return 语句将代码分成小块。
1.如果更新未准备好,则不需要进入方法
只需退出此方法。
2. 同样是 force update boolean is false 然后在 if 语句中执行任务
– 更新缓存并从此方法返回。
3.在最后一步休息中,所有任务都完成了更新备份数据库和更新主数据库。
优化后

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);
}

注意-在上述优化版本中主要考虑的是基于条件语句简化 if else。
这种简单代码块的好处是——对于下一个开发人员来说,调试/理解/扩展这种方法非常容易。
示例 2:
通过现有的Java API 代码示例解释这个想法
此代码片段取自Java Doc:-
JDK子字符串代码Java API
来自上述 API 的现有代码——这写得很完美。
优化后

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 else 如下例所示,它将非常复杂,但最终会产生相同的结果,所以我不喜欢如下所示的实现 -
优化前

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);
  }
}

看了上面的两个例子可以看出,在进入方法的时候进行了错误处理。这是首先处理错误情况的好习惯。
总体而言,如果 if else 可以根据要求在小块中使用,这将消除代码复杂性,并且代码将易于使用/调试/维护/扩展。