上次一篇“你写的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正确吗?的更多相关文章

  1. Intellij Idea 12 开发Android 报Caused by: java.lang.UnsatisfiedLinkError: FindLibrary return null;

    这次开发是用的百度地图api,导入两个so文件,结果启动的时候总是报Caused by: java.lang.UnsatisfiedLinkError: findlibrary return null ...

  2. delete attempted to return null from a method with a primitive return type (int)

    今天被自己给蠢死了 今天在代码中遇到这个错误, 百度翻译一下:映射方法,从一org.system.mapper.child.chmorganizationexaminationmapper.delet ...

  3. 在Java中,return null 是否安全, 为什么?

    Java代码中return value 为null 是不是在任何情况下都可以,为什么不会throw NullPointerException? Java语言层面:null值自身是不会引起任何问题的.它 ...

  4. mybatis查询时使用基本数据类型接收报错-attempted to return null from a method with a primitive return type (int)

    一.问题由来 自己在查看日志时发现日志中打印了一行错误信息为: 组装已经放养的宠物数据异常--->Mapper method 'applets.user.mapper.xxxMapper.xxx ...

  5. [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 ...

  6. js中return false; jquery中需要这样写:return false(); Jquery 中循环 each的用法 for循环

    js中return false; jquery中需要这样写:return false(); Jquery 中循环 each的用法 $(".progressName").each(f ...

  7. Unity中yield return null和yield return WaitForEndOfFrame的区别

    2017/07/04修改 - 对WaitForEndOfFrame的LateUpdate时序进行说明. 测试结论: 1.如果只是等待下一帧执行,用yield return null即可.调用顺序在Up ...

  8. 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. ...

  9. How to return NULL string

    Q: std::string get_file_contents(const char *filename) { std::ifstream in(filename, std::ios::in | s ...

随机推荐

  1. MySQL——保证数据的完整性

    为了防止垃圾的产生,从而影响数据库的执行效率. 1实体完整性——行数据的有效性   唯一约束(unique).主键约束(primary key) 2域完整性——列数据的有效性 非空约束(not nul ...

  2. 第一课1、ROS

    ---恢复内容开始--- 1.什么是ROS ROS起源于2007年,斯坦福大学的人工智能实验室与机器人技术公司Willow Garage针对其个人机器人项目开发了ROS的雏形. ROS大致每年发布一个 ...

  3. qweb

    qweb 是 odoo的模板系统, 在 odoo系统中, 它有不同的用途和实现, 一个是 web client 的 widget 的渲染引擎, 它是通过 javascript实现的,也是 最早引入到 ...

  4. poj1014(还需要改动)

    #include <stdio.h> int n[6]; int main() { freopen("in.txt","r",stdin); int ...

  5. win64

    修改IIS应用程序池,启用支持32位 未能写入输出文件“c:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary AS

  6. 【Mail】搭建邮件服务器(LAMP+Postfix+Dovcot+PostfixAdmin+Roundcubemail)

    大纲 一.mail部署说明 二.安装准备 三.LMAP环境配置 四.配置postfixadmin 五.配置postfix 六.配置dovecot 七.测试SMTP和POP3服务 八.配置Roundcu ...

  7. psp工具需求分析

    PSP个人软件过程开发工具需求分析文档 a.业务需求    a.1 背景 二十一世纪是软件开发的黄金时期,有人把过去的十年称作软件高度发展的十年,不可置疑,越来越多的软件设计需求是物联网时代的趋势,越 ...

  8. hdu 1142(DFS+dijkstra)

    #include<iostream> #include<cstdio> #include<cmath> #include<map> #include&l ...

  9. Spring aop 原始的工作原理的理解

    理解完aop的名词解释,继续学习spring aop的工作原理. 首先明确aop到底是什么东西?又如何不违单一原则并实现交叉处理呢? 如果对它的认识只停留在面向切面编程,那就脏了.从oop(Objec ...

  10. ANSI C 所有的转义字符

    \a 响铃符 \b 回退符 \f 换页符 \n 换行符 \r 回车符 \t 横向制表符 \v 纵向制表符 \\ 反斜杠 \? 问号 \' 单引号 \" 双引号 \000 八进制数 \xhh ...