gpt4 book ai didi

java - 我们是否应该以多个声明为代价来本地化作用域变量

转载 作者:行者123 更新时间:2023-12-01 23:45:32 24 4
gpt4 key购买 nike

Effective 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;
}
}

谢谢

最佳答案

在这种情况下,建议您仅在一处声明。它将更具可读性并节省一些代码行。

重命名也很好,也许可以表明这是您的方法的最终结果(例如 returnArrayresultArray)。

在其他情况下,当该列表意味着几个不同的事物时,最好声明它,在这种情况下,您也会有不同的名称。

关于java - 我们是否应该以多个声明为代价来本地化作用域变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17128976/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com