Reputation: 5719
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;
}
Upvotes: 3
Views: 251
Reputation: 882266
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.
Upvotes: 7
Reputation: 55937
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.
Upvotes: 1