代码简洁优化的一点思考:函数参数的判断与return 语句的使用

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.养成尽量使用现有工具类的代码习惯,已有的轮子自己没必要造,除非你有自信比人家写的更好,我水平初级,还没那个能力,还是老老实实多向人家靠拢。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值