Error-checking idioms

Started by
5 comments, last by jflanglois 17 years, 6 months ago
Which do you guys prefer:
void Example( const string& someString, const Resource* someResource )
{
	if( !someString.empty() && someResource )
	{
		DoSomething();
	}
	else if( someString.empty() )
	{
		StringError();
	}
	else if( !someResource )
	{
		ResourceError();
	}
}

OR
void Example( const string& someString, const Resource* someResource )
{
	if( someString.empty() )
	{
		StringError();
		return;
	}
	if( !someResource )
	{
		ResourceError();
		return;
	}
	DoSomething();
}

Or something else?
Advertisement
void Example( arguments ){  assert(state-constraint);  if (invalid-argument) throw InvalidArgumentException();  if (invalid-operation) throw InvalidOperationException();  DoSomething();  if (invalid-state) throw AdHocException();  DoSomethingElse();  assert(post-condition);}


Edit: C++ified

[Edited by - ToohrVyk on October 1, 2006 12:32:23 PM]
Quote:Original post by ToohrVyk
*** Source Snippet Removed ***

You're not doing that in C++, are you? You probably shouldn't be dynamically allocating the exception like that.
Nope, C#, but the same structure applies to C++ and other languages as well.
Quote:Original post by ToohrVyk
Nope, C#, but the same structure applies to C++ and other languages as well.

The structure applies, but I really do think your example should be in one language or the other.
Quote:Original post by jflanglois
The structure applies, but I really do think your example should be in one language or the other.


Yah, having C# and pseudo-code mixed when my original question was in C++ is a bit weird. But he's essentially selected the second example, as far as I can see.

What about you, jflanglois. Anything to contribute?
Quote:Original post by Jaymar
Quote:Original post by jflanglois
The structure applies, but I really do think your example should be in one language or the other.


Yah, having C# and pseudo-code mixed when my original question was in C++ is a bit weird. But he's essentially selected the second example, as far as I can see.

What about you, jflanglois. Anything to contribute?

Even though I was nitpicky with his example, I actually agree with what ToohrVyk posted. To generalize, though, I would say that you should organize your sanity checking code in the least obtrusive way possible. So for example, in your first piece of code, you essentially repeat your conditions twice. If you check that someString is empty and that someResource is non-null before you do anything with them, then you can assume that ( !someString.empty() && someResource ) is true. The reverse is not true, however. What if you wanted to add another failure condition? Do you want to update that first if statement as well?

This topic is closed to new replies.

Advertisement