Clean Code–Chapter 7 Error Handling

时间:2021-09-30 21:56:40

Error handling is important, but if it obscures logic, it's wrong.

Use Exceptions Rather Than Return Codes

Separate the normal operations with error handlings.

e.g.

Bad code:

public class DeviceController {
...
public void sendShutDown() {
DeviceHandle handle = getHandle(DEV1);
// Check the state of the device
if (handle != DeviceHandle.INVALID) {
// Save the device status to the record field
retrieveDeviceRecord(handle);
// If not suspended, shut down
if (record.getStatus() != DEVICE_SUSPENDED) {
pauseDevice(handle);
clearDeviceWorkQueue(handle);
closeDevice(handle);
} else {
logger.log("Device suspended. Unable to shut down");
}
} else {
logger.log("Invalid handle for: " + DEV1.toString());
}
}
...
}

Good code:

public class DeviceController {
...
public void sendShutDown() {
try {
tryToShutDown();
} catch (DeviceShutDownError e) {
logger.log(e);
}
}
private void tryToShutDown() throws DeviceShutDownError {
DeviceHandle handle = getHandle(DEV1);
DeviceRecord record = retrieveDeviceRecord(handle);
pauseDevice(handle);
clearDeviceWorkQueue(handle);
closeDevice(handle);
}
private DeviceHandle getHandle(DeviceID id) {
...
throw new DeviceShutDownError("Invalid handle for: " + id.toString());
...
}
...
}

Write Your Try-Catch-Finally Statement First

It is good practice to start with a try-catch-finally statement when you are writing code that could throw exceptions.

(本节中有关单元测试的讲解,没看明白,留待以后回顾再看。)

Use Unchecked Exceptions

Checked exceptions is an Open/Closed Principle violation.

