3 ms·
I prefer higher order functional programming, TryGetValue looks ugly to me, I'd rather do... dictionary.WithValue(aKey, value => DoStuffWith(value)); The
by gnaritas 10y ago
I 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.