使用断言或异常按合同进行设计? [英] Design by contract using assertions or exceptions?

查看:28
本文介绍了使用断言或异常按合同进行设计?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当通过契约编程一个函数或方法时,首先检查它的先决条件是否满足,然后再开始处理它的职责,对吗?进行这些检查的两种最突出的方法是通过 assert 和通过 exception.

When programming by contract a function or method first checks whether its preconditions are fulfilled, before starting to work on its responsibilities, right? The two most prominent ways to do these checks are by assert and by exception.

  1. assert 仅在调试模式下失败.确保(单元)测试所有单独的合同先决条件以查看它们是否真的失败至关重要.
  2. 异常在调试和发布模式下失败.这样做的好处是经过测试的调试行为与发布行为相同,但会导致运行时性能下降.

你认为哪个更好?

查看相关问题这里

推荐答案

在发布版本中禁用断言就像说我在发布版本中永远不会遇到任何问题",但通常情况并非如此.因此,不应在发布版本中禁用断言.但是您也不希望发布版本在发生错误时崩溃,对吗?

Disabling assert in release builds is like saying "I will never have any issues whatsoever in a release build", which is often not the case. So assert shouldn't be disabled in a release build. But you don't want the release build crashing whenever errors occur either, do you?

所以使用异常并用好它们.使用良好的、可靠的异常层次结构并确保您捕获并且您可以在调试器中将异常抛出挂钩以捕获它,并且在发布模式下您可以补偿错误而不是直接崩溃.这是更安全的方式.

So use exceptions and use them well. Use a good, solid exception hierarchy and ensure that you catch and you can put a hook on exception throwing in your debugger to catch it, and in release mode you can compensate for the error rather than a straight-up crash. It's the safer way to go.

这篇关于使用断言或异常按合同进行设计?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