interface & inheritance - c#

C#, VS 2008
I have 4 cases say a,b,c,d, I plan to seperate them and create seperate classes
the 4 cases have something in common, I put them in an interface and create a base class that implement the interface. now there are something in common between a&b, a&c, c&d, not sure how to make a good/clean implement
thanks

There are several options.
You could have c and d inherit from a, and d inherit from c.
You could create a base class for each pair a/b, a/c, and c/d.
You could duplicate functionality.
You could provide the functionality via a helper class (static methods might be an option).
It really depends on what functionality is being shared, and the intended usage of the classes.

It depends on how the common things works and how they relate to and use private/protected data, but often composition can be a complement or alternative to inheritance.
Break out the common parts to helper classes that you use from the different implementations of a,b,c and d.
This is only possible if the implementation is not tightly coupled to the private data of each class.

As a general rule, you should only use inheritance if your objects are different kinds of the same object. If this is the case, then you can use inheritance to share implementation that's inherent in the definition of the base object.
If classes a,b,c and d aren't really different kinds of the same object then you can try encapsulating their common functionality in an internally referenced object.
public class a
{
private CommonFunctionalityClass commonFunc;
public a()
{
this.commonFunc = new CommonFunctionalityClass();
}
}
When you want to do the common stuff, you just call your instance of commonFunc. You can do this same encapsulation for a/b, b/c, and c/d where you share functionality via a has a relationship using an internally referenced object. That way you don't duplicate code, but you can share functionality flexibly.

