Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using "out" bad practice

I have just added an out bool parameter to a method I've written in order to get a warning in to my UI. I've used an out rather than getting the method itself to return false/true as that would imply the DoSomething failed/succeeded. My thinking was that the warnUser would indicate what the warning actually was without having to look at the implementation of the method.

Original Code

public void DoSomething(int id, string input);

New Code

public void DoSomething(int id, string input, out bool warnUser);

I'm using Moq to test this code, but it doesn't support out/ref parameters because they're not supported by Lambda expressions

Test Code

mockService.Verify(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<bool>());

So, is using out parameters bad practise and if so what do I do instead?

like image 469
Antony Scott Avatar asked Nov 23 '10 10:11

Antony Scott


1 Answers

Using an out parameter in a void method is generally a bad idea. You say you've used it "rather than getting the method itself to return false/true as that would imply the DoSomething failed/succeeded" - I don't believe that implication is there. Usually in .NET failure is indicated via an exception rather than true/false.

out parameters are generally uglier to use than return values - in particular, you have to have a variable of the right type to handle, so you can't just write:

if (DoSomething(...))
{
   // Warn user here
}

One alternative you might want to consider is an enum indicating the warning level required. For example:

public enum WarningLevel
{
    NoWarningRequired,
    WarnUser
}

Then the method could return a WarningLevel instead of bool. That would make it clearer what you meant - although you might want to rename things slightly. (It's hard to give advice with metasyntactic names such as "DoSomething" although I entirely understand why you've used that here.)

Of course, another alternative is that you might want more information to be present - like the reason for the warning. That could be done with an enum, or you might want to give some richer result entirely.

like image 170
Jon Skeet Avatar answered Sep 24 '22 19:09

Jon Skeet