Derive or Inject - c#

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.

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

Related

Polymorphism in hierarchy with serialised classes - DataContract messages

Diagram below depicts how
producer creates new messages/requests filling data members,
messages are serialized,
sent to consumer,
dserialized,
Consumer invokes virtual function - uses polymorphic behavior of base class reference.
This article discusses a similar question.
But I need to separate DTO (in DataContract.DLL) and some implementation (App.EXE) linked to this DTO within the same class hierarchy (I try to avoid introducing another family of classes like RequestProcessors).
Implementation should be overridden in a different assembly than dll with definition of DTO/message - this dll should be lightweight - used by different teams. Therefore I can't refer to derived class in attribute [KnownType(typeof(SomeData))] like in mentioned article. I don't want to include method implementation in DataContract.DLL.
How to implement polymorphism in hierarchy with serialised classes (DataContract messages) where DataContracts and implementation are separated in different assemblies? Is it possible?
I didn't find the way but C# is not my primary language. I see that producer should not depend on Consumer.EXE but should create most derived class. So, all classes should be introduced in DataContracts.DLL. Partial class definition likely are not cross assembly.
Maybe multiple file assembly will work? Maybe extension method are closest approximation.
Updated (quotation from article):
DTOs that are decorated as DataContract classes are real objects. They can have methods in them, but the methods are not part of the serialization process
How to implement polymorphism in hierarchy with serialised classes (DataContract messages)
"Polymorphic data contract " is an oxymoron.
Data contracts are DTOs (Data Transfer Objects) implementation for WCF.
WCF clearly separates data (data contracts, DTOs) from behavior (services).
Do not mix them.
In other words:
don't try to implement polymorphism in DTO hierarchy;
do not add any behavior to DTOs.
I try to avoid introducing another family of classes like RequestProcessors
But you shouldn't!
This is natural approach for service-based solutions, and this is not about WCF (SOAP) only. E.g., REST (ASP .NET Web API in case of .NET) does the same.
Moreover, service-based way suits well for business-logic implementation inside applications, because it perfectly fits Dependency Injection containers.
Do implement some IRequestProcessor hierarchy - this is the right way to go.
Note, that linked question is about inheritance, but it is not about behavior inheritance. IMO, term "polymorphism" is misused there. You can (and often should) derive one data contract from another, but you can (should) derive data, not behavior.

Polymorphic SERVICES with WCF

I am trying to hold to the DRY principle in developing WCF services for our application, but I seem to be going down a lot of rabbit holes. My original idea was to have an abstract base class to hold code common to all services, and have derived classes for each concrete service, but cannot seem to get VS2012 to play nice.
Whenever you create a service class, it INSISTS on putting the contract (interface) and implementation classes in the same project, and trying to pull those apart seems to hose up the wiring that VS has done under the hood, so then things break.
I guess all my years of "classic" OO design are getting in the way, I wanted to have the concrete services derive from the interface class AND the abstract base class, but I'm not having a lot of luck. I have found questions/blogs on having polymorphic DATA types used by services, but have not found examples of polymorphic SERVICE types. Can anyone point me?
Thanks,
Peter
UPDATE: Perhaps I am over-thinking the whole thing, I am actually NOT trying to have inheritance for OPERATIONS since a composite approach would make more sense, I just want to keep common code in one place (obviously...), and the whole "static helper class" approach always feels "dirty" to me, kind of defeating the whole OO approach...I am hoping I can simply have the contrete service classes inherit from an abstract base class that is NOT necessarily the implementation of any particular service contract, but is just a way to keep the code DRY...
ALSO: I am trying to use the Template pattern for the service classes, since the overall structure of the services is so similar (devil is always in the details...)
You can separate the interface classes and implementation classes into different projects. One easy way to do is to create the projects manually and write/copy the code as you would for any .NET OO solution.
The following is a set of samples provided by Microsoft...
http://www.microsoft.com/en-us/download/details.aspx?id=21459
You should be able to dig into the samples and find one that meets your requirement.

How should i refactor this?

