Java:可以设置Integer = null吗? [英] Java: Is it ok to set Integer = null?

查看:679
本文介绍了Java:可以设置Integer = null吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果参数存在于数据库中,我有一个返回id号的函数。如果不是,则返回null。这是否需要空指针异常?不允许使用负id号,但我认为将不存在的参数返回null而不是像-1这样的错误代码会更清楚。您怎么看?

I have a function that returns an id number if the argument exists in the database. If not, it returns null. Is this begging for a null pointer exception? Negative id numbers are not permitted, but I thought it would be clearer to have non-existent arguments returning null instead of an error code like -1. What do you think?

private Integer tidOfTerm(String name) throws SQLException {
    String sql = "SELECT tid FROM term_data WHERE name = ?";
    PreparedStatement prep = conn.prepareStatement(sql);
    prep.setString(1, name);
    ResultSet result = prep.getResultSet();

    if (result.next()) {
        return result.getInt("tid");
    }

    return null; // TODO: is this begging for a null pointer exception?
}


推荐答案

这是完全合法的。如果要避免使用NPE,请抛出自定义异常。但是不要返回负数。如果调用者没有检查返回值,则总会出现问题。但是,进行 false 计算(因为结果例如乘以-1)肯定比未捕获的异常更难调试。

This is perfectly legal. If you want to avoid a NPE, throw a custom exception. But don't return a negative number. If the caller doesn't check the return value, you will always have a problem. But doing false calculation (because the result is for instance multiplied by -1) is definitely harder to debug than an uncatched exception.

这篇关于Java:可以设置Integer = null吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