本文介绍了使用Collections.emptyList()和null处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说到在Java中处理nulls的最佳实践(特别是List返回),从实体类的getMethod返回Collections.emptyList()是一个好习惯吗?或者我们应该保持实体/数据类/方法整洁干净并始终返回它的值(甚至是null)然后在代码中的其他地方处理该null,例如;

Speaking of best practices to handle "nulls" in Java(especially "List" returns), is it a good practise to return "Collections.emptyList()" from an entity class's getMethod? or should we keep the entity/data classes/methods neat and clean and always return whatever its value is(even its null) then handle that null somewhere else in the code, for example;

Class Reference{

private Reference reference;

@XmlElement(name = "Reference")
public List<Reference> getReference() {
    if(reference==null){
        return Collections.emptyList();
    }
    return reference;
}

public void setReference(List<Reference> reference) {
    this.reference = reference;
}
}

或者更好地处理我使用之后一个基本的获取方法?

Or better to handle that null "after" I use a basic get method?

编辑/警告:仅针对我的方案我注意到这种方法导致我的代码崩溃我不知道为什么,当我后来打电话;

EDIT/WARNING: just for my scenario I noticed this approach crashs my code I dont why, when I later call;

References ref= (References) jaxbUnmarshaller.unmarshal(xmlReader)

我得到了一个不受支持的操作异常,但是当我从collections.emtpyList清理我的getMethod时工作正常。使用@XmlElement标记时要小心

I get an unsupported operation exception, but works ok when I clean my getMethod from collections.emtpyList. So caution when using with a @XmlElement tag

推荐答案

返回非空集合确实是一种好习惯。它可以使每个调用者免于执行

It's indeed good practice to return a non-null collection. It saves every caller from doing

if (list != null) {
    for (Item i : list) {
        ...
    }
}

所以上面的代码很好。但是,在引用变量中禁止任何空值会更精细。如果您有列表的setter,如果传递的列表为null,则使其抛出异常,或者将null转换为空集合。这样,即使是类中的代码也不必担心引用变量为null。

So the above code is fine. But it would be even finer to disallow any null value in the reference variable. If you have a setter for the list, make it throw an exception if the passed list is null, or transform null into an empty collection. This way, even the code inside your class won't have to bother with the reference variable being null.

如果需要区分null和empty list,请考虑使用类,这使事情变得更加清晰。

If you need to distinguish between null and empty list, consider using Guava's Optional class, which makes things much clearer.

只需注意:由于你有一个列表,变量应该是命名为引用(最终 s ),访问者应命名为 getReferences setReferences

Just a note: since you have a list, the variable should be named references (with a final s), and the accessors should be named getReferences and setReferences.

这篇关于使用Collections.emptyList()和null处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 15:12