[ACCEPTED]-Why are 'out' parameters in .NET a bad idea?-.net

Accepted answer
Score: 66

Well, they aren't a bad idea I think. Dictionary<K, V> has 8 a TryGetValue method which is a very good example why 7 out parameters are sometimes a very nice 6 thing to have.

You should not overuse this 5 feature of course, but it's not a bad idea 4 per definition. Especially not in C# where 3 you have to write down the out keyword in function 2 declaration and call which makes it obvious 1 what's going on.

Score: 20

If you care about writing reliable code 15 by embracing immutability and removing side 14 effects, then out parameters are an absolutely 13 terrible idea. It forces you to create mutable 12 variables just to deal with them. (Not that 11 C# supports readonly method-level variables 10 anyway (at least in the version I'm using, 3.5)).

Secondly, they 9 reduce the compositionality of functions 8 by forcing the developer to set up and deal 7 with the variables which receive the out 6 values. This is annoying ceremony. You can't 5 just go and compose expressions using them 4 with anything resembling ease. Therefore 3 code calling these functions quickly turns 2 into a big imperative mess, providing lots 1 of places for bugs to hide.

Score: 15

They are a good idea. Because sometimes 5 you just want to return multiple variables 4 from one method, and you don't want to create 3 a "heavy" class structure for this. The 2 wrapping class structure can hide the way 1 the information flows.

I use this to:

  • Return key and IV data in one call
  • Split a person name, into different entities (first-, middle-, lastname)
  • Split the address
Score: 7

Out - Parameter are a bad idea in my opinion. They 8 increase the risk of side effects and are 7 hard to debug. The only good solution are 6 function results and here is the problem: For 5 function results, you have to create for 4 every complex result a tuple or a new type. Now 3 it should be fairly easy in c#, with anonymous 2 types and generics.

And by the way: I hate 1 side effects too.

Score: 6

The wording of the question is of the "Have you stopped hitting your wife?" variety&mdash;it 18 assumes that out parameters are necessarily 17 a bad idea. There are cases where out parameters 16 can be abused, but…

  • They actually fit very 15 well in the C# language. They are like ref parameters 14 except that the method is guaranteed to 13 assign a value to it and the caller doesn't 12 need to initialize the variable.

  • Normal return 11 values for functions are pushed onto the 10 stack where they are called and exited. When 9 you supply an out parameter, you're giving 8 the method a specific memory address to 7 stick the result in. This also allows for 6 multiple return values, though using a struct 5 often makes more sense.

  • They are wonderful 4 for the TryParse Pattern and also provide 3 metadata for other things like in the case 2 of SQL-CLR where out parameters are mapped 1 to out parameters of a stored procedure signature.

Score: 4

I'd say that your answer is spot on; it's 16 generally unnecessary complication and there's usually 15 a simpler design. The majority of the methods 14 you work with in .NET don't mutate their 13 input parameters, so having a one-off method 12 that utilizes the syntax is a bit confusing. The 11 code becomes a bit less intuitive, and in 10 the case of a poorly documented method, we 9 have no way of knowing what the method does 8 to the input parameter.

Additionally, method 7 signatures with out parameters will trigger 6 a Code Analysis/FxCop violation, if that's 5 a metric you care about. In most cases, there's 4 a better way to accomplish the intent of 3 a method that uses an "out" parameter and 2 the method can be refactored to return the 1 interesting information.

Score: 3

It's not always a bad idea to use out parameters. Usually 13 for the code that tries to create an object 12 based on some form of input it's a good 11 idea to provide a Try method with out parameters 10 and boolean return value, not to force the 9 method consumer to wrap try catch blocks 8 all over, not to mention the better performance. Example:

bool TryGetSomeValue(out SomeValue value, [...]);

this 7 is a case where out parameters are a good 6 ideea.

Another case is where you want to 5 avoid costly large structure passing between 4 methods. For example:

void CreateNullProjectionMatrix(out Matrix matrix);

this version avoids 3 costly struct copying.

But, unless out is 2 needed for a specific reason, it should 1 be avoided.

Score: 3

Well, there is no clear answer for this,but 18 simple use case for out parameter would 17 be Int.TryParse("1",out myInt)

The XXX.TryParse method job is, it converts a value 16 of some type, to another type, it returns 15 to you a boolean flag to indicate the conversion 14 success or failure, which is one part the 13 other part is the converted value, which 12 is carried by the out parameter in that 11 method.

This TryParse method was introduced 10 in .NET 2.0 to get over the fact that XXX.Parse will 9 throw an exception if the conversion fails 8 and you had to put in try/catch around the statement 7 to catch it.

So basically it depends on what 6 your method is doing, and what the method 5 callers are expecting, if you are doing 4 a method that returns some form of response 3 codes, then the out parameters could be use 2 to carry out method returned results.

anyway 1 Microsoft says "Avoid using out parameters", in their design guideline (MSDN page)

Score: 2

I don't think they are. Misusing them is 2 a bad idea, but that goes for any coding 1 practice/technique.

Score: 2

I'd say my reason to avoid it, would be 28 because it is simplest to have a method 27 process data and return one logical piece 26 of data. If it needs to return more data 25 it may be a candidate for further abstraction 24 or formalization of the return value.

One 23 exception is if the data returned is somewhat 22 tertiary, like a nullable bool. It can be 21 true/false or undefined. An out parameter 20 can help solve a similar idea for other 19 logical types.

Another one I use sometimes 18 is when you need to get information through 17 an interface that doesn't allow for the 16 'better' method. Like using .Net data access 15 libraries and ORM for example. When you 14 need to return the updated object graph 13 (after an UPDATE) or new RDBMS-generated 12 identifier (INSERT) plus how many rows were 11 affected by the statement. SQL returns all 10 of that in one statement, so multiple calls 9 to a method won't work as your data layer, library, or 8 ORM only calls one generic INSERT/UPDATE 7 command and can't store values for later 6 retrieval.

Ideal practices like never using 5 dynamic parameter lists, or out parameters, aren't 4 always practical all the time. Again, just 3 think twice if an out parameter is the really 2 right way to do it. If so, go for it. (But 1 make sure to document it well!)

Score: 1

I would say the answer you gave is about 5 the best there is. You should always design 4 away from out parameters if possible, because 3 it usually makes the code needlessly complex.

But 2 this is true of just about any pattern. If 1 there is no need for it, don't use it.

Score: 1

I would have to agree with GateKiller. I 4 can't imagine out parameters being too bad 3 if Microsoft used them as part of the base 2 library. But, as with all things, best 1 in moderation.

Score: 1

It's like the Tanqueray guy likes to say- Everything 10 in moderation.

I definitely would stress 9 against over-use, since it would lead to 8 "writing c in c#" much the same way one 7 can write java in Python (where you're not 6 embracing the patterns and idioms which 5 make the new language special, but instead 4 simply thinking in your old language and 3 converting to new syntax). Still, as always, if 2 it helps your code be more elegant and make 1 more sense, rock out.

Score: 1

the 'out' is great!

It makes a clear statement that 4 the parameter holds a value to be returned 3 by the method.

The compiler also forces you 2 to initialize it (if we are using as a return parameter, it 1 should be initialized).

Score: 1

They just ruin the semantics of a method/function 4 a bit. A method should normally take a bunch 3 of things, and spit out a thing. At least, that's 2 how it is in the minds of most programmers 1 (I would think).

Score: 0

I don't think there is a real reason although 2 I haven't seen it used that often (other 1 than P/Invoke calls).

Score: 0

The out keyword is necessary (see SortedDictionart.TryGetValue). It 4 implies pass by reference and also tells 3 the compiler that the following:

int value;
some_function (out value);

is OK and 2 that some_function isn't using an unitialised value which 1 would normally be an error.

Score: 0

I think in some scenarios they are a good 3 idea because they allow more than 1 object 2 to be returned from a function for example:

DateTime NewDate = new DateTime();
if (DateTime.TryParse(UserInput, out NewDate) == false) {
    NewDate = DateTime.Now;

Very 1 useful :)

Score: 0

Some languages outside of .NET use them as do-nothing 3 macros that simply give the programmer information 2 about how the parameters are being used 1 in the function.

Score: 0

One point I don't see mentioned is that 8 the out keyword also requires the caller 7 to specify out. This is important since 6 it helps to make sure that the caller understands 5 that calling this function will modify his 4 variables.

This is one reason why I never 3 liked using references as out parameters 2 in C++. The caller can easily call a method 1 without knowing his parameter will be modified.

Score: 0

I think the main reason is "...Although 5 return values are commonplace and heavily 4 used, the correct application of out and ref parameters 3 requires intermediate design and coding skills. Library architects who design 2 for a general audience should not expect users to master working with out or ref 1 parameters."

Please read more at: http://msdn.microsoft.com/en-us/library/ms182131.aspx

More Related questions