c# - Overloaded methods in interface -
my question today: overloaded methods in interface bad? know, "omit parameters if don't care, we'll figure out default values" kind of overloaded methods. that:
void add(object item); void add(object item, bool shoulddosomething); void add(object item, bool shoulddosomething, iultraobscuredevicecontext context);
in case tend think latter belongs interface , others should implemented in abstract class on top of it. again, i'm not sure.
also, there times when want different overloads doing different work (stop me right there if overloaded methods should never used that). or can't stuff nulls in place of parameter, want exception thrown if null. should not use overloading in case?
so i'm looking guidelines on overloaded methods in interfaces vs overloaded methods in abstract classes implementing these interfaces , on. in advance
if defaults depend on receiver of method call, declare them interface methods.
if defaults defaults irrespective of receiver, create various reduced-argument-list overloads extension methods , save implementors headache of having supply overloads themselves.
if you're dealing sort of nitty-gritty 80/20 rule exceptions, implementation-independent defaults almost not quite sufficient, have few options, none of good:
- deal if they're different, declare them interface methods, , reimplement them everywhere. not dry.
- deal if they're different, declare them interface methods, , inherit base class provides 80% default implementation. kind of clumsy, , not if sole base-class slot occupied.
- create interface containing specific methods. declare extension methods matching signature against original interface. in extension methods,
as
-castthis
argument new interface type, , if matches, call there, otherwise fill in stock defaults. funky, reliant on dynamic casting not great in inner loop, decouples defaults both implementor , caller without sacrificing flexibility implementors can't take "default defaults".
Comments
Post a Comment