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 have only an opinion, so take it for what its worth.
A method named like this, “Connect”, is an order. It’s like giving it to a soldier, “Jump” or “Shoot”. You don’t expect the soldier to report back unless he’s unable to complete the order, and that would be a rare happening.
As such, I have the tendency to not have a return value for such methods, but if there is a chance that under regular usage of the method, there will be failures, then I build a second method, named TryXYZ, returning a bool, and if necessary providing me with the results of whatever XYZ is as out parameters.
This follows the standard set forth by the Parse methods of various numeric types in the .NET BCL.
So in your case, I would probably have:
The nice thing is that if you build the TryConnect method properly, Connect becomes really easy.
Example:
I don’t expect my orders to not complete, but in the sense they might, I want to be explicit about it.