c# - TryParse dilemma-Dealing with out parameters -
i never liked out
, ref
parameters.when see them in action give me feeling messy design.
i thought exception called tryxxx pattern returns boolean function result (whether fine or went wrong) , out parameter real result, until read this article today , made me think if there's better pattern implement kind of methods.
i thought either have function returns more 1 result(or article says tuple)
tuple<exception,t> tryparset(object obj)
or function accepts callback function success :
void tryparset(object obj,action<t> success)
the question , 1 better functional design point of view ?
update : rephrase question , want know of these 2 functions more complies functional programming principles , why ?
essentially problem follow functional programming approach should provide return value input value. returning void
route isn't way go. need return value can represent success (and hold successful result) , failure (and hold no result).
the closest have returned tuple
includes exception. don't have 'infrastructure' deal tuple
reliably once you've got it. code scaffolding around repeated.
take @ this library language-ext
. deals improving out
problem tryparse
using implementation of option<t>
.
string inp = "123"; // attempts parse value, uses 0 if can't int value1 = parseint(inp).ifnone(0); // functional alternative above // attempts parse value, uses 0 if can't int value2 = ifnone(parseint(inp), 0); // attempts parse value , pattern matches result int value3 = parseint(inp).match( some: x => x * 2, none: () => 0 ); // functional alternative above // attempts parse value , pattern matches result int value4 = match( parseint(inp), some: x => x * 2, none: () => 0 );
the library allows check valid:
if( parseint(inp) ) return 1; else return 0;
and allows comparisons without extracting value:
if( parseint(inp) == 123 ) return 123; else return 0;
as logical operations:
var allvalid = parseint(x) && parseint(y) && parseint(z); var somevalid = parseint(x) || parseint(y) || parseint(z);
and linq expressions can remove need if-then-else or matching:
var res = x in parseint(inp1) y in parseint(inp2) z in parseint(inp3) select x + y + z;
it has trygetvalue
extensions idictionary
, ireadonlydictionary
, iimmutabledictionary
, iimmutableset
instead return option<t>
, can used above.
Comments
Post a Comment