I've got several C# classes each with similar properties.
(They're part of an SDK and their code can’t be changed.)
Person.Name
Product.Name
Order.Name
I want to use these classes polymorphically, but they don’t implement a common interface or derive from a common base class, so that’s not possible.
To get around this, I’d like to wrap each one in another class that does implement a common interface, and wire-up each class property to its corresponding interface property.
What would be a suitable name for the wrapper classes? Wrapper, Decorator, Adaptor, Proxy? Does this pattern have a name? Is there a better approach?
(I don't want to use dynamic duck-typing or an impromptu interface.)
It looks like Adapter, because you are adapting the existing interfaces to the specific requirements.
(I don't want to use dynamic duck-typing or an impromptu interface.)
So what is wrong with a NamedObject?
public class NamedObject
{
public string Name { get; set; }
}
It literally says what it is, nothing less, nothing more.
I'd stick with CodeCaster's idea, and perhaps with a dash of Func<T> for no other reason than I get withdrawal symptoms when I don't use angle brackets...
public class NamedEntity
{
public string Name { get { return _getName(); } }
private Func<string> _getName;
public NamedObject(Func<string> getName)
{
_getName = getName;
}
}
And then call thus:
var named = new[]
{
new NamedEntity(() => person.Name),
new NamedEntity(() => product.Name),
new NamedEntity(() => order.Name)
};
The added benefit with this is when the value of the property changes on the target object, it changes within the NamedEntity reference too via the Func, this means within the life span of the objects you can get away with wrapping them once. You can also do the inverse with Funcs that set values as well as get, and can adapt more properties.
I am not immediately sure what pattern this represents (if any), though I would guess Adapter pattern (which is a type of wrapper pattern). However, it could also be argued to be a Proxy pattern. Not sure really.
Maybe you can just change the namespace and keep the names of the original classes.
Technically, I think the most correct name would be Adapter, see this question.
Adapter is used when you have an abstract interface, and you want to map that interface to another object which has similar functional role, but a different interface.
You don't have abstract interface, but "similar functional role, but a different interface".
Related
In the below adapter design pattern sample code, why a new class is introduced instead of using multiple interface in the client?
interface ITarget
{
List<string> GetProducts();
}
public class VendorAdaptee
{
public List<string> GetListOfProducts()
{
List<string> products = new List<string>();
products.Add("Gaming Consoles");
products.Add("Television");
products.Add("Books");
products.Add("Musical Instruments");
return products;
}
}
class VendorAdapter:ITarget
{
public List<string> GetProducts()
{
VendorAdaptee adaptee = new VendorAdaptee();
return adaptee.GetListOfProducts();
}
}
class ShoppingPortalClient
{
static void Main(string[] args)
{
ITarget adapter = new VendorAdapter();
foreach (string product in adapter.GetProducts())
{
Console.WriteLine(product);
}
Console.ReadLine();
}
}
I have the below queries related to the above code.
What, if ShoppingPortalClient directly inherits VendorAdaptee?
In which scenario we need adapter class?
why instead of simple inheritance a needed class, creating this pattern to access another class method?
Sometimes you have a given API that you can't change (legacy/external-library/etc...) and you want to make your classes be able to work with that API without changing their code.
Lets say you use an API which has an ISomethingToSerialize
public interface ISomethingToSerialize
{
object[] GetItemsToSerialize();
}
That API also has a Serialize function:
public class SerializationServices
{
byte[] Serialize(ISomethingToSerialize objectToSerialize);
}
Now you have a class in your code, and you don't want or not able to change it, let's call it MyUnchangeableClass.
This class doesn't implement ISomethingToSerialize but you want to serialize it using the API so you create AdapterClass which implement ISomethingToSerialize to allow MyUnchangeableClass to use it without implementing it by itself:
public class AdapterClass : ISomethingToSerialize
{
public AdapterClass(MyUnchangeableClass instance)
{
mInstance = instance;
}
MyUnchangeableClass mInstance;
public object[] GetItemsToSerialize()
{
return mInstance.SomeSpecificGetter();
}
}
Now you can use
MyUnchangeableClass instance = ... //Constructor or factory or something...
AdapterClass adapter = new AdapterClass(instance)
SerializationServices.Serialize(adapter);
to serialize an instance of MyUnchangeableClass even though it doesn't meet the requirements of the API by itself.
You've got the idea totally wrong. The VendorAdaptee is the instance of code that produce data, where the ShoppingPortalClient is the one who wants to consume it.
Let me explain what would be the real world situation. You are implementing the shop, and someone else has been implemented a service to give you data about their products(VendorAdaptee). The simple way of doing it is to simply call their methods and use the data, right? But it is their service and they might want to change it later while you don't want to upload your whole solution and release a new version. Therefore, you need an adapter in between to make sure that the data will be send to your real code with the format that you need, and you simply don't care about the address, method name or data format that has been supported by your vendor.
about your questions:
Inheritance is not in any way the case. Conceptually speaking, a shop is not a vendor in any way. considering the code, you have nothing similar in any of those 2, and the behavior is totally different. one is providing data while the other use it.
The main reason you would use an adapter is for legacy code that you don't want to mess with - or a third party that you won't to fit into a certain interface.
There are other reasons, usually depending on how you find easier to develop and if using the adapter design pattern makes sense to you. I don't see it as very useful in other cases though.
First of all I also don't think this is a good example for Adapter pattern. Adapter pattern is much meaningful when you can't directly use one particular kind of class(say A) in your class(say B), instead you implement another class(say C) which can be directly used inside your class (B) and it(C) can directly use the first one(A).
You might ask what will be the examples where B cannot directly use A. There's few.
A's methods don't return the type which is ideally needed by B.
So we don't to mess up with adding the conversion need by B inside B. Instead we give responsibility to C to do it for B.
It might not look natural for B to contain A. etc.
Back to your questions
(1) It is meaningful if you ask,
What, if ShoppingPortalClient directly 'uses' VendorAdaptee?
Just because it is the main class, it has been used as a demo, not to show the structure. And one thing to add, just because you want to call another class's method, don't inherit it unless it is meaningful. In this scenario composition is preferred. For the question why not 'using', just assume it cannot. But you rather ask why cannot. The answer I can give in this example is just assume it is not natural to call Adaptee. That's why I said it is not a good example. :)
(2), (3) I think you can get the answer from the description I have provided so far.
I have a couple of classes in my system
//this was not made an Interface for some WCF reasons
public abstract class BaseTransmission
{
protected internal abstract string Transmit();
//other common properties go here
}
And a few child classes like
public class EmailTransmission : BaseTransmission
{
//This property is added separately by each child class
public EmailMetadata Metadata { get; set; }
protected internal override string Transmit()
{
//verify email address or throw
if (!Metadata.VerifyMetadata())
{
throw new Exception();
}
}
}
Elsewhere, I have created a method with signature Transmit(BaseTransmission transmission). I am calling this method from another part of my code like this:
TransService svc = new TransService();
EmailTransmission emailTrans = new EmailTransmission(); // this inherits from BaseTransmission
svc.Transmit(emailTrans);
This solves my purpose. But usually when I see examples of polymorphism, I always see that the reference type is base class type and it points to an instance of child class type. So usually in typical examples of polymorphism
EmailTransmission emailTrans = new EmailTransmission();
will usually be
BaseTransmission emailTrans = new EmailTransmission();
I cannot do this because EmailTransmission EmailMetadata is different from lets say FaxMetadata. So if I declare the reference to be of BaseTranmission type and point it to an instance of EmailTranmission type, I lose access to the EmailMetadata property of the EmailTransmission.
I want to know whether what I am doing above is a misuse of polymorphism and whether it 'breaks' polymorphism in some way. And if it is abusing polymorphism, whats the right way to do this.
This is perfectly valid. The polymorphic pattern is used in the TransService service Transmit method.
It works with a class that can be morphed in one or more classes.
The fact that you declare the variable using the base class or the derived class is up to you and depends on your specific case.
That should be completely fine. Within the transmit method the object is referenced as BaseTransmission, the "downcasting" is therefore less obvious.
(had this as comment beforehand, but this should really be an answer)
Well, this is perfetly valid case: as you use base class type like a base parameter in the
TransService.Trasmit method.
The only thing which looks strange is:
protected internal abstract string Transmit();
do you really need protected and internal ?
If yes, just skip this notion.
Generally you would prefer using base type
BaseTransmission emailTrans = new EmailTransmission();
This keeps you abstraction clean and helps you with Don't Repeat Yourself. This will be useful in the following scenario: suppose a user can select how she/he can be contacted (email, fax, text). When you need to send something you just have a single method that takes BaseTransmission object and parameters, say BaseParameter.
Note: if it looks, as if there is not much code can be shared, you can define an interface ITransmitter and use it to show that a class can send something, like:
ITransmitter transmitter = new EmailTransmission();
What you are doing is absolutely correct and should work without issue. Passing a child class to a function/method that takes the base class should not be an issue.
However, regarding your example here:
This solves my purpose. But usually when I see examples of polymorphism, I always see that the reference type is base class type and it points to an instance of child class type. So usually in typical examples of polymorphism
EmailTransmission emailTrans = new EmailTransmission();
will usually be
BaseTransmission emailTrans = new EmailTransmission();
This is done if BaseTransmission is an interface or abstract class and you then need to construct a specific version of BaseTransmission. Sometimes if you don't need the extra components some people like to use this to keep their code clean as well. The most common usage of this is seen with generics such as when you want to create a List for example, but need to implement a specific version os List such as ArrayList or LinkedList
I came across an interface recently that only defined a setter like so:
public interface IAggregationView
{
DataTable SetSiteData { set; }
}
I queried this, and it is believed that this is one of the practices advocated by Microsoft for WebPart design (for SharePoint). In fact this example is directly copied from their examples.
I see this as a bad pattern, I don't see why someone should be able to set a value, and then not be able to read it again, and I believe a setter should always be accompanied with a getter (but not necessarily the other way around).
I'm wondering if anyone can explain the benefit of only having a setter, why Microsoft might be suggesting it in this case, and if it's really a good pattern to be following?
There are two scenarios I can see where this might be reasonable:
it is not possible get the value, for example a password; however, I would replace that with a void SetPassword(string) method, personally
the API it is designed for has no requirement to ever read the value, and it is being restricted purely to expose the minimum required API
Re my first point, a Set... method may not be ideal if the consuming API is essentially an automated mapper that assigns values to properties; in that scenario properties would indeed be preferable.
Re your "I don't see why someone should be able to set a value, and then not be able to read it again" - by the same point, however, it could be argued that someone setting the value already knows the value (they set it), so they have no requirement to do this.
But yes; it is very unusual to have a set-only property.
The role of get and set in interface properties is slightly different from those in classes.
public interface IAggregationView
{
DataTable SetSiteData { set; }
}
class AggregationViewImp : IAggregationView
{
public DataTable SetSiteData { get; set; } // perfectly OK
}
The interface specifies that the property should at least have a public setter. The definition and accessibility of the getter is left to the implementing class.
So if the interface contract only needs to write, get can be left open. No need to demand a public getter.
As a consequence, you cannot really specify a read-only property in interfaces either. Only 'at least read access'.
interface IFoo
{
int Id { get; }
}
class Foo : IFoo
{
public int Id { get; set; } // protected/private set is OK too
}
I can imagine using it for (manual) dependency injection. A class may need to have a collaborator injected that it only uses internally. Of course one would normally choose to do this in the class' constructor, but there may be times when one would wish to change the collaborator at runtime.
Classes that implement the interface may add a getter. Most uses of the property may be via an implementing class, not via the interface itself. In which case most code has the ability to get and set the property. The only reason for the interface may be that there is some common code that accesses a common subset of the methods/properties of a family of classes. That code only requires the setter, not the getter. The interface documents that fact.
An interface is just a facility for declaring a group of operations that are "atomically needed" (e.g. if you need to call method A, you'll need to read property B and set property C).
So as always, it depends.
In my experiences such interfaces crop up due to some special need, not for architectural reasons. For example in ASP.NET applications people sometimes make the Global.asax generated type derive from such an interface when they want to maintain global state. Someone might create an initialization value in a separate part of the application and need to publish it to a global place.
I usually like to replace a set-only property with a SetXxx method and make the method check that it is called at most once. That way I clearly enforce "initialization style" which is much less of a smell (imho).
Certainly one cannot set to never produce such a thing but it is to be avoided and will certainly raise questions during code review.
Let's say I have some classes defined as follows:
class Security
{
Boolean AuthenticateUser(String username, String password);
Boolean AddUser(String username, String password);
// many more methods
}
class NetworkedDevice
{
void Stop();
void Start();
// many more methods
}
Then I have another class that contains instances of the above classes. How can I avoid code like the following? I want all the methods of class1 and class2 exposed via this class.
class MyWindowsService
{
Security _security = new Security();
NetworkDevice _netDevice = new NetworkDevice();
Boolean AuthenticateUser(String username, String password)
{
return _security.AuthenticateUser(username, password);
}
// all the rest of "Security" methods implemented here
void StopNetworkDevice()
{
_netDevice.Stop();
}
void StartNetorkDevice()
{
_netDevice.Start();
}
// all the rest of "NetDevice" methods implemented here
}
Edit
I've updated the code to be more real to what I am doing. I am hosting a WCF service within a windows service. The windows service does several things including user authentication and communication to networked devices to name a few. The implementation of my WCF interface calls methods of the "MyWindowsService" class. Exposing the underlying objects as properties is the answer I was looking for. The above class then looks something like:
class MyWindowsService
{
SecurityClass _security = new SecurityClass();
NetworkDevice _netDevice = new NetworkDevice();
Public NetworkDevice NetDevice
{
get { return _netDevice; }
}
Public SecurityClass Security
{
get { return _security; }
}
}
Well, if you're using composition (as you are) there is no "easier way"; you just have to wrap the methods you want to expose. If you want to expose all of the methods of the composed type, then why are you using composition in the first place? You may as well just expose SecurityClass and NetworkDevice via public properties as it is functionally no different than wrapping every method and property/public field.
If it makes sense that they belong in the inheritance chain then SuperClass (oddly named as it would be a sub class...) should inherit from one of those classes. Of course you can't inherit from both in C#, but this design makes me suspect that there may be a better overall approach. It is impossible to tell from your code sample though as you don't tell us what you are actually trying to accomplish with these types.
There is one more way: T4 Templates.
See here: http://msdn.microsoft.com/en-us/data/gg558520
The resulting CS file is generated at build time. This means you could potentially loop your classes using refelection and the result would be what you have now manually created in your "SuperClass".
The cool thing really is that the resulting code is generated on the fly and it is typesafe.
Is it worth the effort? I don't know. It really depends what you are doing and why you are doing it.
We use it for instance to translate Func<T1, T2> into "real" delegates and auto-generate wrapper classes that way.
Unfortunately there is no magic ways to do that as multiple type inheritance is not allowed in .NET.
You cannot do this easily in C#. You could inherit from one of the classes, and create delegates for the other, or you can manually create delegates for both (by delegate, I just mean a method that delegates to the member object, not anything to do with the delegate keyword or class).
If you use a product such a Resharper, there is an option in the Refactor menu that will automate this process, called "Create delegates..."
You can make class1 public and then reference them directly:
SuperClass.class1.MethodFirst();
Of course, static methods will be ok, you will have to construct class1 for instance methods.
in C#, you cannot combine class hierarchies the way you can in Java but you can enforce a contract through iterfaces.
Create an interface for Class1 and Class2 then have SuperClass implement those interfaces. You'll still code up the method calls, but at least you'll have some compile-time checking in place. Perhaps you could also Create a method in SuperClass that dispatches to the appropriate class/method using reflection.
Another approach might be to setup an inheritance chain where SuperClass extends Class2 which extends Class1.
The question is rather old already, and there's one more solution available today: Expose.Fody. This is a plugin for Fody, which is a general-purpose IL-weaving tool. To quote the Expose's description,
Exposes members and optionally implements interface of a field declared in class.
All it takes is just decorating the field with an attribute.
I have a class:
public class MyClass {
private List<string> folderList;
// .... a lot of useful public methods here.....
}
Everything is fine. The list of folders is encapsulated, the class is accessible through public methods. OK. Now I need an "options" form that allows a user to choose folders for MyClass. There is a catch: new Setup class must have access to private folderList field (or I have to provide public methods to get and set the folder list - it's essentially the same). In old good C++ I would use 'friend' feature because nobody but Setup class may access folderList. But there is no 'friend' feature in C# (I'm a newbie in the C# world).
P.S. Actually I just made folderList public, but I feel there is a better solution.
Thanks.
You can use "internal" keyword to make your method available only within your assembly/project and if you want to access your internal methods in other project or assembly then you can use "InternalsVisibleTo" attribute, where you can access your internals only in that assembly for which you define this attribute.
MSDN Internal Keyword
I believe the keyword you're looking for is internal. It is loosely equivilent to C++'s friend.
Internal provides assembly-level visibility.
Paired with Femaref's suggestion of using a Property, and you should have your full solution.
I am not sure if this is what he/she wanted. He/she did not put the requirement that the potential client will be in current assembly... Accordingly, when using friend in c++ (which was never considered a good style) you must know the exact type of the class which will be entitled to access the member. If this class is not part of the program you are writing, you cannot grant access this way.
If you want conditional access to some property or method of an instance of a class, you will need to implement some kind of entitlement mechanism, for example:
public IList<Folder> GetFolderList(Object pClient, IEntitlementService pService) {
if (pService.IsEntitledToAccess(this, pClient) {
return folderList;
} else {
throw new AccessNotGrantedException("...");
}
}
I believe there are built-in utilities in the .Net framwork for that purpose, just go and google (or bing)...
As an exact answer to the question I would suggest the following - create a separate interface IFolderList:
interface IFolderList
{
IList<string> FolderList { get; }
...
}
Well, you can add other required members to interface
In the class MyClass implement this interface explicitly.
As a result, the class Setup can gain access to data through an explicit cast to an interface IFolderList or work only with these interface.
An alternative to making an internal method to be used by your Setup class would be to use the Visitor pattern and add a method that takes a Setup class instance as a parameter, then uses the private folderList to initialize/change Setup state as required. Of course that would require the appropriate public methods on the Setup class, so might not fit your needs.
Making folderList field public is the worst case. Exposing implementation details through public fields or through poorly designed public property (there are no differences for collections between public fields and public property with getter and setter).
With public fields you can't promote a field to be a property when you want to add validation, change notification, put it into an interface or change your collection type from one type to another.
BTW, Jeffrey Richter in annotation to Framework Design Guideline mentioned that "Personally, I always make my fields private. I don't even expose fields as internal, because doing so would give me no protection from code in my own assembly"
I think the best way to add explicit interface that expose strict abstraction to MyClass clients.
For example, you may add two separate methods to retrieving folders and to adding new folder to this storage:
class MyClass {
//You should return IList<string>
public IList<string> MyList {get {return myList;} }
//Or even IEnumerable<string>, because you should return
//as minimal interface as your clients needs
public IEnumerable<string> MyList {get {return myList;} }
//You may expose this functionality through internal
//method, or through protected internal method,
//but you should avoid direct access to your implementation
//even for descendants or another classes in your assembly
public void AddElement(string s) {myList.Add(s);}
private List<string> myList;
}
That's what properties are for in C#:
public class MyClass
{
private List folderList;
public List FolderList
{
get {return folderList;}
set {folderList = value;}
}
}
Properties encapsulate the private fields, provide possibilites for validation while setting. Also, you should read up on Generics (abit like templates in c++) and use List<T> instead of List to have a strongly typed collection.
However, you probably wont be able to achieve what you plan unless Setup derives from MyClass. In that case, you can use a protected field.