JAVA面试(四)

这里列出10条JAVA编程经验

1 字符串常量放在前面

  把字符串常量放在equals()比较项的左侧来防止偶然的NullPointerException。

// Bad
if (variable.equals("literal")) { ... }
 
// Good
if ("literal".equals(variable)) { ... }

2 不要相信-1

// Bad
if (string.indexOf(character) != -1) { ... }
// Good
if (string.indexOf(character) >= 0) { ... }

3 避免意外的赋值

如果你的表达式中有常量,将它放在等式左边。这样当你打算再添加一个 = 时,不容易出错。

// Ooops
if (variable = 5) { ... } 
// Better (because causes an error)
if (5 = variable) { ... }
// Intent (remember. Paranoid JavaScript: ===)
if (5 === variable) { ... }

4 检查NULL和长度

不管什么时候你有一个集合、数组或者其他的,确保它存在并且不为空

// Bad
if (array.length > 0) { ... }
// Good
if (array != null && array.length > 0) { ... }

当然也可以用Collections.isEmpty() 判断

5 所有的方法都用final声明

你可以告诉我任何你想要的开闭原则,不过那都是胡说八道。我不相信你(可以正确继承我的类),也不相信我自己(不会意外地继承我的类)。因此除了接口(专门用于继承)都应该是严格的 final

// Bad
public void boom() { ... }
 
// Good. Don't touch.
public final void dontTouch() { ... }

6 所有的变量和参数都用final声明

// Bad
void input(String importantMessage) {
    String answer = "...";
 
    answer = importantMessage = "LOL accident";
}
 
// Good
final void input(final String importantMessage) {
    final String answer = "...";
}

7 重载的时候不要相信泛型

// Bad
<T> void bad(T value) {
    bad(Collections.singletonList(value));
}
 
<T> void bad(List<T> values) {
    ...
}
 
// Good
final <T> void good(final T value) {
    if (value instanceof List)
        good((List<?>) value);
    else
        good(Collections.singletonList(value));
}
 
final <T> void good(final List<T> values) {
    ...
}

8 总是在switch语句里加上default

// Bad
switch (value) {
    case 1: foo(); break;
    case 2: bar(); break;
}
 
// Good
switch (value) {
    case 1: foo(); break;
    case 2: bar(); break;
    default:
        throw new ThreadDeath("That'll teach them");
}

9 用大括号隔开switch的每一个case块

// Bad, doesn't compile
switch (value) {
    case 1: int j = 1; break;          
    case 2: int j = 2; break;          // j重复定义
}
 
// Good
switch (value) {
    case 1: {
        final int j = 1;
        break;
    }
    case 2: {
        final int j = 2;
        break;
    }
 
    // Remember:
    default: 
        throw new ThreadDeath("That'll teach them");
}
原文地址:https://www.cnblogs.com/liufei1983/p/7200295.html