【鲁棒】最佳实践

1.状态检查

1.1 类型强制转换 检查实例类型

if (value instanceof LogData) {
            LogData logData = (LogData)value;
}

1.2 迭代器 检查hasNext()

for (Iterator<Foo> i = collection.iterator(); i.hasNext(); ) {
    Foo foo = i.next();
    ...
}

2.参数检查

在方法调用开始处进行参数检查,检查是否符合方法执行的限制。

2.1 非空检查

如果没有非空检查,就对实例进行操作的话,当传入空值时会抛出NullPointerException。常用工具类是Assert类,当对象为空时,会抛出IllegalArgumentException

import org.springframework.util.Assert;
import org.springframework.beans.BeanUtils;


// 样例方法
public static void fromPlainObj(Object sourcePlainObj, Object target, Set<Class> neededPlains,String[] ignoreProperties) {
    Assert.notNull(sourcePlainObj);
    Assert.notNull(target);
    Assert.notNull(neededPlains);
    Field[] targetFields = target.getClass().getDeclaredFields();
    BeanUtils.copyProperties(sourcePlainObj, target, ignoreProperties);
    ...
}
// Assert.isNull
public static void isNull(Object object) {
	isNull(object, "[Assertion failed] - the object argument must be null");
}

public static void notNull(Object object, String message) {
	if (object == null) {
		throw new IllegalArgumentException(message);
	}
}

2.2 数组对象检查

2.2.1 数组类型检查

数组类型强制转换之前需要进行数据类型判断

// ObjectUtils.isArray
// 检查对象是数组对象
public static boolean isArray(Object obj) {
	return (obj != null && obj.getClass().isArray());
}

2.2.2 数据内容检查

数组为null或者长度为0的时候,使用arr[i]访问时会抛出NullPointerException或者ArrayIndexOutOfBoundsException。

// Assert.notEmpty
// 为空或者长度为0 抛IllegalArgumentException
public static void notEmpty(Object[] array, String message) {
	if (ObjectUtils.isEmpty(array)) {
		throw new IllegalArgumentException(message);
	}
}
// ObjectUtils.isEmpty
public static boolean isEmpty(Object[] array) {
	return (array == null || array.length == 0);
}

2.2.3 数组下标检查

// 递归分治排序 offset是子数组开始下标 len表示子数组长度
private static void sort(long a[], int offset, int length) {
	assert a != null;
	assert offset >= 0 && offset <= a.length;
	assert length >= 0 && length <= a.length - offset;
	... // 计算
}
 
发布了92 篇原创文章 · 获赞 14 · 访问量 5853

猜你喜欢

转载自blog.csdn.net/sarafina527/article/details/102913084
今日推荐