c# - How to create two sequences without relying on side effects? -
suppose have process sequence of inputtype
produces 2 sequences 1 of type outputtype
, other of type errortype
.
a basic implementation be:
class seqprocessor { private ienumerable<errortype> errortypes; public seqprocessor() { this.errortypes = enumerable.empty<errortype>; } public ienumerable<errortype> errors { { return this.errors; } } public ienumerable<outputtype> processitems(ienumerable<inputtype> inputtypes) { yield return new outputtype(); if (err) this.errortypes = this.errortypes.concat(new errortype()); yield return new outputtype(); yield return new outputtype(); if (err) this.errortypes = this.errortypes.concat(new errortype()); // ... yield break; } }
i see these 2 alternatives example:
use common interface (eg.
iproduct
) betweenoutputtype
,errortype
, letprocessitems
returnienumerable<iproduct>
(than discriminate using linq).define subclass of
errortype
callednoerror
, letprocessitems
return tuplesienumerable<tuple<outputtype, errortype>>
(if no error,noerror
used in tuple).
edit:
since errortype
semantically different outputtype
, mixing these types violation of single responsibility principle. can use of delegate acceptable alternative design:
class seqprocessor { public ienumerable<outputtype> processitems( ienumerable<inputtype> inputtypes, action<errortype> onerror) { yield return new outputtype(); // ... onerror(new errortype()); } }
which approach use in such cases?
depending on want achieve, see multiple possible solutions here:
stay original implementation (where replace
private ienumerable<errortype> errortypes
allows determine item error belongs to). in context, errors encountering have significance of warning (which why prefer namewarning
) because separated actual result.using common interface both result types (that is, output , error) make sense if other functions consuming resulting list make use of error output. doubt intended imho, valid design choice.
as pieter pointed out, having sub-class
noerror
oferrortype
nasty. however, nicer solution usingresulttype
base typesnoerror
,error
. way, have specialization of base class. still, wonder output contain in case of error. original element? processed, invalid element? null? depending on want achieve, could reasonable, hard tell given information and, honest, doubt want.the
onerror
practice in many contexts because allows great flexibility. however, still have think corresponding entry in result in such case. imho, best choice leave out in order avoid treatment of eithernull
or either special values.
all in all, seems onerror
approach seems promising, though additional information may drive towards 1 of other mentioned approaches.
Comments
Post a Comment