4 ms·
> Well written code doesn't use out parameters at all What do you think of the Try pattern, i.e.: Result res; if (TryThing(out res)) { // Do stuff, use
by Nition 10y ago
> Well written code doesn't use out parameters at all
What do you think of the Try pattern, i.e.:
Result res;
if (TryThing(out res)) {
// Do stuff, use res
)
I always thought that was a good use for out, and C# itself uses it for TryGetValue in Dictionaries for instance.
- flukus 10y ago> Wht do you think of the Try pattern I'd call it a valuable exception to the rule.
- krallja 10y agoThis would be a great place for Maybe<Result>
- cobalt 10y agothe purpose of try get was also to avoid boxing of value types
- krallja 10y agoI didn't know that. Couldn't the generic parameter of Some<T> be a nonboxed value type, though? Some<T> could even be a struct, to avoid object allocation. Edit: although that would get boxed so it could fit in a Maybe<T>, so yeah, I see what you're saying!
- gnaritas 10y agoI prefer higher order functional programming, TryGetValue looks ugly to me, I'd rather do... dictionary.WithValue(aKey, value => DoStuffWith(value)); The dictionary knows whether it has a value or not, I shouldn't be making decisions with if's about a dictionaries data when I can just hand some code to the dictionary and let it do the right thing. Your other example. if (TryThing(out res)) { // Do stuff, use res } I'd rather a simple extension to Object enabling this on any value including null... TryThing().IfPresent(thing => thing.DoStuff()); I'm an old Smalltalk'er, we're accustomed to building such control structures into the class library rather than trying to use an if statement for everything. Once you have a clean syntax for lambdas you have the ability to create a better experience than constantly writing procedural code using the common if/while/for/foreach constructs. In Smalltalk we'd do something like... dictionary at: aKey ifPresent: [:value | value doStuff ] That's much better than asking if the key exists with an if, or accessing the dic at a key and doing a null check with an if statement on the value.
- Sacho 10y agoYour suggestions require a continuation to handle the "else" part of the branch. In C# that would look significantly worse than the Try* pattern.
- gnaritas 10y agoThat's a matter of opinion, nothing looks worse to me than those out parameters and there's always a way to do things in a cleaner more expressive way than that ugliness. I find many Smalltalk idioms look and work just fine in C# and greatly reduce the amount of code I need to write. C# still lacks quite a lot in comparison to Smalltalk, but it's slowly getting there year by year.