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.
Its easy to write code that just ignores the returned value, or not realize it returns a value.
There is no way to return an error message.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With