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.
Related
This question already has answers here:
Interface vs Base class
(38 answers)
Closed 9 years ago.
what is the main utility of Interface. we know that we can implement dynamic behaviour using interface but i guess it is not only the utility. so i like to know when we have to write interface and when we need to go for abstract class.
show me 5 or 10 most important uses of interface in real life scenario.
another main use is coming to my mind that project manager or team lead will implement basic skeleton through interface and other developer follow it.
so please guys show me with sample code few most important use of interface which we can do with abstract class or concrete class.
one guy told me like this way which is not very clear to me
interfaces are defined contracts between classes or structs, consumers can exchange the implementation by a different one as long as the same contract is met that is the method names and signature that compose a specification that classes and structs can work against rather than working against a concrete implementation.
The important part about interfaces is to know when to use them and as a matter of fact it's quite simple, when you want two or more unrelated objects to have the same common functionality but not necessarily the same implementation you will want to use interfaces; otherwise, when you have related objects that have a shared functionality and implementation then you may consider to use an abstract class instead of an interface.
this thing is not clear specially
when you want two or more unrelated objects to have the same common functionality but not necessarily the same implementation you will want to use interfaces; otherwise, when you have related objects that have a shared functionality and implementation then you may consider to use an abstract class instead of an interface.
it would be nice if anyone explains with sample code when to go for interface & when abstract class.
show me few best important area which is always handle with interface with sample code or best interface uses with sample code.thanks
Some of microsoft recommendation from this link
If you anticipate creating multiple versions of your component,
create an abstract class. Abstract classes provide a simple and easy
way to version your components. By updating the base class, all
inheriting classes are automatically updated with the change.
Interfaces, on the other hand, cannot be changed once created. If a
new version of an interface is required, you must create a whole new
interface.
If the functionality you are creating will be useful across a wide
range of disparate objects, use an interface. Abstract classes
should be used primarily for objects that are closely related,
whereas interfaces are best suited for providing common
functionality to unrelated classes.
If you are designing small, concise bits of functionality, use
interfaces. If you are designing large functional units, use an
abstract class.
If you want to provide common, implemented functionality among all
implementations of your component, use an abstract class. Abstract
classes allow you to partially implement your class, whereas
interfaces contain no implementation for any members.
I won't answer all you questions. I just want to give you some hints.
The main difference between an interface and an abstract class is, that a c# class can implement multiple interfaces even if they declare the same members. And it can even implement those equally named members differently by implementing the interface explicitly.
If you derive from an abstract class, you also "inherit" al its dependencies. For example if a method in an abstract class uses another class from a different assembly, you have to reference that assembly. --> Compile order --> No parallel build
Mocking in unittest can be trickier when using abstract classes with base functionality
Let's take for instance some Data Access Objects which can retrieve data from a DB, a SAOP Service, a REST Service or even an XML file.
You would use Interfaces to ensure what kind of operations they offer to the rest of the application. You can also say that those interfaces describe the Domain and how they interact with it.
public interface IUserDao
{
User GetUserById(int id);
void AddUser(User u);
....
}
This IUserDao can be implemented by using WCF, Entity Framework, XmlDocuments, and many other techniques, the controller or other parts of the application don't care about the details as long as they have those abstracted methods to retrieve and add a user.
On the other hand the same Data Access Objects can have a base class which can for instance initialize some connections or open the XmlDocument, ...
public abstract BaseDao
{
public Connection GetNewConnection()
{
....
}
// or similar functions which are used by DAOs accessing the same data source (DB, XML, ...)
}
So as it was described, you can use interfaces to hide implementation details and bring the implementation to a more absract level, this way, less skilled developers or developers more interested in the domain specific aspects (some specific calculation, ...) can contribute without the need to understand how exactly they need to retrieve and store the data from / to the database.
Also it is easier to exchange functionality, for instance you can start with a simple xml file but soon you'll realize that you'll need a whole DB - you can keep the interfaces and implement the classes with DB access.
On the other hand abstract classes share basic functionality (technical functionality), which is so basic that it is used by many classes but shouldn't be instantiated alone. You could exchange Abstract Classes for some utility classes with static methods, but than you would loose the advantages of OOP.
I'm a C# coder with a (Windows) sysadmin background. I've been looking at the various service frameworks in order to create a unified REST-API for various infrastructure components (windows management, hardware management, etc.). I've settled on using ServiceStack as my framework for this, but have a question on how to manage my DTOs. Most of the time my source data is from non-database objects, which include:
Other web services (usually SOAP based). I usually bring these in via "Add Web Reference" (most, but not all, are asmx).
.NET Objects (usually WMI/WinRM/PowerShell [System.Management], or Active Directory [System.DirectoryServices])...
In some unfortunate cases, raw text output I get as a result of invoking a command (via ssh or cmd).
In all of these cases, I will have to call some sort of Save() method to update properties. In addition, there might be some non-CRUD methods I would like to expose to the REST service. Usually I don't need everything from the source data (for example, in the case of web service data, I'm only interested in boxing up certain properties and methods of a particular proxy class). My understanding is that my DTOs should be clean and not have any dependencies. Since I don't believe I have an ORM I can use, what design pattern should I use to map my data to a DTO?
Apologies if I'm misusing any terminology here...
With a variety of backend services and data sources, I think it would be hard to use anything highly structured like a framework to map your data to DTOs. I would keep it simple:
Keep your DTO classes separate from any of your backend classes. Generally resist the temptation to try to reuse code, use inheritance, etc., in your DTOs (though sometimes I find it useful to declare interfaces for the DTOs to implement). This will keep the interface of your your ServiceStack service clean and independent of backend details.
There are some extension methods available in ServiceStack to easily map properties between two classes: TranslateTo, PopulateWith, PopulateWithNonDefaultValues, etc. The link above mentions these. The trick is that while your DTO classes should not be subclasses of, or directly reusing your backend classes, you will find it convenient to have the property names match up if you want to use these mapping methods.
Keep your ServiceStack service classes simple; their primary responsibility should be translating between DTO classes and lower level model classes, and making one or two method calls on business logic classes to do the actual work.
It sounds like it would be useful for the highest level of your business layer--the classes that your ServiceStack services interact with--to present a clean interface that abstracts away the details about the source and format of a given type of data. So you may want three layers of model classes. From top to bottom: DTOs, business layer POCO classes, and framework-specific classes for specific backend services like web reference generated code or whatever.
I think that's about all there is to it.
I recommend that you define DTOs that meet the requirements of your API, and then have a 'business logic' layer that mediates between the actual objects and your DTOs.
Your ServiceStack services will have a dependency on both the DTO definitions and the business logic layer, and the business logic layer will have a dependency on the DTO definitions and the real-world object definitions. In effect, your REST services and DTOs will act as a facade over the real-world APIs.
I'm building a public API for our application, using C#. I have a set of facade classes on top of DTOs used with a WCF client. It allows the API consumer to fetch, update, create, etc., from a database application. Standard stuff: Customer has a collection of Orders, Order has a collection of Line Items, etc.
The facade classes all derive from a common base class and override methods that do validation, reading/writing the DTOs, and other plumbing stuff, all using various internal types. I'm using a factory for creating new objects and fetching existing ones.
The question now is how best to expose the classes through the API while minimizing exposure of implementation details.
Interfaces seem like the obvious approach as the simplest way to limit what's exposed (and may in the end be necessary anyway, as a COM-compatible interface is under consideration). The problem with the interface approach is that internally my code will be dependent on particular implementations of the interfaces.
Suppose I have an ICustomer interface exposing my CustomerFacade, and IOrder exposing OrderFacade. Externally, ICustomer has a collection of IOrders. But internally, the CustomerFacade has a collection of OrderFacades. If the client application adds a new IOrder to a customer, I have to check that the IOrder is really an OrderFacade previously created from my factory, and not some other object outside my control that implements IOrder. That's because internally I need an order to be able to do a lot more than what an IOrder can do.
Practically speaking this doesn't much matter--users of the API are not going to be trying to create their own Order implementations. But it feels inelegant to me, like an abuse of what the interface contract is supposed to mean.
Exposing the facade classes directly isn't great, because the entire class hierarchy has to get exposed, along with the internal types used by protected methods, and that clutters up the API with types that the consumer won't be using and doesn't need to know about.
The other alternative I can think of is another layer of encapsulation: An Order that contains a private OrderFacade and only exposes the members that should be public. But this seems like a lot of extra code for limited benefit.
I considered abstract base classes but that doesn't work any better than exposing the facade classes, due to the inheritance structure. For example, if I have a ServiceItem that inherits from CatalogItem, introducing an abstract ServiceItemBase in between still requires me to expose all the protected methods in CatalogItem.
Any recommendations on these approaches, or an alternative I haven't looked at?
That seems pretty complex. I don't know the business problems you're trying to solve, so I don't know why there's the need for the various facades. If users will be using your api for data manipulation, you could consider using commands to modify the data, and queries to return DTO's that contain only the data the client will need.
http://www.amazon.com/Framework-Design-Guidelines-Conventions-Libraries/dp/0321545613
This is a great book that might help.
You could also expose abstract classes with no public constructors instead of interfaces. This has the additional advantage that abstract classes can be extended as a non-breaking change, which is not true for interfaces.
Using the internal access modifier enables the hiding of members that should not be visible outide the implementing assembly.
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
I was wondering if it was better in WCF to use multiple operation contracts or to have only one operation contract with a polymorphic data contract.
Let me give you a small example :
[OperationContract]
action1Answer action1(action1data a);
[OperationContract]
action2Answer action2(action2data a);
or
[OperationContract]
actionAnswer action(actionContract a);
Action contract would be an abstract class which both action1Contract and action2Contract will inherit from. The action contract would specify the do() member function in its interface which would have in turn to be overloaded in the child classes
Personnaly I find the second approach to be more intersting as it allow you to nicely encapsulate the data and the action in the derived actionContract and in turn makes it easier to add new actions. But It's the first time I'm using WCF so probably you know better!
This question borders on the edges of the Holy Wars of OO polymorphism and SOA, but I'll provide my two cents:
When you're considering developing a service layer, it should be clear to the end consumer of the service what to pass in and what to expect; approach 2 doesn't handle that well. (Also, when doing SOAP with WCF and then loading from the wsdl in other .NET projects, it doesn't properly mark abstract classes, nor do interfaces get transferred. WSDLs have no way of describing a non-instantiable base class, it seems.)
Though, I must admit, I think the second process is great using the KnownTypeAttributes (as I see just now marc_s has posted) - I've used it myself when allowing for unknown future requirements.
I agree approach #2 looks better - from an OOP standpoint.
But: SOA/WCF and polymorphism typically don't match too well - SOA (at least when doing SOAP based calls) needs concrete classes that can be expressed in the WSDL/XSD that defines your service.
You can use derived datatypes based on a common base type - if you do, you'll have to look into the KnownType attribute (or ServiceKnownType) to signal to WCF that you might be returning something else than the operation contract actually says it will.