你写的return null正确吗?
上次一篇“你写的try…catch真的有必要吗”引起了很多朋友的讨论。本次我在code review又发现了一个问题,那就是有人有意无意的写出了return null这样的代码,例如:
public User GetUser(Guid userId)
{
if ( /*for some reason*/)
return null; return DB.GetByUserId(userId);
}
这样的写法有木有问题?
在我看来没有充分的理由不应该返回null,因为方法的使用者并不知道在何种条件下会得到null,从而导致臭名昭著的NullReferenceException异常。
如果由于其他原因导致无法得到一个User,我们应该抛出一个明确的异常供上层服务决定如何处理:
public User GetUser(string userName, string password)
{
if ( /*for some reason*/)
return new SpecificException("can't get this user because ...."); return DB.GetByUserId(userId);
}
在我读过的开源项目中我几乎没有见到过return null的写法。能让我一时想到的两个linq方法FirstOrDefault()和LastOrDefault(),这两个方法通过命名的方式提醒使用者该方法会返回null。
说到FirstOrDefault()方法让我想起了很多人容易犯的另一个错误:
public User GetUserById(Guid userId)
{
return list.FirstOrDefault(x=>x.UserId==userId);
}
在确认数据库中该userId必须对应一个User的情况下使用FirstOrDefault()方法,此种场景我会建议你果断使用Single()方法。因为此时使用FirstOrDefault()会隐藏bug。你期望该userId必须得到一个User,如果Single()方法抛出异常则说明有bug出现,并且让你在第一时间发现该bug。
F#为了减少null类型的使用引入了option类型,在将option用作函数的返回类型时,如果没有对未定义的类型做处理,编译器会报错。
let invalidInt = None match invalidInt with
| Some x -> printfn "the valid value is %A" x
| None -> printfn "the value is None"
如果此处的模式匹配忘记编写None->分支,编译器将会报错,从而提醒你必须处理invalidInt值为None时的逻辑。但是在C#中使用null类型,编译器给予不了我们帮助,所以我们应该避免return null这样的代码,你觉得呢?
刚才搜了一下stackoverflow,发现一篇很有意思的讨论 Should a retrieval method return 'null' or throw an exception when it can't produce the return value? 我觉得里面的回答比较准确。
你写的return null正确吗?的更多相关文章
- Intellij Idea 12 开发Android 报Caused by: java.lang.UnsatisfiedLinkError: FindLibrary return null;
这次开发是用的百度地图api,导入两个so文件,结果启动的时候总是报Caused by: java.lang.UnsatisfiedLinkError: findlibrary return null ...
- delete attempted to return null from a method with a primitive return type (int)
今天被自己给蠢死了 今天在代码中遇到这个错误, 百度翻译一下:映射方法,从一org.system.mapper.child.chmorganizationexaminationmapper.delet ...
- 在Java中,return null 是否安全, 为什么?
Java代码中return value 为null 是不是在任何情况下都可以,为什么不会throw NullPointerException? Java语言层面:null值自身是不会引起任何问题的.它 ...
- mybatis查询时使用基本数据类型接收报错-attempted to return null from a method with a primitive return type (int)
一.问题由来 自己在查看日志时发现日志中打印了一行错误信息为: 组装已经放养的宠物数据异常--->Mapper method 'applets.user.mapper.xxxMapper.xxx ...
- [LeetCode OJ] Linked List Cycle II—Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode ...
- js中return false; jquery中需要这样写:return false(); Jquery 中循环 each的用法 for循环
js中return false; jquery中需要这样写:return false(); Jquery 中循环 each的用法 $(".progressName").each(f ...
- Unity中yield return null和yield return WaitForEndOfFrame的区别
2017/07/04修改 - 对WaitForEndOfFrame的LateUpdate时序进行说明. 测试结论: 1.如果只是等待下一帧执行,用yield return null即可.调用顺序在Up ...
- rg.apache.ibatis.binding.BindingException: Mapper method 'com.dao.Cameao.getOnlineDayRation attempted to return null from a method with a primitive return type (float)
本文为博主原创,未经允许不得转载: 异常展示如下: org.apache.ibatis.binding.BindingException: Mapper method 'com.dao.Cameao. ...
- How to return NULL string
Q: std::string get_file_contents(const char *filename) { std::ifstream in(filename, std::ios::in | s ...
随机推荐
- 第九章 springboot + mybatis + 多数据源 (AOP实现)(转载)
本编博客转发自:http://www.cnblogs.com/java-zhao/p/5415896.html 1.ShopDao package com.xxx.firstboot.dao; imp ...
- SEO和SEM的区别
SEO是属于SEM的一部分,SEO和SEM最主要的是最终目标的不同: SEO主要是为了关键词的排名.网站的流量.网站的结构.搜索引擎中页面收录的数据. SEM是通过SEO技术基础上扩展为搜索引擎中所带 ...
- seaJS 简单例子,理解seaJS
学习心得: 记得第一次学underscore的时候,去的官网(不管什么都是官网好),呼啦一长列语法,我就一个个看,看完也不知道underscore是做什么的.就是现在underscore我也用不上,学 ...
- Qt 5.7设置调试器
mingw版本下自带的,这个我就不在赘述. 现在来说一下msvc版本下调试器,cdb,这个需要到ms去下载. thunder://QUFodHRwOi8vZG93bmxvYWQubWljcm9zb2Z ...
- Git 源代码管理工具
Git 源代码管理工具 Git基本信息 Git :Git是一个“分布式”的版本控制工具 Git的作者是Linux之父 Linus Benedict Torvolds,当初开发Git仅仅是为了辅助Lin ...
- 用栈解决Largest Rectangle问题
一问题描述 Given n non-negative integers representing the histogram's bar height where the width of each ...
- redis cluster节点管理测试
####redis v3.2.0###添加节点:1.添加master节点 170 ./redis-trib.rb add-node 127.0.0.1:7007 127.0.0.1:7001 171 ...
- spring自动装配
spring提供了自动装配(autowiring)和自动检测(autodiscovery)用来减少XML的配置数量. 自动装配bean属性 byName——把与Bean的属性具有相同名字(或ID)的其 ...
- ES5 getter setter
最近在学习vuejs,了解到内部实现使用到了es5的Getters和Setters.之前看高程的时候,没有重视这块,今天查看一下文档,了解了他们的作用,再次记录一下,可供以后查看和共享. 定义Gett ...
- 谁动了我的特征?——sklearn特征转换行为全记录
目录 1 为什么要记录特征转换行为?2 有哪些特征转换的方式?3 特征转换的组合4 sklearn源码分析 4.1 一对一映射 4.2 一对多映射 4.3 多对多映射5 实践6 总结7 参考资料 1 ...