测试indexOf返回值的最佳实践 [英] Best practice for testing return value of indexOf

查看:587
本文介绍了测试indexOf返回值的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您测试indexOf的返回值时,您通常会写什么?

What do you normally write when you're testing for the return value of indexOf?

if str.indexOf("a") < 0 

vs

if str.indexOf("a") == -1

一种方法比其他人更受欢迎?

Would one method be preferred over the other?

我实际上是针对任何语言中出现错误时返回-1的任何函数提出此问题。

I'm actually posing this question for any function in any language that returns -1 on error.

我通常更喜欢< 0方法,因为如果函数扩展为在某些其他情况下返回-2,代码仍然可以工作。

I normally prefer the < 0 approach, because if the function is extended to return -2 on some other case, the code would still work.

但是,我注意到== -1方法更常用。有原因吗?

However, I notice that the == -1 approach is more commonly used. Is there a reason why?

推荐答案

我尝试实施一般原则,即错误条件的测试应该与可能。因此我会使用< 0 而不是 == -1

I try to implement the general principle that tests for "error conditions" should be as wide as possible. Hence I would use < 0 rather than == -1.

这是我被教导的原则在我获得CS学位期间的正式方法课程中。

This is a principle I was taught during classes in formal methods during my CS degree.

在一个简单的上如果它并不重要,但是在循环中,检测任何超出范围条件以确保循环终止是重要的,并且不要假设循环终止值将被精确命中。

On a simple if it doesn't matter too much, but on loops it's important to detect any "out of range" condition to ensure that the loop is terminated, and not to assume that the loop termination value will be hit exactly.

以此为例:

i = 0;
while (i < 10) {
    ++i;
    // something else increments i
}

vs

i = 0;
while (i != 10) {
    ++i;
    // something else increments i
}

后一种情况可能会失败 - 前一种情况不会。

The latter case could fail - the former case won't.

这篇关于测试indexOf返回值的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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