Derive or Inject

2019-08-08 21:17发布

问题:

Recently I was hacking out some code to communicate with an external web api. The web api is a set of GET/POST operations that return Xml, called in from my application via HttpWebRequest and manipulated on my side using Linq to Xml.

There is are logical groupings of api methods that form multiple services. I have created classes to represent each of these services. Each service has to contact the same base uri and base through the same set of response headers. That is, there are a series methods that are shared between all of my service classes. I performed an Extract Method to Superclass refactoring on these common methods and inherited all my service classes form the new super class. All the methods involved in the refactoring deal with configuring the underlying connection to the remote api and dealing with the raw data coming back, such as deserializing the xml into POCO's.

I've just been asked why I'm using inheritance to use methods from the base class instead of injecting it in. Frankly I've got no real good answer so I want to understand why this question was asked and what are the merits of injection over inheritance. I'm aware that basic OO design tenets say we should favour composition over inheritance, and I can see how to refactor for compoosition, but I'm unsure what advantages this would gain me.

My colleague has said "not only is it more testable... well it's easier to test". I can see his argument but I'd like to know more. Hopefully I've given enough info to get a sensible response.

回答1:

It Depends :)

If your child classes provide speicialisation over the base class then this favours inheritance while if the base class provides more of a utility function then i would go with composition.

If you child classes are just adapting the POCO's to the needed format for the web calls then inheritance could be the way to go, but as with most things software development the cat can be skinned many ways.

Injecting it in allows you to test the injected code in isolation, rather than with inheritance where you would need to sub-class to test just the common code.

Hope i've been able to help



标签: c# oop