It appears that some people interpreted the title of one of my rants from many months ago, "Cleaner, more elegant, and wrong", to be a reference to exceptions in general. (See bibliography reference [35]; observe that the citer even changed the title of my article for me!)

The title of the article was a reference to a specific code snippet that I copied from a book, where the book's author claimed that the code he presented was "cleaner and more elegant". I was pointing out that the code fragment was not only cleaner and more elegant, it was also wrong.

You can write correct exception-based programming.

Mind you, it's hard.

On the other hand, just because something is hard doesn't mean that it shouldn't be done.

Here's a breakdown:

Really easy Hard Really hard
Writing bad error-code-based code
Writing bad exception-based code
Writing good error-code-based code Writing good exception-based code

It's easy to write bad code, regardless of the error model.

It's hard to write good error-code-based code since you have to check every error code and think about what you should do when an error occurs.

It's really hard to write good exception-based code since you have to check every single line of code (indeed, every sub-expression) and think about what exceptions it might raise and how your code will react to it. (In C++ it's not quite so bad because C++ exceptions are raised only at specific points during execution. In C#, exceptions can be raised at any time.)

But that's okay. Like I said, just because something is hard doesn't mean it shouldn't be done. It's hard to write a device driver, but people do it, and that's a good thing.

But here's another table:

Really easy Hard Really hard
Recognizing that error-code-based code is badly-written
Recognizing the difference between bad error-code-based code and not-bad error-code-based code.
Recognizing that error-code-base code is not badly-written
Recognizing that exception-based code is badly-written
Recognizing that exception-based code is not badly-written
Recognizing the difference between bad exception-based code and not-bad exception-based code

Here's some imaginary error-code-based code. See if you can classify it as "bad" or "not-bad":

