Why are 'out' parameters in .NET a bad idea?
I was recently asked this, but I had no real answer besides it's simply unnecessarily complicating an application. What other reasons are there?
You should not overuse this feature of course, but it's not a bad idea per definition. Especially not in C# where you have to write down the out keyword in function declaration and call which makes it obvious what's going on.
The out parameter in C# is used to pass arguments to methods by reference. It differs from the ref keyword in that it does not require parameter variables to be initialized before they are passed to a method. The out keyword must be explicitly declared in the method's definition as well as in the calling method.
Variables passed as out arguments do not have to be initialized before being passed in a method call. However, the called method is required to assign a value before the method returns.
Generally speaking, out parameters must be initialized before the called method returns control to the caller.
Well, they aren't a bad idea I think. Dictionary<K, V>
has a TryGetValue
method which is a very good example why out parameters are sometimes a very nice thing to have.
You should not overuse this feature of course, but it's not a bad idea per definition. Especially not in C# where you have to write down the out
keyword in function declaration and call which makes it obvious what's going on.
If you care about writing reliable code by embracing immutability and removing side effects, then out parameters are an absolutely terrible idea. It forces you to create mutable variables just to deal with them. (Not that C# supports readonly method-level variables anyway (at least in the version I'm using, 3.5)).
Secondly, they reduce the compositionality of functions by forcing the developer to set up and deal with the variables which receive the out values. This is annoying ceremony. You can't just go and compose expressions using them with anything resembling ease. Therefore code calling these functions quickly turns into a big imperative mess, providing lots of places for bugs to hide.
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