重构的概念已经为广大的程序员所熟悉。但是还是有很多细节可以注意。
public static String getHiddenEmail(String email, int prefix, int suffix) {
// 仅对包含@的email账户进行处理
if (StringUtil.isBlank(email) || !StringUtil.contains(email, "@")) {
return email;
}
int length = email.length();
if (length < DEFAULT_TOTAL) {
return email;
}
// @所在位置
int splitPos = StringUtil.lastIndexOf(email, '@');
// @前的字符段
String preEmail = StringUtil.substring(email, 0, splitPos);
if (StringUtil.isBlank(preEmail)) {
return email;
}
// @后的字符段,包含@
String latEmail = StringUtil.substring(email, splitPos, length);
if (StringUtil.isBlank(latEmail)) {
return email;
}
if (preEmail.length() > 17)
preEmail = StringUtil.abbreviate(preEmail, prefix);
if (latEmail.length() > 13)
latEmail = StringUtil.abbreviate(latEmail, suffix);
return preEmail.concat(latEmail);
}
以上的code在我看来,有以下几个缺点。
1 方法名和实际的方法体不匹配。
2 魔数
3 if (StringUtil.isBlank(latEmail)) 永远返回false,因为当程序执行到这里,latEmail至少包括一个字符@。
4 方法中的代码的内聚性不够。主要是对preEmail和latEmail的处理分开了。
5 拼写错误,应该为lastEmail而误拼为latEmail
清洗代码后如下
private static String getAbbreviatedEmail(String email, int prefix, int suffix) {
if (StringUtil.isBlank(email)) {
return email;
}
if (email.length() <= DEFAULT_TOTAL) {
return email;
}
// @所在位置
int splitPos = StringUtil.lastIndexOf(email, '@');
if (splitPos == -1 || splitPos == 0|| splitPos == email.length() - 1) {
return email;
}
// @前的字符段
String preEmail = StringUtil.substring(email, 0, splitPos);
if (preEmail.length() > DEFAULT_PREFIX_LENGTH) {
preEmail = StringUtil.abbreviate(preEmail, prefix);
}
// @后的字符段,包含@
String lastEmail = StringUtil.substring(email, splitPos, email.length());
if (lastEmail.length() > DEFAULT_SUFFIX_LENGTH) {
lastEmail = StringUtil.abbreviate(lastEmail , suffix);
}
return preEmail+lastEmail ;
}
其实我个人最喜欢的风格是简单的方法的guard condition不用大括号{},这样代码变为
private static String getAbbreviatedEmail(String email, int prefix, int suffix) {
if (StringUtil.isBlank(email))
return email;
if (email.length() <= DEFAULT_TOTAL)
return email;
// @所在位置
int splitPos = StringUtil.lastIndexOf(email, '@');
if (splitPos == -1 || splitPos == 0|| splitPos == email.length() - 1)
return email;
// @前的字符段
String preEmail = StringUtil.substring(email, 0, splitPos);
if (preEmail.length() > DEFAULT_PREFIX_LENGTH) {
preEmail = StringUtil.abbreviate(preEmail, prefix);
}
// @后的字符段,包含@
String lastEmail = StringUtil.substring(email, splitPos, email.length());
if (lastEmail.length() > DEFAULT_SUFFIX_LENGTH) {
lastEmail = StringUtil.abbreviate(lastEmail , suffix);
}
return preEmail+lastEmail ;
}
谢谢论坛上朋友的讨论,preEmail+latEmail这个地方用+号比用concat方法好。