I always see the word contract and it seems to have different meanings or at least it is how it looks to me (I am not a native English speaker) so when I see the word "contract" I cannot be sure what I should understand and expect from it. I don't know if anyone else is having the same trouble but this bugs me a lot. For example, when I see "interface" it makes me think "abstraction, dependency injection, inheritance, etc." and I know what I am looking for and it is getting formed in my mind nicely and easily.
But when it comes to the word contract I cannot visualize a pattern, class etc. whatever it is. Is it something formed using interface or a class or maybe an attribute etc.
For example, there is a class here (in Json.NET) which talks about something called IContractResolver and the page is explained what it is used for :
The IContractResolver interface provides a way to customize how the
JsonSerializer serializes and deserializes .NET objects to JSON
without placing attributes on your classes.
The explaination is very comprehensible but I cannot just form the idea when I see Contract and I cannot say :
"Umm, I am expecting some methods which do this and that so I can
override it and later I use this class here/there to change/fulfill
some functionality etc."
and this bugs me a lot. I read some article about it but they are talking about Design by Contract and it is not something useful for someone who has troubles with the meaning of "contract".
So can some one please explain how I should understand this term and what I should expect when I see it? It would be very nice you could add some sample code in order for me to visualize it.
In "Design by Contract", a contract means an agreement between the developer of a library (class, function) and the consumer.
It could be an agreement that no one will pass null for a certain parameter. It could be an agreement that a particular method always completes in less than 200ms. Or that events are raised on the thread which created the object. What's important is that there is some document full of rules and both caller and function agree to those rules.
IContractResolver sounds like it provides a data format. It is not a contract. (There may be a contract that says both endpoints of the communication will use this format for particular messages, but a format is not by itself a complete contract. A contract would need to also describe when each message should be sent, and so on.)
Contract is an agreement among at least two parties. In this context .NET contracts make perfect sense.
In design by contract context, it's similar. Designing by an agreement, you're agreeing on an interface and some verifiable obligations.
Contract is rather broad term, but have some specific meanings. So to understand it correctly you should know the context. The general definition is (from here):
A binding agreement between two or more persons or parties
It can be agreement on what operations are provided (partially synonymous to protocol), like here:
The service contract specifies what operations the service supports.
Or in what format data has to be passed (here):
A data contract is a formal agreement between a service and a client
Also interface sometimes is called contract - because it is exactly it: binding agreement on what can be called and how.
Contracts in data-driven development are also agreements on what data can be passed, what data can be returned, and what are valid states of objects. It is essentially the same thing as in first quote: binding agreement between two different pieces of code.
So if you are not sure about context, try to use common sense. If you are not familiar with context, try to understand or ask:
What does contract define in this case?
How is it defined?
What are the parties that are involved?
Well, contract is one of those burdened words which have many meanings depending on context.
To me, it is any agreement between two parties, so it can be an interface in the sense of .NET interface (i.e. a type), or it can be a set and sequence of messages exchanged between the parties (i.e. a protocol) or in your JSON example a mapping between an object and its persisted form.
It is interesting that you mention "interface" as clearer because it is not necessarily so. I don't associate it with abstraction, dependency injection or inheritance (especially that last one), but more loosely with any kind of protocol. Maybe the reason is that I started with languages which don't have interface built in with specific meaning and as a keyword (e.g. C++). The point is that it also depends on context.
Related
I'm currently implementing the publish-subscribe pattern for use in my future applications. Right now I'm having trouble figuring out the "best" way to design the message part of the pattern. I have a couple of ideas in mind but please tell me if there's a better way to do it.
Idea 1: Each message is an object that implements a simple tag interface IMessage.
Idea 2: Each message is represented as an array where the first index is the type of message and the second contains the payload.
Are any of these "better" than the other and if so, why? Please excuse me if this seems like a stupid question.
Your first idea make more sense, take a look at the NServiceBus github implementation of messaging patterns using marker interfaces or unobtrusive message definitions.
In essence a message in publish/subscribe scenario is an event, it's name should describe the event and have the relevant reference to data related to this event.
Andreas has a good article
HTH
Both approaches are useful. The first is useful when working with the message in your application. The second is useful if you are receiving raw message data over the network and have to determine how to deserialize it.
If you look at how WCF serializes, then they put the type as an attribute in the serialization, so it knows what to deserialize it to. However if you are going for JSON serialization fx, then you are probably better off having a property to hold your type information. Also be aware that this type information does not have to specify an actual CLR type, just an identifier to let you know how to read the data.
Once you know how to read the data, then you can create your object and take advantage of the type system, ex. using tag interfaces.
You don't specify whether your messages cross process boundaries or not.
In the latter case, where messages are passed between layers in the same application, the first approach where messages are just objects (optionally implementing the same interface) is probably the easiest.
In the former, where you have interprocess and interoperable messaging, I think you get the most of XML. XML is very flexible, easy to support in different techologies, allows you to sign messages in an interoperable way (XMLDSig) and allows you to create variety of different input/output ports (tcp/http/database/filesystem). Also, messages can be easily validated for their integrity with XSD specifications.
In the pypubsub library (a publish-subscribe for python), I found that there was great benefit to name the payload data, so the sender and receiver can just populate fields and not have to rely on order of items in message, plus it provides "code as documentation". For example, compare these, written in pseudocode. Using array:
function listener(Object[] message):
do stuff with message[0], message[1], ...
message = { 123, 'abc', obj1 } // an array
sendMessage('topicName', message)
Using keywords:
function listener(int radius, string username = None):
do stuff with radius, username, ...
// username is marked as optional for receiver but we override the default
sendMessage('topicName', radius=123, username='abc')
Doing this in C# may be more of a challenge than in Python, but that capability is really useful in pypubsub. Also, you can then use XML to define the schema for your messages, documenting the payload items, and you can mark some payload items as optional (when they have a default value) vs required (when they don't). The lib can also check that the listener adheres to the "payload contract", and that the sender is providing all data promised via the "contract".
You should probably take a look at (and even use) existing libraries to get some ideas (pypubsub is at pypubsub.sourceforge.net).
Both approaches are viable, the second one involves that you are responsible for the de/serialization of the message, it gives you much more freedom, power and control over the message, espacially versioning, but all this comes at a cost and I see this cost sustainable only if some of the actors are not .net actors. Otherwise go with the first approach and as Sean pointed out take a look at toolkits and frameworks that can greatly help you with all the plumbing.
I'm designing some services and I would like to get some feedback about the conventions I'm using.
For all operations, I always define a 'Context' object and a 'Result' one, because of the following advantages:
extensibility: I can add parameters to the context or objects to the result without changing the interface
compactness: I only have a single object in the definition, even if I need many parameters
Example:
[OperationContract]
DoSomethingResult DoSomething(DoSomethingContext context)
Anyway, I'm not really sure that this is the best way to do it because of the following reasons:
overhead: I always wrap the response properties into an object. Sometimes, the Result object has no properties
versioning: WCF has built-in versioning for contracts, and maybe it could be better to use a different version to inform about the difference
In fact I use the same technique with normal methods too, so it would be important for me to get some feedback, advices, critics and so on and so forth.
Thank you
I think that's a perfectly legitimate way to write your contracts. I've worked on a number of projects with these sort of contracts and it is has been a pleasure - very easy during development (just add a property to the object and you're done), a straightforward and clear pattern that applies to all services, and allows for things like a single validation method for all operations.
In response to your concerns:
I don't think the overhead of creating an empty object is at all significant. Don't worry about this unless it becomes an issue.
If the Result object has no properties (i.e. you aren't returning anything) then simply return void. You aren't gaining anything by returning an empty object.
You can (and probably should) version these objects as you version your contracts. What you are doing in no way precludes you from versioning your objects.
Please note that versioning objects does not mean changing them to DoSomethingResult_v1, DoSomethingResult_v2 as I've seen before. You should version with namespaces; it makes things clearer and cleaner. Just put a version in the XML namespaces in both the operation contract and data member attributes.
I don't think there are any performance concerns here, and the code looks easy to work with from the code-owners perspective.
My big concern is that it isn't at all clear from the consumers perspective how your service works. They would have to rely on separate documentation or error messages.
It would be much easier for someone unfamiliar with your code (i.e. just downloaded the WSDL) to consume your service if the parameters that it required were declared. You also get a good degree of validation out of the box.
To illustrate:
[OperationContract]
DoSomethingResult DoSomething(DoSomethingContext context)
vs
[OperationContract]
[FaultContract(typeof(CustomerNotFoundFault))]
Customer GetCustomer(UInt32 customerId)
This point is mostly relevant to the design of APIs. Where this isn't so relevant, is where you are both the author and the consumer of the service.
I totally support Kirk Broadhurst's suggestion of using namespaces for versioning. I use that and it works well.
EDIT: on a second reading, I think I misread your post. I was assuming here that your parameter and return value objects were some generic object that you use across all services. If indeed they are specific to each service, then that's a great approach which I've used successfully on many occasions. You'll do well with it.
I'll start in the way most people seem to have taken to, on here....
So I was....
Nah thats gash. I'll start again (might lose a few points for not being straight to the point but wth)
Right,
I have inherited a framework which utilities WCF to provide some operation and data contracts.
This might be irksome to some, but I haven't done enough reading on SOA or WCF to garner knowledge about effective patterns (or best practices..) and therefore, don't really have a weighted opinion on my team on this subject, as of yet.
As an example in the framework I am using, there are a bunch of models for users.
Specifically we have the following models (data contracts):
users_Loaded
users_Modify
users_Create
For all intents and purposes these data contracts are exactly the same - in so much that other than their "type", they have the same members and properties etc, and therein is my first problem.
The operations which utilise the data contracts have parameters which match the data contract you might want to perform some action with
Thus the operations utilising the data contracts:
CreateUser(users_Create createdUser, ..., ...)
ModifyUser(users_Modify modifyUser, ..., ...)
GetUser(out users_Load loadedUser, .., ...) (out parameters on left most side of parameter list to boot!?)
Maybe the intent was to delineate the models and the operations from one another, but from my experience a method and its parameter list, usually give a good indication of what we are going to need to do.
Surely one data contract would have sufficed, and maybe even one operation (with a operation type parameter)
Am I missing the point. Why would you do what I have described?
Thanks.
i
It sounds like the previous developer(s) were either trying to implement some bastardized Command pattern, or they flat didn't understand WCF.
Long answer short, yes, from what you've said, you should be just fine combining these into a UserDto class that is the DataContract for all three operations. svcutil, for its part, should have no trouble generating one DataContract class on the client side that will work for all three OperationContract methods (or, since you seem to control both sides of this service, just use a shared assembly containing your DTOs on both client and server).
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.
I am in the process of converting all my parameters, return types, classes to all use Interfaces instead ie. IUser instead of User.
Besides the extra code required to maintain this, are their any negatives to this approach?
This isn't an uncommon approach, especially if you do a lot of mocking; however, it has issues with:
data-binding support (especially when adding rows to tables)
xml serialization (including comms WCF, asmx, etc), or contract-based serialization in general
You need to figure out whether the advantages of mocking etc outweigh these issues. It might be that you use IUser in most scenarios, but (for example) at the comms layer it may be simpler to use raw DTOs rather than interfaces.
Note that I'm applying the above to classes. If you involve structs, then remember that in most cases this will involve boxing too.
Overall, this will give you all the advantages associated with loose coupling, so in general I consider this a huge win. However, since you asked about disadvantages, here are some minor ones I can think of:
There's more code involved becase you have both the interface declaration and at least one implementation (you already mentioned this, so I'm just including it for completeness sake).
It becomes more difficult to navigate the code because you can't just Go to Definition to review what another method does (although I'm told that Resharper helps in this regard).
In some cases there may be more in a contract than mere semantics, and an interface can't capture that. The classic example from the BCL is that if you implement IList, you must increment the Count property every time you add an item. However, nothing in the interface forces you, as a developer, to do this. In such cases, abstract base classes may be worth considering instead.
Interfaces are brittle when it comes to adding new members. Once again, you may consider abstract base classes instead.
I once went through a phase of this, but in practice found that for anemic data objects (i.e. POCOs) the interfaces weren't required.
In practice it can be useful to have interfaces to define a contract for behaviour, but not necessarily for attributes.
In general I'd suggest you let your unit testing guide you. If you have rich objects throughout your application then you'll most likely need interfaces. If you have POCOs, you most likely will only need them for controller-style classes.
Interfaces are very good thing, but applying them to all artifacts is overkill. Especially in java you would end up with two distinct files (interface + implementation). So (as always), it really depends :)
Regarding 'interface or not-to-interface'
I would not have domain-objects have interfaces (e.g. User). In my view for code comprehension it is rather confusing (for domain objects interface often would define getter methods). Recently it was a real pain to get unit-tests in place and having domain-object-interfaces. I had to mock all these getters and getting test-data into the domain-object mocks was rather cumbersome.
The opposite is true for coarse grained services and api interfaces. For them I always have an interface from start on.
In more internal-module encapsulated scenarios I start without interface and after some code-evolution if necessary react and do an extract-interface refactoring.
'I' prefix for interface artifact names
I also used to work with the Ixxx prefix but I (happily) got rid of it nowadays for following reasons:
It is difficult to keep up all this 'I' naming convention in an evolving codebase, especially if you refactor a lot (extract-interface, collapse-interface etc.)
For client code it should be transparent whether the type is interface or class based
The 'I' can make you lazy about good interface and classnames.
Not so much a disadvantage but a warning. You would find that to achieve good component de-coupling you will need to use a Dependency Injection framework (that is if you want to keep your sanity and have some sort of idea what your interfaces map to).
What also tends to happen is that non-trivial classes sometimes naturally convert into more than one interface. This is especially true when you have public static methods (i.e. User.CreateAdminUser). You will also find that it's harder to get an interface to hold state AND do stuff. It's frequently more natural for an interface to be either one or the other.
If you get stuck in the process, do take a minute a do some research into what's an appropriate paradigm that you are trying to implement. Chances are someone has solved this particular design pattern before. Considering this is a big refactoring job, you might as well take extra time and do it properly.
avoid the ISuck prefix.
edit: the ISuck convention is a manifestation of the Systems Hungarian notation applied to type names.