c# - How to use Composition instead of Inheritance? -


i have configurator class that, in order work, must receive context object via interface:

public class configurator : icontextaware {     private icontext _context;      //property setter defined icontextaware interface     public icontext context { set { _context = value; } }      //  use _context object in other methods here ... } 

i plan write many configurator types, need initalize _context fields same way. first thought "why not anger every programmer on internet , use inheritance"?

public class contextinitializer: icontextaware {     // field hold injected context     protected icontext _context;      //property setter defined icontextaware interface     public icontext context { set { _context = value; } } }  public class configurator : contextinitializer {     //  use _context object here ... } 

this way, other classes write need context object can inherit contextinitializer, , use context object straight away.

pros: guaranteed consistent initialization, no distracting, duplicated initialize code in every class

cons: implementation inheritance evil!,.. um, configurator cannot inherit other class.. ??

i should clarify 1 way or another, configurator must implement icontextaware interface. also, class must have default/no-arg constructor, constructor dependency injection not option here.

can suggest how composition can used achieve same benefits, more flexible design, and/or describe real short-comings of inheritance solution above? thanks!

p.s. adapted spring.net codeconfig, if curious.

i think .net base class library standard answer such questions. use of inheritance would have never been put bcl because exposes user of api api internals. there base class not have semantic meaning. exists save code. public api elements should have purpose , semantic meaning.

the authors of bcl strict when comes api design. have never seen such huge yet pristine collection of types.

that said, don't need adhere same standards if don't need level of api cleanliness. not every api exposed millions of developers. legitimate trade-off compromise on api purity little save lots of code , remove redundancy , potential errors.

my choice: i'd use approach internal code. public apis (think of codeplex libraries , on) i'd rather duplicate redundant stuff , keep public api surface clean.


Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -