I have to access a legacy database that has "generic" tables in it and I do not have the authority to change it. Depending on the customer data that I'm working with, the relationships between the tables may differ. So, customerA may join to the order table by only their customer number while CustomerB may join to the order table by customer number and the date. CustomerC may not join to the order table at all but to a different table.
So, what I would like to do is to create an object graph for CustomerA and one for CustomerB and one for CustomerC. I thought about creating a wrapper class for each but have been researching proxies. That said, the examples that are written about Proxy classes make them look identical to a wrapper class. Thus my question, are proxy classes synonymous to wrapper classes.
Thank You.
No, they are not the same. Have a look at Proxy pattern and Wrapper pattern at Wikipedia.
Basically, a proxy is an object that looks the same as the original object (i.e. implements the same interfaces), but does something more.
Wrapper is an object that looks differently than the original object, but usually does the same.
There are a couple of ways of handling the problem at hand.
One is to map to a common domain model. This works fine if you have the same basic behavior, but might not serve you well in the particulars (different keys for different types of clients).
Another is to move the common bits down into a base class and then inherit for the different specifics in state (different properties) or the different behaviors (primary key only id, etc). Considering this is both differing behavior and state, this is a direction you can use.
Now, patterns. A proxy pattern is one where the new object can provide some of the behavior and state of another object, but is not the object. Think of it like what a person voting for you as a proxy means, and then relate it to software. I would not think of it like a wrapper, as a wrapper is normally used to present a different face from the underlying object. This can be due to the need to hide something in the underlying object or to add further behavior on top of the object. The proxy pattern will not help with the varying keys; Possible with the wrapper, although I am not convinced it is the simplest way to do this.
From wikipedia: "A proxy, in its most general form, is a class functioning as an interface to something else"
ProxyPattern
Proxy: is an "interface", it's a "blackbox", if you like, from which you request something and it gives you back what you want.
Wrapper: is a entity which basically hides a functionality by encapsulating, so hiding inside it a "real" component/another class/... by exposing to the caller its own methods, so the user of wrapper has no clue with which object it really works.
Hope this helps.
Regards.
Looking at the implementation a proxy and a wrapper class might be very similar. However the terms are often used in different meenings.
A proxy is an object that behaves like the real object, but isn't. Instead it forwards all calls to the real object, hiding the complexity of accessing the remote object. An example of proxy objects are the WCF clients genereated by Visual Studio. The client calls them as if they were the real service code, and the proxy handles the communication.
A wrapper is an object that for some reason hides another object. Usually this is done when interfaces are not compatible. An object with the right functionality, but the wrong interface, is wrapped in another object that translates the interface.
Related
I have a WCF service that uses generics in its data contract, for example (simplified):
public GetDetails(StatusField<string> status);
Now WCF supports generics by creating a non-generic equivalent type for every possible value of T in the generic. So, for the above example, the client consuming the WCF service will see the following signature for the above function:
public GetDetails(stringStatusField status);
//...
Now the client has a copy of the generic version of the StatusField class. We want to use AutoMapper in the client, to map between this generic StatusField and the types generated above by WCF (such as stringStatusField) so we can call the service. We could do this by manually creating the maps at client startup, like so:
Mapper.CreateMap<StatusField<string>, stringStatusField>();
However this is laborious as there are 50+ possible values of that WCF has converted. Extending this idea, we could use reflection to automatically create maps for all the types and this is the solution we are currently using.
Ideally what i would like to see is a solution that ties into the architecture of AutoMapper to avoid having to do the reflection manually. conceptually, this would require some way of defining a convention that AutoMapper would use to allow it to tie the two types together, similar to how it allows custom conventions to be specified when matching properties. As yet, i have not seen a way to do this and this is the question i would like answered here, if anyone knows how this can be done, specifically in relation to the above scenario.
BTW i am aware that some may be thinking of Mapper.DynamicMap() as a solution to this problem. Firstly, we dont want to use this as it means debugging could potentially be harder (as indicated by some in other posts similar to this) and also if the StatusField is deeply nested in an object graph being passed to the WCF method, im not sure this solution would work and could potentially lead to a type being incorrectly mapped and other such issues. I would really like to concretely define the allowable mappings if possible.
Unsure if AutoMapper provides the support you are after, but if it did it would be using reflection as you propose.
If you are opposed to the reflection solution due to performance concerns (which should be a one-time startup cost), then maybe a T4 template-based code generation solution might be worth considering?
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.
I have started writing my own WebDAV server class in .NET, and the first class I'm starting with is a WebDAVListener class, modelled after how the HttpListener class works.
Since I don't want to reimplement the core http protocol handling, I will use HttpListener for all its worth, and thus I have a question.
What would the suggested way be to handle this:
Implement all the methods and properties found inside HttpListener, just changing the class types where it matters (ie. the GetContext + EndGetContext methods would return a different class for WebDAV contexts), and storing and using a HttpListener object internally
Construct WebDAVListener by passing it a HttpListener class to use?
Create a wrapper for HttpListener with an interface, and constrct WebDAVListener by passing it an object implementing this interface?
If going the route of passing a HttpListener (disguised or otherwise) to the WebDAVListener, would you expose the underlying listener object through a property, or would you expect the program that used the class to keep a reference to the underlying HttpListener?
Also, in this case, would you expose some of the methods of HttpListener through the WebDAVListener, like Start and Stop, or would you again expect the program that used it to keep the HttpListener reference around for all those things?
My initial reaction tells me that I want a combination. For one thing, I would like my WebDAVListener class to look like a complete implementation, hiding the fact that there is a HttpListener object beneath it.
On the other hand, I would like to build unit-tests without actually spinning up a networked server, so some kind of mocking ability would be nice to have as well, which suggests I would like the interface-wrapper way.
One way I could solve this would be this:
public WebDAVListener()
: WebDAVListener(new HttpListenerWrapper())
{
}
public WebDAVListener(IHttpListenerWrapper listener)
{
}
And then I would implement all the methods of HttpListener (at least all those that makes sense) in my own class, by mostly just chaining the call to the underlying HttpListener object.
What do you think?
Final question: If I go the way of the interface, assuming the interface maps 1-to-1 onto the HttpListener class, and written just to add support for mocking, is such an interface called a wrapper or an adapter?
I'll answer your last question first: a class is an adapter if it implements some ITarget interface using a contained object matching some ISource -- an adapter from ISource to ITarget. In this case, there is no source interface, you're trying to add one in, so I'd call it a wrapper.
I'd be inclined to
Make a WebDavListener class which has all the methods it needs for its own behaviour, uses an HttpListener internally, and doesn't expose anything about that HttpListener.
If and when you need it, make IHttpListenerWrapper and HttpListenerWrapper as you suggest, and change the WebDavListener to take an IHttpListenerWrapper in its constructor. Assuming all the methods are the same, this should be a simple search-and-replace. You could even leave the original constructor in there and have it construct a wrapper and call the new constructor.
If and when you need it, make an IWebDavListener for it to implement, if you think you might want a dummy WebDAV listener for unit testing other things.
This sort of design issue is why I love refactoring tools like ReSharper: Extract Interface, Create Derived Implementation etc. make it much easier to make these sort of changes, so you can worry less about whether to do them now or later :-) (Assuming you are allowed to freely change the source later, of course, which depends how you're delivering things.)
I'm getting a complex object from the server - lets call it ServerDTO. I want to map it to a client side object - lets call it ClientDTO.
assuming both ServerDTO & ClientDTO have the same structure inside them.
I want to map the ServerDTO object to the ClientDTO object.
very simple mapping like so:
ServerDTO sd = server.Result;
ClientDTO cd = new ClientDTO();
cd.Property1 = sd.Property1;
cd.JahRas = sd. JahRas;
and so on...
so far so good.
now my question is can this mapping be done in some abstracted layer that can handle all the mapping of all my objects no matter what type or what's inside them?
so when I want to map I'll go:
ClientDTO cd = Mapper.Map(sourceServerDTO, typeOf(ClientDTO));
You might want to look at Automapper
As Steve said, I'd try to use only one type. To avoid referencing directly the web service, migrate all the interfaces / common types into a common assembly that both your client and server will reference. Obviously, this assumes that you have hands on both codebases.
If the 2 objects have the same structure and you want to mirror the content why do you even need 2 different types? Can you not just use ServerDTO type in your client code too?
I know there are times when you need separate types, but I'd think twice before doing this.
If you do need different types then I think Automapper (link posted by Lee in separate answer) is a good bet.
Shared types between client and server only works if you are not going to have different applications calling the same server. (This sort of defeats the one of the main benifits of having a set of servers)
If you do share types you end up with one big splurge of a domain model where changes in one application breaks things in another. i.e asmall change on one client that doesn't even involve a change to the service interface can lead to a rollout of your whole application suite..
I would never say never but shared types is rarely a good idea.
Did about 30 minutes worth of searching, found lots of relevant info, but none that addresses this particular concern, hope I'm not repeating a common question.
I would like to know what the general consensus is in regard to implementing infrastructure-related interfaces in domain types. Everything I've read about DDD leads me to believe that this is to be avoided, as this understandably detracts from the conciseness of the model.
I am, however, at a point where I'm uncertain as to how to work around this. Specifically, I've got a domain type that would be perfectly fine to use in my presentation layer, except that I'd like to display an instance of it in a control that requires it implements IComparable. I would rather not 'pollute' my type with an implementation of this interface.
I think (perhaps naively) my options are:
Use a Data Transfer Object (DTO), have it implement the interface, and use an instance of that in my
presentation layer.
I'm vaguely
familiar with the fundamentals of
AOP - perhaps there's a suitable
technique in this realm?
Perhaps
related to option 2 - code 'weaving'?
I know very little of why/when to
consider this, but am I bumping up
against it now?
Bite the bullet,
and implement the bit of code
that it takes to satisfy the contract.
Some voodoo-magic I've
never even heard of?
If anybody cares to recommend 2, 3, or 5 - could you point me in the direction of some reading material that might help get me started?
Thx in advance.
implement an intermediate "View-Model" class:
the View part knows how to talk to the user-interface (databinding, IComparable, et al)
it holds a reference to the Model (domain) object
it exposes the properties of the Model object (and relays change notifications if necessary)
This will work, and should be fine.
2-4. These are really the same option. The difference is in how you implement the code to satisfy the contract. Code weaving and AOP are still "polluting" your object, but they're doing the work for you in a semi-automatic way (ie: you just put an attribute on your object, and it implements it post-compile). The final result is the same, though, whether you implement the object or use AOP/code gen.
My suggestion below:
Most of the time, anything that requires IComparable<T> also provides an option to pass an IComparer<T>. If your control does, this would let you implement the comparing logic external to your data objects, and just pass it in as well. I would investigate this as an option first.
Otherwise, my suggestion would be to just implement IComparable<T> directly in the object. If you don't want to "pollute" the API, just implement it explicitly.