变量声明与错误检查:哪个来了? [英] Variable Declaration Versus Error Checking: Which Comes First?

查看:139
本文介绍了变量声明与错误检查:哪个来了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写函数时,我总是有这种混淆,首先是检查错误,然后再声明变量(或)将参数分配给局部变量,然后检查错误。以下哪种方式是首选,为什么?我通常坚持第一个类型。

  void DoSomething1(Object x,Object y){

//所有类型的错误检查在这里
如果IsError(x)返回;
如果IsError(y)返回;

//变量声明
int i,j;
对象z = x;
}


void DoSomething2(Object x,Object y){

//变量声明
int i,j;
对象z = x;

//所有类型的错误检查都在这里
如果IsError(z)返回;
如果IsError(y)返回;

}


解决方案

遵循接近规则,并尽可能将变量声明为。这使他们的创作和使用的地方。您也应该在最早的机会之间检查参数的有效性,以尽量减少所执行的工作。



因此,我同意您的第一个更好,但它是主观的。可能有其他方法可能有争议,但我还没有听到有说服力的人,所以我认为这两个指导方针是最佳实践。



由于你声明语言不可知论,尽管你的代码看起来有点奇怪的事实:-),几乎肯定有一些语言,你没有得到一个选择,变量必须在顶部被声明。


When writing a function I always have this confusion whether to check for errors first and declare the variables later (or) assign the parameters to local variables and then check for errors. Which of the following way is preferred and why? I usually stick to the first type.

void DoSomething1(Object x, Object y){

  // All sort of error checking goes here
  if IsError(x) return;
  if IsError(y) return;

  // Variable declaration
  int i,j;
  Object z = x;
}


void DoSomething2(Object x, Object y){

  // Variable declaration
  int i,j;
  Object z = x;

  // All sort of error checking goes here
  if IsError(z) return;
  if IsError(y) return;

}

解决方案

You should follow a proximity rule and declare the variables as late as possible. This localises their creation and use. You should also check parameters for validity at the earliest possible opportunity to minimise the work performed.

Hence I agree that your first one is better but it is subjective. There's possibly arguments for the other approach but I've yet to hear convincing ones, so I consider those two guidelines as best practice.

Since you state "language agnostic" despite the fact your code looks somehow strangely familiar :-), there are almost certainly some languages where you don't get a choice and variables have to be declared at the top.

这篇关于变量声明与错误检查:哪个来了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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