so in my application I've got several different customers being "serviced". Each customer has their own implementations of various classes that are all based on interfaces.
With the latest customer being added, I've noticed there will be a lot of duplication of code from another customer but the other customer is in no other way related to them.
I've already got a default implementation for several other customers and roll new ones as i need them.
My question is how do i refactor this and still keep the code clean? If i were a dev new to this code base i would want each customer to either use the default or their own implementation of these classes... but that's a lot of duplication.
Consider using an abstract base class with abstract or virtual members. Abstract members are essentially equivalent to interface members (they have no build-in behavior, they only guarantee the method exists) whereas virtual members have a default implementation which can be overridden by derived classes.
Your question is really too vague to answer in full, but here's how you can leverage inheritance.
If you want all classes to use the same implementation of a member then that member can be implemented in the base-class.
If you want each class to have its own implementation of a member then you can either use a base-class with abstract members, or an interface.
If you want some classes to use the same implementations and others to use different implementations then implementing the default behavior in the base-class and override it as needed.
My main point is that OOP there is a spectrum of how much or little functionality is in base/abstract/concrete classes. There's no silver-bullet answer, sometimes your base classes will be skeletons and sometimes they'll be fully fleshed-out; it all depends on the specific problem at hand.
Is there some way that you could create a base class, then a specific implementation for each customer and then using some type of Dependency Injection have that load classes or functionality as needed. You want to really have a DRY system so as to avoid headaches and typos or other similar human mistakes.
You may use either inheritance (put common logic to the base class) or aggregation (spread that logic among other classes and make use them from your customers).
I'd recommend the visitor pattern:
http://en.m.wikipedia.org/wiki/Visitor_pattern
As well as the mediator pattern:
http://en.m.wikipedia.org/wiki/Mediator_pattern
Reason being that it sounds like you may benefit from decoupling, or at least more-loose-coupling, the business logic from your classes, based on what you are saying.
It's a bit difficult to know what to suggest without a better understanding of the code... but some things that have worked for me in similar situations include:
Use a Strategy, for the duplicated code. I've had most success where the strategy is encapsulated within a class implementing a known interface (one class per alternate strategy). Often in such cases I use some form of Dependency Injection framework (typically StructureMap) to pass the appropriate strategy/strategies to the class.
Use some sort of template class (or template methods) for the common item(s).
Use a Decorator to add specific functionality to some basic customer.
STW suggested that I should offer some clarification on what I mean by "Strategy" and how that differs from normal inheritance. I imagine inheritance is something you are very familiar with - something (typically a method - either abstract or virtual) in the base class is replaced by an alternate implementation in the derived class.
A strategy (at least the way I typically use it) is normally implemented by a completely different class. Often all that class will contain is the implementation for a single replaceable operation. For example if the "operation" is to perform some validation, you may have a NullValidationStrategy which does nothing and a ParanoidValidationStrategy which makes sure every McGuffin is the correct height, width and specific shade of blue. The reason I usually implement each strategy in its own class is because I try and follow the Single Responsibility Principle which can make it easier to reuse the code later.
As I mentioned above, I typically use a Dependency Injection (DI) framework to "inject" the appropriate strategy via the class constructor, but a similar results may be obtained via other mechanisms - e.g. having a SetSomeOperationStrategy(ISomeOperation StrategyToUse) method, or a property which holds the strategy reference. If you aren't using DI, and the strategy will always be the same for a given customer type, you could always set the correct choices when the class is constructed. If the strategy won't be the same for each instance of a given customer type, then you probably need some sort of customer factory (often a factory method will be sufficient).
I'd go with the answer of spinon (got my vote at least), but it's to short so let me elaborate:
Use your interfaces for the default implementation and then use dependency injection. Most tools allow you to define a scope or some criteria how to resolve something.
I assume that you do know the client at some early point of the program. So for ninject you just might want to define a "Module" for each client and load that into the kernel, depending on the client.
So I'd create a "no customization" Module and create a "ClientX" Module for every special case that uses ´Bind.To()` instead.
You end up with
a base implementation that is clean/default
a single place change for a new client (got a new one? Great. Either it works with the default or just needs a single Module that maps the interfaces to other classes)
The rest of the code shouldn't mind and get the dependencies via injection (constructor, property, whatever is easiest to go for. Constructor would probably be the nicest way) and has no special treatment at all.
You could even use a conditional binding in Ninject link text to solve the binding issue without different modules at all (although, depending on the number of clients, this might get messy and should better be separated).
I was going to suggest aggregation, as #the_joric suggests, over inheritance, but your description makes it sound like your application is already reasonably well-factored - that there aren't a lot of small classes waiting to be extracted from your existing classes. Assuming that's the case, for any given interface, if you have a perfect class for the new customer already written and ready to go, I would say go ahead and use it. If you're worried about that, for some reason, then take that perfect class, make it abstract, and create empty subclasses for your existing customer and your new customer - and if it's not quite a perfect fit, then that's the way I would go.

c# when to program to an interface?

