java integer 非空,Java:可以设置Integer = null吗?

讨论了一个关于数据库查询函数的设计,是否应该在不存在对应数据时返回null还是抛出自定义异常。作者认为返回null在法律上可行,但可能隐藏潜在问题。建议避免空指针异常,通过明确的错误处理来提高代码清晰度。
摘要由CSDN通过智能技术生成

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?

}

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值