public interface IABInterface
{
//Whatever is common to A and B. It will have to be implemented in the classes
}
public interface IACInterface
{
//Whatever is common to A and C. It will have to be implemented in the classes
}
public interface ICDInterface
{
//Whatever is common to C and D. It will have to be implemented in the classes
}
public class ABCDBase
{
//Whatever is common to all classes
}
public class A : ABCDBase, IABInterface, IACInterface
{
}
public class B : ABCDBase, IABInterface
{
}
public class C : ABCDBase, IACInterface, ICDInterface
{
}
public class D : ABCDBase, ICDInterface
{
}
You can create later in a static class extension methods for your interfaces to not duplicate the code for your methods in the Interfaces implementations (In other words, don't define methods in your interfaces, only properties). With refactoring can be really easy to implement the properties in your interfaces.
It would be nice to have extension properties. Hopefuly in the future.
EDIT
Like this:
public static class Helper
{
public static void IABMethod1(this IABInterface aOrBObject, arguments args)
{
//This will be available for any A or B object without duplicating any code
}
}

Related

Base class or common class?

for our asp.net web application v 4.0, we are in process of defining a class that contains methods that are common across the application. to achieve this there are 2 Suggestions within our team.. one to create a base class, define the methods in that and derive all the other classes from that base class.. the other one is to create a seperate class (not a base class) and instantiate that common class in other classes when required to access the common methods. Please guide me in identifying the best approach..
I'd only go the base class route if there is a real is-a relationship between the base class and the derived classes. One reason is that a class can only inherit from a single base class. I'd use this relationship in a sensible way. Just sharing some helper methods is not a scenario worth blocking this relationship.
If you want to use some helper methods in several classes, composition is the better way as you describe in the 2nd approach. Instead of creating the objects in the classes, you should think about whether you can inject the instances into the classes (see this link for details on dependency injection), e.g.:
public class HelperClass
{
public virtual void HelperMethod()
{
// ...
}
}
public class ClassThatUsesHelper
{
private readonly HelperClass _helper;
public ClassThatUsesHelper(HelperClass helper)
{
_helper = helper;
}
public void DoSomething()
{
_helper.HelperMethod();
}
}
By injecting the helper class you decouple the classes so that you can substitute the helper class by a different implementation that shares the same interface. ClassThatUsesHelper works with any class that is derived from HelperClass (or HelperClass itself of course). So if you need to decorate the helper method or need a special implementation in some cases, this is possible without any problem.
Using composition also enables you to test the helper methods separately.
However, if it is about very basic helper methods, you might also think about having a static class with static helper methods. Please note that you introduce a strong dependency between the classes and that you cannot adjust the implementation easily.
public static class HelperClass
{
public static void HelperMethod()
{
// ...
}
}
public class ClassThatUsesHelper
{
public void DoSomething()
{
HelperClass.HelperMethod();
}
}
Your question is vague, but if you need a method which all objects in your program will need to have access to, that uses their member variables, then I wold recommend creating an abstract class upon which your objects are based.
If you need a means of performing some sort of calculation from anywhere in your code, just create a public static method in a class meant for the purpose. MyMathClass.InterestingFourierTransform(), for example.

Adding private method to class by inheritance in C#

I asked this question yesterday, but I think it was unclear what my primary concern was. In C++, we have private and multiple inheritance, which enables us to add private methods to classes by just inheriting from the class declaring these methods. That is, if there's a class
class B {
public:
virtual void doMethodB();
};
and a class
class A : private B {
virtual int doMethodA();
};
doMethodB() can be called from within doMethodA(), but is not accessible from outside.
Now, I'd like to mimic this behavior in C#. There is no multiple nor private inheritance. Up to know, I can think of four way to achieve somthing similar, but still with serious drawbacks:
First: Use an interface, i.e.
interface IB {
public void doMethodB();
};
class A : IB {
public void doMethodB();
int doMethodA();
};
However, when we do this, doMethodB() is public, and must be implemented in each class inheriting from IB.
Second: Use a static method
public static class B {
public static void doMethodB();
};
That way, there need only be one implementation, but the method is still public and can't be restricted to certain classes.
Third: Use a extension method, like that. That way however, the method is called on the object (i.e. a.doMethodB()) and not from "inside".
Fourth: Composition.
class A {
private B b;
public int doMethodA();
};
Now, B's methods can be called like b.doMethodB() from A only, but are other issues now regarding serialization, b == null etc.
Is there another alternative? And if not, which one among the presented ones would you consider "the best"?
Regarding your "First" proposal with interfaces: you can also implement the interface explicitly:
"A class that implements an interface can explicitly implement a member of that interface. When a member is explicitly implemented, it cannot be accessed through a class instance, but only through an instance of the interface. "
See / Source: http://msdn.microsoft.com/en-us/library/aa288461%28v=vs.71%29.aspx
However, i would choose the Composition approach. "Favor Composition over Inheritance", also see Prefer composition over inheritance?
Ideally, i would constructor-inject B into A by dependency injection, that should help mitigate your b == null concern.
Note:
Using a static method / extension method (is a static method, too...) makes unit-testing A (respectively faking B) very hard, which is why i would forgo these solutions completely.
Edit:
If you don't need B.doMethodB accessible from anyone else than A, you can also make B an abstract class and B.doMethodB a protected method.
But i was thinking that you already know that ;-)
(And because of the testing issues i would still favor composition over inheritance).
I think the concept you are looking for is the protected access modifier. It means that only B itself and its derived classes can access the method, but others cannot.
class B {
protected virtual void DoMethodB() {}
}
class A : B {
virtual void DoMethodA() {
DoMethodB();
}
}
If you wanted, you can further restrict the access to protected internal which means that the method can only be accessed from derived classes inside your assembly.
Also, be aware of the consequences of virtual methods. If there is no explicit need to make a method virtual, it should not be marked virtual.

How can subclasses share behavior when one already derives from a different base class?

