关于java方法里的非空判断的疑问,谢谢
本文介绍了关于java方法里的非空判断的疑问,谢谢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
public static void main(String[] args) {
String result = replaceStr("jaja");
if (result != null) { //在这里又要判断下非空
int count = 50 + Integer.parseInt(result);
}
}
public static String replaceStr(String tem){
String result;
if (tem == null) {
result = null;
} else {
String substring = tem.substring(0, 1);
result = substring;
}
return result;
}
如上代码,我的疑惑时,当参数tem为空,方法返回null,那岂不是又要在调用
replaceStr
这个方法的地方又要判断次返回值是否为null?那这个代码看上去不是很难看,好多if(**!=null)这样的语句。我想问的是:有没有一种设计,可以只要在一处判断非空,其他地方只要写业务逻辑就行了?
谢谢
解决方案
改了一下你的代码:
public static String replaceStr(String tem){
if (tem == null || tem.length() == 0) {
return null;
}
return tem.substring(0, 1);
}
首先,判断非空这种业务需求是无法避免的,或者你可以在设计的时候加上默认值,当返回值为null时就使用默认值(具体还要视乎业务上遇到null值时下一步要怎么处理,或使用默认值,或抛出异常,或终止执行,etc)。
关于默认值的使用可以看一下guava的MoreObjects#firstNonNull。
java8中的Optional就是为了解决这种判空的问题(其实还是免不了判断,只是换了种方式避免NullPointerException),也可以看一下。
另外,直接ctrl+c spring的StringUtils#replace方法给你(同理也可以参考apache common的StringUtils,反正java的世界就不缺StringUtils),可以参考一下别人是怎样实现的。
/**
* Replace all occurrences of a substring within a string with
* another string.
* @param inString {@code String} to examine
* @param oldPattern {@code String} to replace
* @param newPattern {@code String} to insert
* @return a {@code String} with the replacements
*/
public static String replace(String inString, String oldPattern, String newPattern) {
if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) {
return inString;
}
StringBuilder sb = new StringBuilder();
int pos = 0; // our position in the old string
int index = inString.indexOf(oldPattern);
// the index of an occurrence we've found, or -1
int patLen = oldPattern.length();
while (index >= 0) {
sb.append(inString.substring(pos, index));
sb.append(newPattern);
pos = index + patLen;
index = inString.indexOf(oldPattern, pos);
}
sb.append(inString.substring(pos));
// remember to append any characters to the right of a match
return sb.toString();
}
这篇关于关于java方法里的非空判断的疑问,谢谢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文