有效的java非常强调变量的本地化范围。但是如果我们有一个 if else 它可能会导致多次贬值,例如:
public List<E> midPoint() {
if (first == null) {
throw new NullPointerException("Linked list is empty");
}
if (first.next == null) {
ArrayList<E> arr = new ArrayList<E>();
arr.add(first.element);
return arr;
}
Node<E> fast = first.next;
Node<E> slow = first;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
// even count for number of nodes in linkedlist.
if (fast != null) {
ArrayList<E> arr = new ArrayList<E>();
arr.add(slow.element);
arr.add(slow.next.element);
return arr;
} else {
ArrayList<E> arr = new ArrayList<E>();
arr.add(slow.element);
return arr;
}
}
在上面的代码中,Arraylist 定义/声明多次出现,但变量是本地化的。它是好的方式还是应该在顶部声明 arrayList 并在其匹配条件的地方返回:例如:
public List<E> midPoint() {
if (first == null) {
throw new NullPointerException("Linked list is empty");
}
ArrayList<E> arr = new ArrayList<E>(); // NOTE - JUST A SINGLE DECLARATION.
if (first.next == null) {
arr.add(first.element);
return arr;
}
Node<E> fast = first.next;
Node<E> slow = first;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
// even count for number of nodes in linkedlist.
if (fast != null) {
arr.add(slow.element);
arr.add(slow.next.element);
return arr;
} else {
arr.add(slow.element);
return arr;
}
}
谢谢