简体   繁体   English

Java:null的默认值object更好

[英]Java: null of default value of object is better

The first case: There is a class that has another class as its data member.第一种情况:有一个 class 有另一个 class 作为其数据成员。 When this class is instantiated, what we should do with the data member?当这个 class 被实例化时,我们应该如何处理数据成员?

  • (A) In constructor: this.anotherClass = new AnotherClass(); (A) 在构造函数中:this.anotherClass = new AnotherClass();
  • (B) left it null, no need to instantiate it. (B) 留下null,不需要实例化它。

The second case: There is a class that has an ArrayList as its data member.第二种情况:有一个 class 有一个 ArrayList 作为其数据成员。 When this class is instantiated, what we should do with the ArrayList?当这个 class 被实例化时,我们应该如何处理 ArrayList?

  • (A) In constructor: this.bulidingList = new ArrayList< Building >(); (A) 在构造函数中:this.bulidingList = new ArrayList< Building >();
  • (B) left it null, no need to instantiate it. (B) 留下null,不需要实例化它。

The third case: when we create a method in which its return type is a collection , for example第三种情况:当我们创建一个返回类型为集合的方法时,例如

public ArrayList< Building > getBuildingList(){ /// Bah Bah Bah.. } public ArrayList< Building > getBuildingList(){ /// Bah Bah Bah.. }

if there is no Building, we should return the empty ArrayList " new ArrayList< Building >() " "or null .如果没有建筑物,我们应该返回空的 ArrayList " new ArrayList< Building >() " "或null

I would prefer not using null to avoid potential NullPointerException 's.我宁愿不使用 null 来避免潜在的NullPointerException To avoid creating unnecessary objects you could construct a single static instance to return, as long as it's immutable.为了避免创建不必要的对象,您可以构造一个 static 实例来返回,只要它是不可变的。 As for an empty ArrayList , you can use Collections.emptyList() to do this for you.至于空的ArrayList ,您可以使用Collections.emptyList()为您执行此操作。

In the end it's up to you how you want to define how your API works.最后,如何定义 API 的工作方式取决于您。 Either way you should clearly document it so the caller knows what to expect.无论哪种方式,您都应该清楚地记录它,以便调用者知道会发生什么。

What are your needs?你有什么需求? My general preference is to return null when possible as this avoids creating another object in memory.我的一般偏好是尽可能返回 null,因为这样可以避免在 memory 中创建另一个 object。

Provided that you ensure the documentation clearly states that the method may return null and it is the responsibility of calling code to handle that, I don't see a problem.如果您确保文档清楚地说明该方法可能返回 null 并且它是调用代码来处理它的责任,我认为没有问题。

There is no concrete answer.没有具体的答案。 It is a case of your API, or, speaking simpler, the expectations of the surrounded code.这是您的 API 的情况,或者更简单地说,是包围代码的期望。

Try to think in details about your getBuildingList().尝试详细考虑您的 getBuildingList()。 Is it ok to return null?可以退货 null 吗? Or null is forbidden and you should return empty list?或者 null 被禁止,你应该返回空列表?

Anyway, docuemtn you thoughts in javadoc for the method.无论如何,请在 javadoc 中记录您对该方法的想法。

Given the destructive nature of Nulls in Java, I think it's a good practice to return empty collections rather then null collections.鉴于 Java 中 Null 的破坏性,我认为返回空 collections 而不是 null116B9ABFE6EB17CCA22collections 是一个好习惯。

For Objects, you should return "null" if the object has no values set internally.对于对象,如果 object 内部没有设置值,则应返回“null”。

Is a default-initialized object meaningful, as an empty ArrayList certainly is?默认初始化的 object 是否有意义,就像空的 ArrayList 一样? Then instantiate it.然后实例化它。 Don't optimize prematurely.不要过早优化。

On the other hand, if a default AnotherClass makes no sense, then leave the member as null.另一方面,如果默认的AnotherClass没有意义,则将成员保留为 null。

Finally, if you run into performance or memory usage problems, consider revising the design.最后,如果遇到性能或 memory 使用问题,请考虑修改设计。

In my opinion, it is best to design your APIs to avoid returning a null if there is a better alternative.在我看来,如果有更好的选择,最好设计您的 API 以避免返回null

  • For collections, return an empty collection;对于 collections,返回一个空集合; eg Collections.emptyList() or new ArrayList() ... depending on the API requirements.例如Collections.emptyList()new ArrayList() ...取决于 API 要求。
  • For arrays, return an array of length zero.对于 arrays,返回长度为零的数组。
  • For objects, consider whether it is feasible to use a distinguished instance of the class, or to design the API so that the result can't be null in the first place.对于对象,考虑是否可以使用 class 的区分实例,或者设计 API 使得结果首先不能是null

If you do need to return null , or accept null as a method parameter, make sure that the javadoc clearly states that this is a valid result / argument... and what it means .如果您确实需要返回null ,或接受null作为方法参数,请确保 javadoc 明确指出这是一个有效的结果/参数......以及它的含义


The problem with APIs that use null is that developers forget about the null case and the result is an unexpected NullPointerException .使用null的 API 的问题是开发人员忘记null情况,结果是意外的NullPointerException You could say that's not the API designer's fault - the API user should have read the documentation.您可以说这不是 API 设计者的错 - API 用户应该阅读过文档。 But that doesn't really address the issue.但这并不能真正解决问题。 A better approach is to avoid returning the null in the first place, especially in cases where there is a simple alternative.更好的方法是首先避免返回null ,尤其是在有简单替代方案的情况下。

The other point is that a non-null value is generally easier for the caller to deal with.另一点是调用者通常更容易处理非空值。 A null typically has to be dealt with as a special case by the calling code. null通常必须由调用代码作为特殊情况处理。 A non-null value doesn't.非空值不会。 For example, you can iterate over an empty collection or array using a for loop, but a null has to be tested for explicitly.例如,您可以使用for循环遍历空集合或数组,但必须显式测试null

The third case: when we create a method in which its return type is a collection, for example第三种情况:当我们创建一个返回类型为集合的方法时,例如

public ArrayList< Building > getBuildingList(){ /// Bah Bah Bah.. }

This is awful, a public member should never return an implementation type.这太糟糕了,公共成员永远不应该返回实现类型。 The signature should be:签名应该是:

public List< Building > getBuildingList()

That way you can (and should) return Collections.emptyList() if your data is empty.这样,如果您的数据为空,您可以(并且应该)返回Collections.emptyList()

The first case: There is a class that has another class as its data member.第一种情况:有一个 class 有另一个 class 作为其数据成员。 When this class is instantiated, what we should do with the data member?当这个 class 被实例化时,我们应该如何处理数据成员?

(A) In constructor: this.anotherClass = new AnotherClass(); (A) 在构造函数中:this.anotherClass = new AnotherClass();

(B) left it null, no need to instantiate it. (B) 留下null,不需要实例化它。

I would prefer (C) In constructor: require a non-null AnotherClass parameter.我更喜欢 (C) 在构造函数中:需要一个非空的AnotherClass参数。

If you need a default constructor and you always expect the caller to also call setAnotherClass() afterwards you could leave it null in the constructor and check for null when you actually use the field, otherwise you should probably create a default AnotherClass object in the constructor.如果您需要一个默认构造函数并且您总是希望调用者在之后也调用setAnotherClass()您可以将它留在构造函数中null并在您实际使用该字段时检查 null ,否则您可能应该在构造函数中创建默认的AnotherClass ZA8CFDE6331BD59EB62AC96B .

The second case: There is a class that has an ArrayList as its data member.第二种情况:有一个 class 有一个 ArrayList 作为其数据成员。 When this class is instantiated, what we should do with the ArrayList?当这个 class 被实例化时,我们应该如何处理 ArrayList?

(A) In constructor: this.bulidingList = new ArrayList< Building >(); (A) 在构造函数中:this.bulidingList = new ArrayList< Building >(); (B) left it null, no need to instantiate it. (B) 留下null,不需要实例化它。

I would always instantiate it, but if the list is read-only I'd declare it this way instead:我总是会实例化它,但如果列表是只读的,我会这样声明它:

List<Building> buildingList = Collections.emptyList();

The third case: when we create a method in which its return type is a collection, for example第三种情况:当我们创建一个返回类型为集合的方法时,例如

public ArrayList< Building > getBuildingList(){ /// Bah Bah Bah.. } public ArrayList< Building > getBuildingList(){ /// Bah Bah Bah.. }

if there is no Building, we should return the empty ArrayList "new ArrayList< Building >()" "or null.如果没有建筑物,我们应该返回空的 ArrayList "new ArrayList< Building >()" "或 null。

I'm not especially proud about it, but I do sometimes return null when I want an additional return value, something like getBuildingsListAndReturnNullIfThereAreNoTenants .我对此并不特别自豪,但是当我想要一个额外的返回值时,我有时会返回null ,比如getBuildingsListAndReturnNullIfThereAreNoTenants When you just want to say "I haven't found any buildings" it's always better to return an empty list instead.当您只想说“我没有找到任何建筑物”时,最好返回一个空列表。

Sometimes you can do an upfront check and return Collections.emptyList() instead of creating a new ArrayList<Building> instance, but I wouldn't go out of my way to do it.有时您可以进行前期检查并返回Collections.emptyList()而不是创建新的ArrayList<Building>实例,但我不会 go 这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM