Java 是沉默的争论还是大喊大叫?

Java 是沉默的争论还是大喊大叫?,java,Java,我们就这个方法进行了讨论- public static AbstractAttribute getAttribute(List<AbstractAttribute> attributes, String name) { if ((attributes != null) && (name != null) && !name.trim().isEmpty()) { for (AbstractAttribute attribute :

我们就这个方法进行了讨论-

public static AbstractAttribute getAttribute(List<AbstractAttribute> attributes, String name) {
    if ((attributes != null) && (name != null) && !name.trim().isEmpty()) {
        for (AbstractAttribute attribute : attributes) {
            if (attribute.getName().equalsIgnoreCase(name)) {
                return attribute;
            }
        }
    }
    return null;
}
getAttribute(null,null); // returns null
getAttribute(list,null); // returns null
getAttribute(null,name); // returns null
getAttribute(list,name); //  may return null if not found
所有这些调用都可能返回null,那么客户端如何理解不同类型调用之间的差异呢?他可能错误地调用了带有null参数的方法——并且他收到了null结果,就好像所有ok和属性都没有在列表中找到,但根本找不到一样。 隐马尔可夫模型。。。不知道,但我想一定有arg检查

您应该问自己,哪一个对开发人员更有用

AbstractAttribute a = getAttribute(null, "name");

a.something(); // Oh no, null pointer.

您的
异常
应该始终尽可能接近实际问题。如果他们的参数有问题,会严重中断方法的功能,那么抛出异常!开发人员需要知道他们的错误,您有责任确保错误尽可能清楚

编辑

是的,你说得对。你的信息需要具体

public Object myFunction(String something, String somethingElse) {
    // First option - Not so good.
    if(something == null || somethingElse == null) {
        throw new IllegalArgumentException("Invalid parameters. Can not be null");
    }

    // Second option - much better.

    if(something == null) {
        throw new IllegalArgumentException("Something can not be null");
    }

    if(somethingElse == null) {
        throw new IllegalArgumentException("Something else can not be null");
    }
}

毫无疑问,
属性
名称
——您应该
抛出新的IllegalArgumentException(“列表不应为空”)
,并为
名称==null
发送不同的消息。但是,如果在列表中找不到该名称,则可以根据您的特定应用程序做出设计决策,您可以决定返回
null
,而不是抛出异常。当然,您必须在JavaDoc.IMHO中记录决策,它取决于设计。以偏执的方式进行参数检查甚至可能会增加性能惩罚,您可能正在检查可能永远不会发生的条件。如果参数是静态地(由开发人员)提供的,或者是在其他地方收集后由开发人员控制的,那么文档中的注释比代码中的检查更好。这样,开发人员必须在调用您的方法之前检查数据。@watery是的,如果同一个人/团队正在使用该API,并且知道该参数永远不会为null,则不应检查该参数。我的评论是针对您向另一个团队或开发社区(例如JavaSDKAPI)提供API的情况编写的,+1并按照我认为您的意图编辑了您的示例。(也投票重新开始这个问题)是的,谢谢你纠正错误!只是无法理解为什么该方法必须\may在空列表中静默搜索属性。你一定是错误地将null放入参数中,如果出现异常,你可能无法尽快发现错误。对我来说,这就像被零除一样,然后捕获错误,什么也不做,而不是在逻辑中查找错误并修复它。克里斯托弗,在所有情况下都有可能得到null,即使所有参数都不是null。。。
public Object myFunction(String something, String somethingElse) {
    // First option - Not so good.
    if(something == null || somethingElse == null) {
        throw new IllegalArgumentException("Invalid parameters. Can not be null");
    }

    // Second option - much better.

    if(something == null) {
        throw new IllegalArgumentException("Something can not be null");
    }

    if(somethingElse == null) {
        throw new IllegalArgumentException("Something else can not be null");
    }
}