(C# doesn't have checked exceptions.)

Provide Context with Exceptions

To determine the source and location of an error.

Mention the operation that failed and the type of failure.

Define Exception Classes In terms of a Caller's Needs

Most important concern: how they are caught.

In most exception handling situations, the work that we do is relatively standard regardless of the actual cause. So we can simplify our code considerably by wrapping the third-party APIs.

e.g.

Bad code:

ACMEPort port = new ACMEPort(12);
try {
port.open();
} catch (DeviceResponseException e) {
reportPortError(e);
logger.log("Device response exception", e);
} catch (ATM1212UnlockedException e) {
reportPortError(e);
logger.log("Unlock exception", e);
} catch (GMXError e) {
reportPortError(e);
logger.log("Device response exception");
}
finally {

}

Good code:

LocalPort port = new LocalPort(12);
try {
port.open();
}
catch (PortDeviceFailure e) {
reportError(e);
logger.log(e.getMessage(), e);
}
finally {

} public class LocalPort {
private ACMEPort innerPort;
public LocalPort(int portNumber) {
innerPort = new ACMEPort(portNumber);
}
public void open() {
try {
innerPort.open();
} catch (DeviceResponseException e) {
throw new PortDeviceFailure(e);
} catch (ATM1212UnlockedException e) {
throw new PortDeviceFailure(e);
} catch (GMXError e) {
throw new PortDeviceFailure(e);
}
}

}

Define the Normal Flow

Use the Special Case Pattern. Create a class or configure an object so that it handles a special case for you. When you do, the client code doesn't have to deal with exceptional behavior. That behavior is encapsulated in the special case object.

Don't Return Null

When we return null, we are essentially creating work for ourselves and foisting problems upon our callers.

If you are tempted to return null from a method, consider throwing an exception or returning a special case object instead. If you are calling a null-returning method from a third-party API, consider wrapping that method with a method that either throws an exception or returns a special case object.

e.g.

Bad code:

List<Employee> employees = getEmployees();
if (employees != null) {
for(Employee e : employees) {
totalPay += e.getPay();
}
}

Good code:

List<Employee> employees = getEmployees();
for(Employee e : employees) {
totalPay += e.getPay();
} public List<Employee> getEmployees() {
if( .. there are no employees .. )
return Collections.emptyList();
}

Don't Pass Null

Conclusion

We can write robust clean code if we see error handling as a separate concern, something that is viewable independently of our main logic. To the degree that we are able to do that, we can reason about it independently, and we can make great strides in the maintainability of our code.

Clean Code–Chapter 7 Error Handling的更多相关文章

  1. Clean Code &ndash&semi; Chapter 3&colon; Functions

    Small Blocks and Indenting The blocks within if statements, else statements, while statements, and s ...

  2. Clean Code – Chapter 4&colon; Comments

    “Don’t comment bad code—rewrite it.”——Brian W.Kernighan and P.J.Plaugher The proper use of comments ...

  3. TIJ——Chapter Twelve&colon;Error Handling with Exception

    Exception guidelines Use exceptions to: Handle problems at the appropriate level.(Avoid catching exc ...

  4. Clean Code &ndash&semi; Chapter 2&colon; Meaningful Names

    Use Intention-Revealing Names The name should tell you why it exists, what it does, and how it is us ...

  5. Clean Code &ndash&semi; Chapter 6 Objects and Data Structures

    Data Abstraction Hiding implementation Data/Object Anti-Symmetry Objects hide their data behind abst ...

  6. Clean Code – Chapter 5 Formatting

    The Purpose of Formatting Code formatting is about communication, and communication is the professio ...

  7. setjmp&lpar;&rpar;、longjmp&lpar;&rpar; Linux Exception Handling&sol;Error Handling、no-local goto

    目录 . 应用场景 . Use Case Code Analysis . 和setjmp.longjmp有关的glibc and eglibc 2.5, 2.7, 2.13 - Buffer Over ...

  8. Erlang error handling

    Erlang error handling Contents Preface try-catch Process link Erlang-way error handling OTP supervis ...

  9. Error Handling

    Use Exceptions Rather Than Return Codes Back in the distant past there were many languages that didn ...

随机推荐

  1. SQL Server调优系列玩转篇(如何利用查询提示(Hint)引导语句运行)

    前言 前面几篇我们分析了关于SQL Server关于性能调优的一系列内容,我把它分为两个模块. 第一个模块注重基础内容的掌握,共分7篇文章完成,内容涵盖一系列基础运算算法,详细分析了如何查看执行计划. ...

  2. 传智168期JavaEE就业班 day05-XML 约束与解析

    * 课程回顾: * DOM解析HTML简介 * DOM 文档对象模型 * 解析器 * document对象 * getElementById("id的值"); 返回一个元素(标签) ...

  3. SQL Server中追踪器Trace的介绍和简单使用

    一.What is Trace? 对于SQL Profiler这个工具相信大家都不是很陌生,没用过的朋友可以在SQL Server Management Studio>工具>SQL Ser ...

  4. c&plus;&plus;异常 连续抛出异常

      今天天遇到这样一个问题,连续两次抛出异常,但是只有一个catch,会导致core这个时候会导致core, 单线程编程中可能很少遇到这样的问题,但是多线程中是很容易遇到的, 举个例子:catch代码 ...

  5. C&plus;&plus;函数学习笔记

    C++继承了C语言的全部语法,也包括函数的定义和使用方法. 调用其他函数的函数因为位高权重被尊称为主调函数,被其他函数调用的函数称为被调函数. 函数的返回值由return语句给出,return 表达式 ...

  6. jQuery实例—选项卡(js源码和jQuery)【一些常见方法(1)-练习】

    分别利用javascript的源码和jQuery来实现一个简单的选项卡,对比各自的步骤. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Tr ...

  7. 【Java基础】【19异常&amp&semi;IO&lpar;File类&rpar;】

    19.01_异常(异常的概述和分类) A:异常的概述 异常就是Java程序在运行过程中出现的错误. B:异常的分类 通过API查看Throwable Error 服务器宕机,数据库崩溃等 Except ...

  8. C&num;&sol;&period;NET 使用官方驱动操作MongoDB(一):插入、查询

    概述 想要在C#中使用MongoDB,首先得要有个MongoDB支持的C#版的驱动. C#版的驱动有很多,这里我们先用官方提供的 MongoDB.Driver(使用 Nuget 安装),当前版本为2. ...

  9. centos7以rpm方法装mysql5&period;7及大坑

    环境: CentOS Linux release 7.5.1804 (Core)   Mysql版本: MySQL-5.7.17-1.el6.x86_64.rpm-bundle.tar   下载地址( ...

  10. AndroidStudio 代码(导入类)报错但可正常运行,以及解决此问题后带来的系列问题解决

    首先是应用中很多导入的类都报红色异常显示找不到此类,但运行编译正常: 第一种方法: 点击AndroidStudio菜单File -> Invalidate Caches/Restar… ,在弹出 ...