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
Related
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".
i want to write my own serialisation (xml and binary do not fit for me,
i want "a more ADO" way)
so i defined an interface:
interface ISerializeData
{
DataTable GetDataSchema();
DataTable SerializeData();
object DeserializeData(DataTable data);
}
now i do not want to create an instance of an object to let
me get the schema for that object.
And: DeserializeData should return an instance, not use an instance.
Therefore i think it should be also static. (okay, it can initialize
an instancce from a datatable...)
Any ideas? How can i model that? static is not allowed in
interfaces and my classes already inherit from another abstract
base class.
Any ideas appreciated!
that issue is why the other serializer utilize attributes as they allow you to provide metadata about how the class is to be stored with out forcing you to deal with the implementation of the class itself.
Maybe I'm wrong, but this is really more a task for a utility class. Take DeserializeData, for instance. Somewhere in your code you decide which type you're going to construct. In your proposed code you would choose the type and call its static method. Now what? Would each type have its own code to do the serialization? You'd probably end up creating some class doing all the work, to stay DRY. So you might as well have one DeserializeData method in a utility class, like:
public static T DeserializeData(DataTable data)
where T : new
{
var T = new T();
.... // Set properties
}
In this method you'd probably get the data schema.
Maybe SerializeData() could be an instance method, but that too would delegate its work to some utilty class.
Please let me know if I completely misunderstood your question.
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 method
private object SetGrid(IGrid grid)
{
grid.PagerHelper.SetPage(1, 10);
grid.SortHelper.SetSort(SortOperator.Ascending);
grid.PagerHelper.RecordsPerPage = 10;
return grid;
}
which returns an object of type object.
Then I cast the object back to the previous type.
var projectModel = new ProjectModel();
projektyModel = (ProjectModel)SetGrid(projectModel);
The gain of this is, the method SetGrid can be reused across the app.
Is this a common practice or should I avoid doing this ?
You could use a generic method instead, and constrain the type argument to your IGrid interface:
private T SetGrid<T>(T grid) where T : IGrid
{
grid.PagerHelper.SetPage(1, 10);
grid.SortHelper.SetSort(SortOperator.Ascending);
grid.PagerHelper.RecordsPerPage = 10;
return grid;
}
You should still be able to call the method in exactly the same way, just without the cast. Type inferencing should be capable of automagically figuring out the required generic type argument for you:
var projectModel = new ProjectModel();
projektyModel = SetGrid(projectModel);
EDIT...
As other answers have mentioned, if your IGrid objects are reference types then you don't actually need to return anything at all from your method. If you pass a reference type then your method will update the original object, not a copy of it:
var projectModel = new ProjectModel(); // assume that ProjectModel is a ref type
projektyModel = SetGrid(projectModel);
bool sameObject = object.ReferenceEquals(projectModel, projektyModel); // true
Since you are passing in an object of a class that implements IGrid you could just as well change the return type to IGrid.
Also, since it's a reference type you don't even need to return the grid again. You could just as well use this:
var projectModel = new ProjectModel();
SetGrid(projectModel);
This is better accomplished with generics. You can use a constraint on the generic typeparam to preserve your type safety!
private T SetGrid<T>(T grid) where T : IGrid
{
grid.PagerHelper.SetPage(1, 10);
grid.SortHelper.SetSort(SortOperator.Ascending);
grid.PagerHelper.RecordsPerPage = 10;
return grid;
}
and then
var projectModel = new ProjectModel();
projectModel = SetGrid(projectModel);
Here, the generic typeparam "T" is actually inferred by the compiler by the way you call the method.
It's worth noting that in the particular use-case you've demonstrated, returning grid is probably unnecessary, as your original variable reference will be appropriately modified after the method call.
In the case you illustrate above there is no need to return grid. The IGrid instance is passed by reference, so your projectModel reference will be updated with the changes you've made in the SetGrid method.
If you still want to return the argument, at least return IGrid, since it is already known that the argument is an IGrid.
In general, provide as much type information as you can when programming in a statically typed language/manner.
"Is this a common practice or should I avoid doing this ?"
This is not common practice. You should avoid doing this.
Functions that only modify the parameter passed in should not have return types. If causes a bit of confusion. In the current C# you could make the modifying function an extention method for better read-ability.
It causes an unnecisary cast of the return type. It's a performance decrease, which may not be noticable... but its still needless since you are casting from an interface, return that interface even if the object is different from the parameter passed in.
Returning object is confusing to users of the function. Lets say the function created a copy and returned a copy... you would still want to return the interface passed in so that people using the function know "hey i'm getting an IGrid back." instead of having to figure out what type is being returned on thier own. The less you make your team mates think about stuff like this the better, for you and them.
This is a very weird example because SetGrid doesn't seem to do a lot of things other than setting some defaults. You are also letting the code perform manipulation on the object that could very well do that by itself. Meaning IGrid and ProjectModel could be refactored to this:
public interface IGrid {
// ...
public void setDefaults();
// ...
}
public class ProjectModel : IGrid {
// ...
public void setDefaults() {
PagerHelper.SetPage(1, 10);
SortHelper.SetSort(SortOperator.Ascending);
PagerHelper.RecordsPerPage = 10;
}
// ...
}
Using this refactoring you only need perform the same with this:
myProjectModel.setDefaults();
You could also create an abstract base class that implements IGrid that implements the setDefaults() method and let ProjectModel extend the abstract class.
what about the SOLID principles ? Concretely the Single Responsibility Principle. The class is in the first place something like a DTO. – user137348
I'm exercising the Interface Segregation Principle out of the SOLID principles here, to hide the implementation from the client of the class. I.e. so the client doesn't have to access the internals of the class it is using or else it is a violation of Principle of Least Knowledge.
Single Responsibility Principle (SRP) only tells that a class should only have one reason to change which is a very vague restriction since a change can be as narrow and broad as you want it to be.
I believe it is okay to put some configuration logic in a parameter class if it is small enough. Otherwise I'd put it all in a factory class. The reason I suggest this solution is because IGrid seems to have reference to PagerHelper and SortHelper that seem to be mutators for IGrid.
So I find it odd that you mention the class being a DTO. A DTO from a purist sense shouldn't have logic in it other than accessors (i.e. getter methods) which makes it strange that ProjectModel itself has references to PagerHelper and SortHelper which I assume can mutate it (i.e. they're setters). If you really want SRP the "helpers" should be in a factory class that creates the IGrid/ProjectModel instance.
Your grid is an IGrid, why not return IGrid?
I hit this problem all the time. Suppose I am making a command line interface (Java or C#, the problem is the same I think, I will show C# here).
I define an interface ICommand
I create an abstract base class CommandBase which implements ICommand, to contain common code.
I create several implementation classes, each extending the base class (and by extension the interface).
Now - suppose that the interface specifies that all commands implement the Name property and the Execute method...
For Name each of my instance classes must return a string that is the name of that command. That string ("HELP", "PRINT" etc) is static to the class concerned. What I would love to be able to do is define:
public abstract static const string Name;
However (sadly) you cannot define static members in an interface.
I have struggled with this issue for years now (pretty much any place I have a family of similar classes) and so will post my own 3 possible solutions below for your votes. However since none of them is ideal I am hoping someone will post a more elegant solution.
UPDATE:
I can't get the code formatting to work properly (Safari/Mac?). Apologies.
The example I am using is trivial. In real life there are sometimes dozens of implementing classes and several fields of this semi-static type (ie static to the implementing class).
I forgot to mention - ideally I want to be able to query this information statically:
string name = CommandHelp.Name;
2 of my 3 proposed solutions require that the class be instantiated before you can find out this static information which is ugly.
You may consider to use attributes instead of fields.
[Command("HELP")]
class HelpCommand : ICommand
{
}
As you mentioned, there is no way to enforce this from the interface level. Since you are using an abstract class, however, what you can do is declare the property as abstract in the base class which will force the inheriting class it override it. In C#, that would look like this:
public abstract class MyBaseClass
{
public abstract string Name { get; protected set; }
}
public class MyClass : MyBaseClass
{
public override string Name
{
get { return "CommandName"; }
protected set { }
}
}
(Note that the protected set prevents outside code changing the name.)
This may not be exactly what you're looking for, but it's as close as I think you can get. By definition, static fields do not vary; you simply can't have a member that is both static and overridable for a given class.
public interface ICommand {
String getName();
}
public class RealCommand implements ICommand {
public String getName() {
return "name";
}
}
Simple as that. Why bother having a static field?
Obs.: Do not use a field in an abstract class that should be initiated in a subclass (like David B suggestion). What if someone extends the abstract class and forget to initiate the field?
just add the name property to the base class and pass it ito the base class's constructor and have the constuctor from the derived class pass in it's command name
What I usually do (in pseudo):
abstract class:
private const string nameConstant = "ABSTRACT";
public string Name
{
get {return this.GetName();}
}
protected virtual string GetName()
{
return MyAbstractClass.nameConstant;
}
----
class ChildClass : MyAbstractClass
{
private const string nameConstant = "ChildClass";
protected override string GetName()
{
return ChildClass.nameConstant;
}
}
Of course, if this is a library that other developers will use, it wouldn't hurt if you add some reflection in the property to verify that the current instance in fact does implement the override or throw an exception "Not Implemented".
My answer will relate to Java, as that is what I know. Interfaces describe behavior, and not implementation. Additionally, static fields are tied to the classes, and not instances. If you declared the following:
interface A { abstract static NAME }
class B { NAME = "HELP" }
class C { NAME = "PRINT" }
Then how could this code know which NAME to link to:
void test(A a) {
a.NAME;
}
How I would suggest to implement this, is one of the following ways:
Class name convention, and the base class derives the name from the class name. If you wish to deviate from this, override the interface directly.
The base class has a constructor which takes name
Use annotations and enforce their presence through the base class.
However, a much better solution is proabably to use enums:
public enum Command {
HELP { execute() }, PRINT { execute() };
abstract void execute();
}
This is much cleaner, and allows you to use switch statements, and the NAME will be easily derived. You are however not able to extended the number of options runtime, but from your scenario description that might not be even needed.
[Suggested answer # 3 of 3]
I have not tried this yet and it would not be so nice in Java (I think?) but I could just tag my classes with Attributes:
[CammandAttribute(Name="HELP")]
Then I can use reflection to get that static information. Would need some simple helper methods to make the information easily available to the clients of the class but this could go in the base class.
From a design perspective, I think it is wrong to require a static implementation member... The relative deference between performance and memory usage between static and not for the example string is minimal. That aside, I understand that in implementation the object in question could have a significantly larger foot print...
The essential problem is that by trying to setup a model to support static implementation members that are avaialble at a base or interface level with C# is that our options are limited... Only properties and methods are available at the interface level.
The next design challenge is whether the code will be base or implementation specific. With implementation your model will get some valdiation at compile time at the code of having to include similar logic in all implementations. With base your valdiation will occur at run time but logic would be centralized in one place. Unfortunately, the given example is the perfect show case for implemntation specific code as there is no logic associated with the data.
So for sake of the example, lets assume there is some actual logic associated with the data and that it is extensive nad/or complex enough to provide a showcase for base classing. Setting aside whether the base class logic uses any impelementation details or not, we have the problem of insuring implemtation static initialization. I would recommend using an protected abstract in the base class to force all implementations to created the needed static data that would be valdated at compile time. All IDE's I work with make this very quick any easy. For Visual Studio it only takes a few mouse clicks and then just changing the return value essentially.
Circling back to the very specific nature of the question and ignoring many of the other design problems... If you really must keep this entire to the nature of static data and still enforce it thru the nature confines of the problem... Definately go with a method over properties, as there are way to many side effects to make go use of properties. Use a static member on the base class and use a static constructor on the implementations to set the name. Now keep in mind that you have to valdiate the name at run-time and not compile time. Basically the GetName method on the base class needs to handle what happens when an implementation does not set it's name. It could throw an exception making it brutally apparent that something is worng with an implementation that was hopefulyl cause by testing/QA and not a user. Or you could use reflection to get the implementation name and try to generate a name... The problem with reflection is that it could effect sub classes and set up a code situation that would be difficult for a junior level developer to understand and maintain...
For that matter you could always generate the name from the class name thru reflection... Though in the long term this could be a nightmare to maintain... It would however reduce the amount of code needed on the implementations, which seems more important than any other concerns. Your could also use attributes here as well, but then you are adding code into the implementations that is equivalent in time/effort as a static constructor and still have the problem off what todo when the implementation does not include that information.
What about something like this:
abstract class Command {
abstract CommandInfo getInfo();
}
class CommandInfo {
string Name;
string Description;
Foo Bar;
}
class RunCommand {
static CommandInfo Info = new CommandInfo() { Name = "Run", Foo = new Foo(42) };
override commandInfo getInfo() { return Info; }
}
Now you can access the information statically:
RunCommand.Info.Name;
And from you base class:
getInfo().Name;
[Suggested solution #1 of 3]
Define an abstract property Name in the interface to force all implementing classes to implement the name property.
(in c#) Add this property as abstract in the base class.
In the implementations implement like this:
public string Name
{
get {return COMMAND_NAME;}
}
Where name is a constant defined in that class.
Advantages:
Name itself defined as a constant.
Interface mandates the property be created.
Disadvantages:
Duplication (which I hate). The exact same property accessor code pasted into every one of my implementations. Why cant that go in the base class to avoid the clutter?
[Suggested solution #2 of 3]
Make a private member variable name.
Define an abstract property Name in the interface.
Implement the property in the base class like this:
public string Name
{
get {return Name;}
}
Force all implementations to pass name as a constructor argument when calling the abstract base class constructor:
public abstract class CommandBase(string commandName) : ICommand
{
name = commandName;
}
Now all my implementations set the name in the constructor:
public class CommandHelp : CommandBase(COMMAND_NAME) {}
Advantages:
My accessor code is centralised in the base class.
The name is defined as a constant
Disadvantages
Name is now an instance variable -
every instance of my Command classes
makes a new reference rather than
sharing a static variable.