1.背景
在项目开发中,我们经常要传进去userId即用户id这个参数,如果用户参数是空,就不进行其他下面的业务操作。常常我们的书写方式如下:
if(userId != null){
// 以下是业务代码
..........
}
2.局限与问题
在spring 框架中包装了很多判断参数是否为空的工具类,比如StringUtils、ObjectUtils,我们完全可以用人家经过测试严密的工具类:
例如两个判断是否为空的源码:
/**
* Determine whether the given array is empty:
* i.e. {@code null} or of zero length.
* @param array the array to check
* @see #isEmpty(Object)
*/
public static boolean isEmpty(Object[] array) { //ObjectUtils.isEmpty()方法源码
return (array == null || array.length == 0);
}
/**
* Check whether the given {@code String} is empty.
* <p>This method accepts any Object as an argument, comparing it to
* {@code null} and the empty String. As a consequence, this method
* will never return {@code true} for a non-null non-String object.
* <p>The Object signature is useful for general attribute handling code
* that commonly deals with Strings but generally has to iterate over
* Objects since attributes may e.g. be primitive value objects as well.
* @param str the candidate String
* @since 3.2.1
*/
public static boolean isEmpty(Object str) { //Stringutils.isEmpty()方法,各种情况已经考虑的很完美
return (str == null || "".equals(str));
}
基于代码简洁优美避免重复造不好的轮子的想法,有必要习惯使用工具类。
3.工具类与return 语句结合使用
package basis;
import org.springframework.util.StringUtils;
public class TestReturn {
public static void main(String[] args) {
get(null); // 代码不睡输出xxx,说明return语句直接返回了,一下所有业务代码肯定不执行
}
private static void get(String userId) {
if (StringUtils.isEmpty(userId))
return;
System.out.println("xxx");
}
}
4.总结与提炼
1.不能仅仅追求完成业务功能的实现,要在保证业务功能实现的同时,追求代码简洁严密优美,尽量少bug。
2.养成尽量使用现有工具类的代码习惯,已有的轮子自己没必要造,除非你有自信比人家写的更好,我水平初级,还没那个能力,还是老老实实多向人家靠拢。