Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a connect method return a value?

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

like image 342
Matt S Avatar asked Jun 08 '10 20:06

Matt S


1 Answers

I would opt for the exception versus the out parameters. If you want consumers of your class to care, make them care with the Exception, or else leave them alone. By using the out parameters, you're simply making their lives more inconvenient if they don't have to care by making them use throwaway variables. Also consider that if your function is already in the wild, you're introducing a breaking change if you change the signature (instead of providing an additional overload).

Programmers expect exceptions in error cases, particularly in languages like C#. We've been trained.

like image 137
Anthony Pegram Avatar answered Sep 30 '22 05:09

Anthony Pegram