Should a connect method return a value?

Posted by Matt S on Stack Overflow See other posts from Stack Overflow or by Matt S
Published on 2010-06-08T20:54:40Z Indexed on 2010/06/08 21:12 UTC
Read the original article Hit count: 292

Filed under:
|

I was looking at some code I've inherited and I couldn't decided if I like a bit of code.

Basically, there is a method that looks like the following:

bool Connect(connection parameters){...}

It returns true if it connects successfully, false otherwise.

I've written code like that in the past, but now, when I see this method I don't like it for a number of reasons.

  1. Its easy to write code that just ignores the returned value, or not realize it returns a value.

  2. There is no way to return an error message.

  3. Checking the return of the method doesn't really look nice:

    if (!Connect(...)){....}

I could rewrite code to throw an exception when it doesn't successfully connect, but I don't consider that an exceptional situation. Instead I'm thinking of refactoring the code as follows:

void Connect(Connection Parameters, out bool successful, out string errorMessage){...}

I like that other developers have to provide the success and error strings so they know the method has error conditions and I can know return a message

Anyone have any thoughts on the matter?

Thanks -Matt

© Stack Overflow or respective owner

Related posts about c#

Related posts about coding-style