Ok the great thing about programming to an interface is that it allows you to interchange specific classes as long as the new classes implement everything in that interface.
e.g. i program my dataSource object to an interface so i can change it between an xml reader and a sql database reader.
does this mean ideally every class should be programmed to an interface?
when is it not a good idea to use an interface?
When the YAGNI principle applies.
Interfaces are great but it's up to you to decide when the extra time it takes developing one is going to pay off. I've used interfaces plenty of times but there are far more situations where they are completely unnecessary.
Not every class needs to be flexibly interchanged with some other class. Your system design should identify the points where modules might be interchangeable, and use interfaces accordingly. It would be silly to pair every class with an additional interface file if there's no chance of that class ever being part of some functional group.
Every interface you add to your project adds complexity to the codebase. When you deal with interfaces, discoverability of how the program works is harder, because it's not always clear which IComponent is filling in for the job when consumer code is dealing with the interface explicitly.
IMHO, you should try to use interfaces a lot. It's easier to be wrong by not using an interface than by using it.
My main argument on this is because interfaces help you make a more testable code. If a class constructor or a method has a concrete class as a parameter, it is harder (specially in c#, where no free mocking frameworks allow mocking non-virtual methods of concrete classes) for you to make your tests that are REAL unit tests.
I believe that if you have a DTO-like object, than it's overkill to use an interface, once mocking it may be maybe even harder than creating one.
If you're not testing, using dependency injection, inversion of control; and expect never to do any of these (please, avoid being there hehe), then I'd suggest interfaces to be used whenever you will really need to have different implementations, or you want to limit the visibility one class has over another.
Use an interface when you expect to need different behaviours used in the same context. I.e. if your system needs one customer class which is well defined, you probably don't need to use an ICustomer interface. But if you expect a class to comply to a certain behaviour s.a. "object can be saved" which applies to different knids of objects then you shoudl have the class implement an ISavable interface.
Another good reason to use an interface is if you expect different implementations of one kind of object. For example if ypu plan an SMS-Gateway which will route SMS's through several different third-party services, your classes should probably implent a common interface s.a. ISmsGatewayAdapter so your core system is independent from the specific implementation you use.
This also leads to 'dependecy injection' which is a technique to further decouple your classes and which is best implemented by using interfaces
The real question is: what does your class DO? If you're writing a class that actually implements an interface somewhere in the .NET framework, declare it as such! Almost all simple library classes will fit that description.
If, instead, you're writing an esoteric class used only in your application and that cannot possibly take any other form, then it makes no sense to talk about what interfaces it implements.
Starting from the premise of, "should I be implementing an interface?" is flawed. You neither should be nor shouldn't be. You should simply be writing the classes you need, and declaring what they do as you go, including what interfaces they implement.
I prefer to code as much as possible against an interface. I like it because I can use a tool like StructureMap to say "hey...get me an instance of IWidget" and it does the work for me. But by using a tool like this I can programatically or by configuration specify which instance is retrieved. This means that when I am testing I can load up a mock object that conforms to an interface, in my development environment I can load up a special local cache, when I am in production I can load up a caching farm layer, etc. Programming against an interface provides me a lot more power than not programming against an interface. Better to have and not need than need and not have applies here very well. And if you are into SOLID programming the easiest way to achieve many of those principles sort of begins by programming against an interface.
As a general rule of thumb, I think you're better off overusing interfaces a bit than underusing them a bit. Err on the side of interface use.
Otherwise, YAGNI applies.
If you are using Visual Studio, it takes about two seconds to take your class and extract an interface (via the context menu). You can then code to that interface, and hardly any time was spent.
If you are just doing a simple project, then it may be overkill. But on medium+ size projects, I try to code to interfaces throughout the project, as it will make future development easier.

DAL design question

I need to design a Data access layer DAL .Net Enterprise library version 3.5 Data access application block (DAAB)
In my application,I've various logical modules like Registration, billing, order management, user management,etc
Am using C# business entities to map the module objects to database tables and then return the List collection to the client.
I would like to design my DAL in such a way that if tomorrow we decide to use some other data access framework we should have minimal code change.
Given this, how do i design my class structure?
I thought I would have a class DbManagerBase which would be a wrapper over existing .net DAAB
This class DbManagerBase would implement an interface called IDbManagerBase which would have public methods like ExecuteReader, ExecuteNonQuery, etc.
The client class ie. RegistrationDAL,UserManagermentDAL would have the following code inside each of its methods:
IDbManagerBase obj= new DbManagerBase()
obj.ExecuteReader(myStoredProcName)
.
.
.
is this a good OOPS design?may i know any better approach please?or do i need to use inheritance here?
Can i have all the methods in DbManagerBase class and RegistrationDAL,UserManagermentDAL classes as static?I guess,if i've methods as static then the above interface code wont make any sense...right???
To truly abstract the DAL I'd use the repository pattern.
To answer a few of the questions:
Can i have all the methods in
DbManagerBase class and
RegistrationDAL,UserManagermentDAL
classes as static?
I would probably go with a non-static approach cause it gives the flexibility to better control instantiation of the DALs (eg. you could create instances of them from a factory), also it will allow you to have two DALs in place that are talking to different DBs in a cleaner way. Also you will not need to create an instance of the DbManagerBase in every object since it would be an instance member.
Regarding IDbManagerBase having ExecuteReader, ExecuteNonQuery and obj.ExecuteReader(myStoredProcName)
I would be careful about baking the knowledge about database specific concepts in too many places. Keep in mind some DBs to not support stored procedures.
Another point is that before I went about implementing a DAL of sorts I would be sure to read through some code in other open source DALs like NHibernate or Subsonic. It is completely possible they would solve your business problem and reduce your dev time significantly.
If you are looking for a small example of a layered DAL architecture there is my little project on github (it is very basic but shows how you can build interfaces to support a lot of esoteric databases)

Categories

Resources