我应该在我的 PHP 代码中使用断言吗? [英] Should I be using assert in my PHP code?

查看:46
本文介绍了我应该在我的 PHP 代码中使用断言吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一位同事在我们的库中多次添加了 assert 命令,在这些地方我会使用 if 语句并抛出异常.(在此之前我什至从未听说过 assert.)以下是他如何使用它的示例:

A coworker has added the assert command a few times within our libraries in places where I would have used an if statement and thrown an exception. (I had never even heard of assert before this.) Here is an example of how he used it:

assert('isset($this->records); /* Records must be set before this is called. */');

我会这样做:

if (!isset($this->records)) {
    throw new Exception('Records must be set before this is called');
}

从阅读 关于 assert 的 PHP 文档 来看,似乎建议您确保 assert 处于活动状态并在使用 assert 之前添加处理程序.我找不到他这样做的地方.

From reading the PHP docs on assert, it looks like it's recommended that you make sure assert is active and add a handler before using assert. I can't find a place where he's done this.

所以,我的问题是,鉴于上述情况,使用断言是一个好主意,我应该更频繁地使用它而不是 if 和异常吗?

So, my question is, is using assert a good idea given the above and should I be using it more often instead of if's and exceptions?

另一个说明,我们计划在各种项目和服务器上使用这些库,包括我们甚至可能不参与的项目(这些库是开源的).这对使用 assert 有什么影响吗?

Another note, we are planning to use these libraries on a variety of projects and servers, including projects that we may not even be part of (the libraries are open source). Does this make any difference in using assert?

推荐答案

适用于大多数语言的经验法则(所有我模糊知道的)是使用 assert 来断言条件总是为真,而if是合适的,如果可以想象它有时会失败.

The rule of thumb which is applicable across most languages (all that I vaguely know) is that an assert is used to assert that a condition is always true whereas an if is appropriate if it is conceivable that it will sometimes fail.

在这种情况下,我会说 assert 是合适的(基于我对情况的薄弱理解),因为 records 应该总是在调用给定方法之前设置.因此,未能设置记录将是程序中的错误而不是运行时条件.在这里,assert 有助于确保(通过充分的测试)没有可能的程序执行路径导致被 assert 保护的代码被调用没有设置记录.

In this case, I would say that assert is appropriate (based on my weak understanding of the situation) because records should always be set before the given method is called. So a failure to set the record would be a bug in the program rather than a runtime condition. Here, the assert is helping to ensure (with adequate testing) that there is no possible program execution path that could cause the code that is being guarded with the assert to be called without records having been set.

使用assert 相对于if 的优点是assert 通常可以在生产代码中关闭,从而减少开销.可以想象,最好使用 if 处理的情况可能会在生产系统的运行时发生,因此无法关闭它们不会有任何损失.

The advantage of using assert as opposed to if is that assert can generally be turned off in production code thus reducing overhead. The sort of situations that are best handled with if could conceivably occur during runtime in production system and so nothing is lost by not being able to turn them off.

这篇关于我应该在我的 PHP 代码中使用断言吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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