BOOL ComputeChecksum(LPCTSTR pszFile, DWORD* pdwResult)
{
HANDLE h = CreateFile(pszFile, GENERIC_READ, FILE_SHARE_READ,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
HANDLE hfm = CreateFileMapping(h, NULL, PAGE_READ, 0, 0, NULL);
void *pv = MapViewOfFile(hfm, FILE_MAP_READ, 0, 0, 0);
DWORD dwHeaderSum;
CheckSumMappedFile(pvBase, GetFileSize(h, NULL),
&dwHeaderSum, pdwResult);
UnmapViewOfFile(pv);
CloseHandle(hfm);
CloseHandle(h);
return TRUE;
}

This code is obviously bad. No error codes are checked. This is the sort of code you might write when in a hurry, meaning to come back to and improve later. And it's easy to spot that this code needs to be improved big time before it's ready for prime time.

Here's another version:

BOOL ComputeChecksum(LPCTSTR pszFile, DWORD* pdwResult)
{
BOOL fRc = FALSE;
HANDLE h = CreateFile(pszFile, GENERIC_READ, FILE_SHARE_READ,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (h != INVALID_HANDLE_VALUE) {
HANDLE hfm = CreateFileMapping(h, NULL, PAGE_READ, 0, 0, NULL);
if (hfm) {
void *pv = MapViewOfFile(hfm, FILE_MAP_READ, 0, 0, 0);
if (pv) {
DWORD dwHeaderSum;
if (CheckSumMappedFile(pvBase, GetFileSize(h, NULL),
&dwHeaderSum, pdwResult)) {
fRc = TRUE;
}
UnmapViewOfFile(pv);
}
CloseHandle(hfm);
}
CloseHandle(h);
}
return fRc;
}

This code is still wrong, but it clearly looks like it's trying to be right. It is what I call "not-bad".

Now here's some exception-based code you might write in a hurry:

NotifyIcon CreateNotifyIcon()
{
NotifyIcon icon = new NotifyIcon();
icon.Text = "Blah blah blah";
icon.Visible = true;
icon.Icon = new Icon(GetType(), "cool.ico");
return icon;
}

(This is actual code from a real program in an article about taskbar notification icons, with minor changes in a futile attempt to disguise the source.)

Here's what it might look like after you fix it to be correct in the face of exceptions:

NotifyIcon CreateNotifyIcon()
{
NotifyIcon icon = new NotifyIcon();
icon.Text = "Blah blah blah";
icon.Icon = new Icon(GetType(), "cool.ico");
icon.Visible = true;
return icon;
}

Subtle, isn't it.

It's easy to spot the difference between bad error-code-based code and not-bad error-code-based code: The not-bad error-code-based code checks error codes. The bad error-code-based code never does. Admittedly, it's hard to tell whether the errors were handled correctly, but at least you can tell the difference between bad code and code that isn't bad. (It might not be good, but at least it isn't bad.)

On the other hand, it is extraordinarily difficult to see the difference between bad exception-based code and not-bad exception-based code.

Consequently, when I write code that is exception-based, I do not have the luxury of writing bad code first and then making it not-bad later. If I did that, I wouldn't be able to find the bad code again, since it looks almost identical to not-bad code.

My point isn't that exceptions are bad. My point is that exceptions are too hard and I'm not smart enough to handle them. (And neither, it seems, are book authors, even when they are trying to teach you how to program with exceptions!)

(Yes, there are programming models like RAII and transactions, but rarely do you see sample code that uses either.)

Cleaner, more elegant, and harder to recognize (msdn blog)的更多相关文章

  1. Cleaner, more elegant, and harder to recognize(翻译)

    Cleaner, more elegant, and harder to recognize 更整洁,更优雅,但更难识别 看来,有些人把我几个月前一篇文章的标题"Cleaner,more e ...

  2. Cleaner, more elegant, and wrong(msdn blog)

    Cleaner, more elegant, and wrong Just because you can't see the error path doesn't mean it doesn't e ...

  3. Cleaner, more elegant, and wrong(翻译)

    Cleaner,more elegant,and wrong 整洁,更优雅,但是错的 并不是因为你看不到错误的产生路径就意味着它不存在. 下面是C#编程书中的一个片段,摘自关于异常处理的章节. try ...

  4. Go 开发关键技术指南 | 敢问路在何方?(内含超全知识大图)

    作者 | 杨成立(忘篱) 阿里巴巴高级技术专家 Go 开发关键技术指南文章目录: 为什么你要选择 Go? Go 面向失败编程 带着服务器编程金刚经走进 2020 年 敢问路在何方? Go 开发指南大图 ...

  5. Go 开发关键技术指南 | Go 面向失败编程 (内含超全知识大图)

    作者 | 杨成立(忘篱) 阿里巴巴高级技术专家 关注"阿里巴巴云原生"公众号,回复 Go 即可查看清晰知识大图! 导读:从问题本身出发,不局限于 Go 语言,探讨服务器中常常遇到的 ...

  6. diff/merge configuration in Team Foundation - common Command and Argument values - MSDN Blogs

    One of the extensibility points we have in Team Foundation V1 is that you can configure any other di ...

  7. C# Development 13 Things Every C# Developer Should Know

    https://dzone.com/refcardz/csharp C#Development 13 Things Every C# Developer Should Know Written by ...

  8. EF 5 最佳实践白皮书

    Performance Considerations for Entity Framework 5 By David Obando, Eric Dettinger and others Publish ...

  9. Build Instructions (Windows) – The Chromium Projects

    转自:http://121.199.54.6/wordpress/?p=1156 原始地址:http://www.chromium.org/developers/how-tos/build-instr ...

随机推荐

  1. iOS 中 .a 和 .framework 静态库的创建与 .bundle 资源包的使用

    iOS 中 .a 和 .framework 静态库的创建与 .bundle 资源包的使用 前言 开发中经常使用三方库去实现某特定功能,而这些三方库通常又分为开源库和闭源库.开源库可以直接拿到源码,和自 ...

  2. SSM Spring+SpringMVC+mybatis+maven+mysql环境搭建

    SSM Spring+SpringMVC+mybatis+maven环境搭建 1.首先右键点击项目区空白处,选择new->other..在弹出框中输入maven,选择Maven Project. ...

  3. 一个非常好用的图片切割工具(c# winform开发) 附源码

    本人业余时间开发了一个图片切割工具,非常好用,也很灵活! 特别对大型图片切割,更能体现出该软件的优势! 开发工具为winform,源码下载地址:http://download.csdn.net/dow ...

  4. mysql 打开慢查询日志

    打开mysql的配置文件  my.ini或是my.cnf找到节点[mysqld]下添加下面这两行(默认可能不带这两行,直接手敲即可) [AppleScript] 纯文本查看 复制代码 ? 1 2 3 ...

  5. 可以在手机上看电脑本地html步骤,我自己总结的哦!

    1.打开控制面板 2.打开程序和功能 3.打开或关闭功能 4.internet信息服务展开后里面所有的都要选中 5.回到桌面,然后右键计算机,选择'管理' 6.先在E盘或者D盘创建一个文件夹,自己随意 ...

  6. JavaScript学习笔记(一)数组排序

    数组(Array)在JavaScript中是非常常用的类型,关于数组的排序,与C#等语法中的排序,乍看相似,其实差别比较大. Array的排序方法有两个,分别是reverse()和sort(). re ...

  7. python 初学之账户登录

    要求: 输入用户名密码正确,提示登录成功, 输入三次密码错误,锁定账户. 开始: 使用两个文件: 密码账户文件 文件格式: jason    23456 tom       56789 tang   ...

  8. ArcGIS教程:创建特征

    摘要 创建由输入样本数据和一组栅格波段定义的类的 ASCII 特征文件. 使用方法 · 输出特征文件应使用扩展名 .gsg. · 输入栅格波段和输入栅格或要素样本数据必须具有重叠范围.将仅为公共区域计 ...

  9. Apache HTTPserver安装后报:无法启动,由于应用程序的并行配置不对-(已解决)

    原创作品.出自 "深蓝的blog" 博客.欢迎转载,转载时请务必注明出处.否则有权追究版权法律责任. 深蓝的blog:http://blog.csdn.net/huangyanlo ...

  10. JAVA入门[11]-jsp几点基础语法

    一.include <%@include file="copyright.jsp"%> <jsp:include page="copyright.jsp ...