Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable Declaration Versus Error Checking: Which Comes First?

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;

}
like image 931
rkg Avatar asked Mar 08 '26 22:03

rkg


2 Answers

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.

like image 186
paxdiablo Avatar answered Mar 11 '26 13:03

paxdiablo


Declare variables when you need them, that's usually when some intermediate result is ready or when you're just about to enter a loop.

So this does imply that error checks will often come before declarations.

like image 33
djna Avatar answered Mar 11 '26 15:03

djna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!