I have two classes that implement ISomeBehavior. Now I want them to share functionality. Normally I would replace ISomeBehavior with an abstract class, like SomeBehaviorBase. The problem is that one of the subclasses already derives from another class, and that other class isn’t software we own. (This is C#, so multiple inheritance isn't an option.) The subclass, that derives from the 3rd party class, has no implementation. It simply derives from the 3rd party class, and implements ISomeBehavior, so the 3rd party class can be treated the same way as the other subclasses that implement ISomeBehavior.
What I've done, for the moment, is implement an extension method on ISomeBehavior. Now the consuming code can call the method. The problem with that approach is that I want to force the calling code to use this extension method. I can't remove SomeMethod() from the interface, because the extension method has to eventually call it.
Any ideas on how to let two classes elegantly share the same behavior, when one of them already derives from another, third party, class? Note: The strategy design pattern sounds like it makes sense here, but that pattern is used when behavior varies among subclasses. The behavior here doesn't vary; it just needs to be shared.
Is there any reason you can't use composition instead of delegation to implement the class which currently derives from the 3rd party class? Just delegate all the interface methods to an instance of the third party class. That way, if you want to add functionality you can use a common base class.
This won't work in some cases where the object identity is relevant, but in many cases it's a perfectly reasonable design.
public interface ISomeBehavior
{
int Sample();
}
public class A : ISomeBehavior
{
int ISomeBehavior.Sample()
{
return 1;
}
}
static class SomeExtension
{
public static int Sample(this ISomeBehavior obj)
{
return 2;
}
}
and then use this
A a = new A();
var a1 = ((ISomeBehavior)a).Sample(); // a1 = 1
var a2 = a.Sample(); // a2 = 2
How about something like this:
class MyClass: ThirdPartyClass
{
}
class MyFunctionality
{
public MyFunctionality(ThirdPartyClass target)
...
}
interface IMyFunctionality
{
public MyFunctionality MyFunctionality;
}
So the interface would enforce that the derived class has to instantiate the add-on member, and the design of MyFunctionality would just operate against a reference to the base class. This might not work if there are protected members that you need internal access to, though.

Interfaces vs. inheritance: which is better in this case?

Let's suppose I have a widget class:
struct Widget {
public Color Color { get; set; }
public int Frobbles { get; set; }
}
Now, I need to make a factory to create these widgets, so I build a WidgetFactory:
abstract class WidgetFactory {
public virtual Widget GetWidget();
}
As it turns out, you can make widgets out of several different materials, but the resulting widgets are pretty much the same. So, I have a few implementations of WidgetFactory:
class GoldWidgetFactory : WidgetFactory {
public GoldWidgetFactory(GoldMine goldmine) {
//...
}
public Widget GetWidget() {
Gold g = goldmine.getGold();
//...
}
}
class XMLWidgetFactory : WidgetFactory {
public XMLWidgetFactory(XmlDocument xmlsource) {
//...
}
public Widget GetWidget() {
XmlNode node = //whatever
//...
}
}
class MagicWidgetFactory : WidgetFactory {
public Widget GetWidget() {
//creates widget from nothing
}
}
My question is this: Should WidgetFactory be an abstract class, or an interface? I can see arguments in both directions:
Base class:
The implementations ARE WidgetFactories
They might be able to share functionality, (say, a List<Widget> WidgetFactory.GetAllWidgets() method)
Interface:
The implementations do not inherit any data or functionality from the parent
Their internal workings are completely different
Only one method is defined
To those answering, this does not (currently) parallel to any real-world problem, but if/when I need to implement this pattern, it would be good to know. Also, "it doesn't matter" is a valid answer.
Edit: I should point out why go through this in the first place. The hypothetical usage of this class hierarchy would be something like:
//create a widget factory
WidgetFactory factory = new GoldWidgetFactory(myGoldMine);
//get a widget for our own nefarious purposes
Widget widget = factory.GetWidget();
//this method needs a few widgets
ConsumeWidgets(factory);
So, having a GetGoldWidget() method in WidgetFactory is not a very good idea. Plus, perhaps advents in Widget technology allow us to add different and more exotic types of widgets in the future? It's easier and cleaner to add a new class to handle them than shoehorn a method into an existing class.
In the example that you have given WidgetFactory has absolutely no reason to be an abstract class since there are not shared attributes or methods between different implementations of the factory.
Even if there was shared functionality, it would be more idiomatic to make an interface and pass it around to the users of WidgetFactory, to reduce the mount of knowledge those components need to have about the factory.
The overall implementation is fine and is really an abstract factory pattern, the only addition I would do is IWidgetFactory:
public interface IWidgetFactory {
Widget GetWidget();
}
abstract class WidgetFactory : IWidgetFactory {
//common attributes and methods
}
//Defferent implementations can still inherit from the base abstract class
class GoldWidgetFactory : WidgetFactory {
public GoldWidgetFactory(GoldMine goldmine) {
//...
}
public Widget GetWidget() {
Gold g = goldmine.getGold();
//...
}
}
In this case I see no benefit to using an abstract class instead of an interface.
I would generally favour interfaces over abstract classes:
They don't use up your one opportunity at class inheritance
They can be easier to mock
They feel "purer" somehow (it's clear just from the interface what the implementer needs to provide; you don't need to check each method to see whether or not it's concrete, abstract, or virtual)
In this case, however, you could easily use a delegate as there's only a single method... basically a Func<Widget>.
I disagree with Larry's idea of just using a single factory to directly create all the widgets with separate methods - as you may want to pass the WidgetFactory as a dependency to another class which doesn't need to know about the source, but needs to call CreateWidget either at a different time or possibly multiple times.
However, you could have a single widget factory with multiple methods each returning a Func<Widget>. That would give the benefits of having a single factory class while also allowing for dependency injection of the "factory" notion.
Honestly, what ever else, besides the Concrete Factory classes, do you expect to inherit from WidgetFactory? Anything?... ever?
If not it probably doesn't ever matter.
If down the road you want to add common code between them all than an abstract class would be your best bet.
Also I don't really see the need for your factory methods to implement any other interface except that of your creation method. So it doesn't matter whether it's abstract or interface. It all comes down to whether in the future you will want to add additional functionality in the future to the abstract class.
You don't need inheritance or an interface or even more than one class. The single factory should make all different kinds of widgets ; you can just pass in the materials as a parameter to the create method. The idea is to hide the aspects of different construction of objects from the caller - by making a bunch of different classes you are exposing this, not hiding it.

Combine the functions of two different base classes

I'm trying to combine the functions of two different base classes into a new class, to no avail. Say I have class A and B, whereas B is a descendant of A with different functionality (i.e. can't be used as a substitute for A during runtime) and need a class C, which combines A and B, uses both and provides a unique interface to users of C. How can I achieve this? Multiple inheritance isn't possible with C#, interfaces don't seem to fit. So what can I do?
Your design is broken.
B is a descendant of A with different functionality (i.e. can't be used as a substitute for A during runtime)
That situation is a mis-use of inheritance. If you want to do that, you should either use composition or a common interface that both A & B implement separately instead.
Consider explicit interface implementation:
http://msdn.microsoft.com/en-us/library/ms173157.aspx
public interface IFriendly
{
void Greet();
}
public interface IEnemy
{
void Greet();
}
public class SomeGuy : IFriendly, IEnemy
{
//default Greeting
public void Greet()
{
//...
}
//greeting when using an IFriendly reference
void IFriendly.Greet()
{
//,,
}
//greeting when using an IEnemy reference
void IEnemy.Greet()
{
//,,
}
}
You say that B descends from A but is different and cannot be used as an A; this defies the purpose of inheritance altogether. What are you trying to achieve? Regardless, it sounds as though you should be using composition, not inheritance. If C does not expose the interface defined by A or B, then it should not inherit from either.
The fact that you need to consider such an action makes me think that you might need to consider refactoring your class structure.
But, to solve your immediate problem why not instantiate the two classes (ignore the fact that they are in an inheritance relationship) and call the methods in the sequence you need? Think of C as a facade pattern for A and B.
Problem solved. Using System.Reflection now.

Categories

Resources