a question about class design. Currently I have the following structure:
abstract Base Repository Class
Default Repository implementation class (implements some abstract methods, where logic is common thru all of the Specific classes but leaves other empty)
Specific Repository implementation Class (implements what is left empty in the above Default class)
I've now came to the problem where I have a specific Update() method in Specific class but when all the code in this method executes some code from the base Default class should be executed too.
I could do it like this
public override Update()
{
// do Specific class actions and updates
// ....
// follow with base.Update()
base.Update();
}
but this requires those base.XYZ() calls in all the inherited methods. Could I go around that somehow with partials?
So the requirement is to have code in both parent and inherited class (or to make those two one class using partials) and code from method implementation in both places should be executed. Also what about if I wanted to turn it around and execute base class code first followed by the inherited class code?
thanks
Have you considered something like:
public abstract class YourBaseClass
{
public void Update()
{
// Do some stuff
//
// Invoke inherited class's method
UpdateCore();
}
protected abstract void UpdateCore();
}
public class YourChildClass : YourBaseClass
{
protected override void UpdateCore()
{
//Do the important stuff
}
}
//Somewhere else in code:
var ycc = new YourChildClass();
ycc.Update();
All the partial keyword means is that the definition of the class is split between source files:
It is possible to split the definition of a class or a struct, an interface or a method over two or more source files. Each source file contains a section of the type or method definition, and all parts are combined when the application is compiled.
There still has to be a complete definition of the class in the project.
You'd be better off creating a subclass, that way you can override specific methods.
As far as partial methods go (from the same link as above):
A partial method declaration consists of two parts: the definition, and the implementation. These may be in separate parts of a partial class, or in the same part. If there is no implementation declaration, then the compiler optimizes away both the defining declaration and all calls to the method.
// Definition in file1.cs
partial void onNameChanged();
// Implementation in file2.cs
partial void onNameChanged()
{
// method body
}
You can't have half the method in one file and the other half in another.
Here's how you can do this:
public sealed override void Update()
{
UpdateCore();
base.Update();
}
public abstract /* or virtual */ void UpdateCore()
{
// Class-specific stuff
}
Forget about partial, that has entirely different semantics. Whether the overrider of your virtual base class method should call the base class method is not automatic. It needs to be part of your documentation. A good example are the OnXxxx() methods in the Control class, the MSDN library docs have a "Note to implementer" comment that warns that calling the base class method is usually necessary.
If you make the base class method abstract then it is crystal-clear to the overrider. If it is not, you are dropping a strong hint that it ought to be done. If you expect the override to completely replace your base implementation then you should really consider making it abstract. This ambiguity, combined with the odds that the overrider breaks your base class by overriding incorrectly, is definitely one of the weak points of polymorphism.
Add a new virtual (not abstract, since not all specific implementation need to override it?) method to your Default implementation to accommodate inheritors having their own additional steps on top of it's own implementation.
Call the virtual method at the appropriate point in the Default Implementation's abstract method implementation.
You've left your abstract class as it is and transparently grown the flexibility of the default implementation.
Related
I hope this isn't a duplicate but I can't find one via Google or SO search. If I want to force the accessibility for a method's implementation of an overridden method to be protected, is my only option to either create as abstract or protected virtual? I know that interfaces specify the declaration but leave the accessibility/scope to the class implementation but I'd like to be sure.
I'd like to know/be certain of if the only way to limit the scope of a method is via a abstract \ protected virtual to give semantics of "this applies to the class implementation or the child override implementation".
A code sample to illustrate. I know I can do the following and limit the scope of an implementation like so;
public class BaseClass
{
protected virtual void OnlyMeOrChildrenCanDoAction()
{
// leave empty as current class is structural/conceptual
// but child instances may need it
}
}
By doing the above I guarantee that child implementations can only override OnlyMeorChildrenCanDoAction()as protected but not public.
But is there another way of limiting to protected without resorting to abstract or protected virtual? An example of creating a method like this is Object.Finalize() as seen here.
Or, to invert the question somewhat, why would you create a method as protected virtual unless to ensure that any implementations were limited in scope? Or is there another way to do the same?
I think you're misunderstanding the meaning and use of virtual. You can only override a method in the parent class if it is declared virtual. The override method in the child class must have the same visibility as the method in the parent class.
Implementations of methods declared in interfaces are always public.
Declaring a method abstract has the same effect as declaring it virtual, except you do not implement it in your class and any concrete classes that derive from your class must implement it.
Technically, the compiler will not allow you to change the access modifiers of a method when overriding it from the parent, so the answer to the question is that by declaring a method as protected within a class, you are only making it available to derived classes (whether abstract or not is a separate concern and doesn't bear on the access level).
Keep in mind, however, that derived class would be free to expose the function in some other way such as calling the protected method from a public one and there is no way to prevent that.
As far as "why" you would have a protected abstract member, a great example can be seen in many implementations of the Template Method pattern. You may have an abstract base class that describes the structure of an algorithm and leave the specific steps of what happens inside the boundary of each step to derived classes. In this case, one way to implement would be to declare the base class as abstract, have a public method serve as the "entry point" for the algorithm, and define specific methods used within the algorithm as protected abstract methods to lay out what the responsibility of derived classes will be. This pattern does a nice job of leaving public only those things that are intended to be consumed by the world, but can present some challenges from a unit testing perspective which are sometimes addressed by raising the visibility of the helper methods from protected to internal.
You cannot use the c# language to prevent a derived class from implementing a public version of OnlyMeOrChildrenCanDoAction. Even if you mark it as protected virtual, the derived class can use the new keyword to cover the method and change its accessibility. For example:
public class BaseClass
{
protected virtual void OnlyMeOrChildrenCanDoAction()
{
// leave empty as current class is structural/conceptual
// but child instances may need it
}
}
public class DerivedClass : BaseClass
{
public new void OnlyMeOrChildrenCanDoAction()
{
Console.WriteLine("This is public.");
}
}
public class Program
{
public static void Main()
{
var b = new BaseClass();
//b.OnlyMeOrChildrenCanDoAction(); //Will not compile
var d = new DerivedClass();
d.OnlyMeOrChildrenCanDoAction(); //Look! It's public!
}
}
Output:
This is public.
Code available on DotNetFiddle.
If you want to protect the caller from calling OnlyMeOrChildrenCanDoAction, your best bet is for the caller to use only interfaces. If OnlyMeOrChildrenCanDoAction isn't in the interface, there is no way a caller could call it, even if a derived class decided to expose it as a public class member. This is good SOLID design anyway.
On the other hand, if you're not so much worried about the caller as you are worried about your own development team doing bad things, perhaps your best option is to use FxCop or some other source code rules engine integrated into your continuous build process. Developers could still add the method but you could set up a rule to cause it to fail the build if they do so.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have a class A which derives from class B:
public class B
{
protected void Run() // pass data here used by all 3 Run methods
{
BeforeRun();
RunInternal();
AfterRun();
}
private void RunInternal()
{
}
private void BeforeRun()
{
}
private void AfterRun()
{
}
}
public class A : B
{
}
What is the nearest achievement I can get to force the user who inherits from class B MUST call the base method Run() ?
Add protected, virtual, abstract, etc... where you want, I am free to do changes where you suggest.
You can't require someone to call a method, except for the constructor. But a class's behavior shouldn't be in the constructor or called from the constructor. A class shouldn't start doing something just because we instantiated it. It should do something when we call its methods.
When we design a class it typically has one or two methods which are the primary responsibility of that class. Whoever creates an instance of the class is going to call one or more of those methods because that's the only reason why the class exists.
Instead of adding another method and expecting others to call it, you design the class so that the primary methods cannot be overridden. The only public methods are in the base class. The methods that get overridden aren't public. That way the base class methods always get called, and if there's something you want the base class to always do, it always gets done.
That way other classes don't change the required base class behavior. They only extend it.
public abstract class TheBaseClass
{
public void DoSomething()
{
AlwaysDoThis();
InheritedClassBehavior();
}
private void AlwaysDoThis()
{
//This method in the base class always gets called.
//You don't need to explicitly require someone
//to call it.
}
protected abstract void InheritedClassBehavior();
}
public class TheInheritedClass : TheBaseClass
{
protected override void InheritedClassBehavior()
{
//The inherited class has its own behavior here.
//But this method can't be called directly because
//it's protected. Someone still has to call
//DoSomething() in the base class, so AlwaysDoThis()
//is always called.
}
}
InheritedClassBehavior is protected, so nothing can call it directly. The only way to call it is by calling DoSomething, which will always call the method in the base class, AlwaysDoThis().
InheritedClassBehavior is abstract, so inherited classes must implement it. Or you could make it virtual - it has an implementation in the base class but an inherited class can override it. (If there aren't any abstract methods then the base class doesn't need to be abstract. The base class would only be abstract if you want to prevent creating instances of the base class, only allowing creation of inherited classes.)
Your best option is to have a base implementation in A (so make it virtual), and only override it in the derived classes if they need to change the behavior of Run().
Anything that calls Run() will get the base implementation unless there has been an override supplied. There is no way you can force the override to call the base, classical OO simply doesn't work like that.
You should also be careful of calling a virtual method from a constructor - Resharper will warn you about this (because an override may get called, and this is unknown to the base implementation).
But other than that, there is no way within C# to force a derived class to call a particular method - a derived class extends the base class, so to force this sort of behavior would break basic OO concepts. Even if you put the calls into a constructor in the base class there is no guarantee that a derived class will invoke that constructor. You can force the base class to call the derived class (use an abstract base method, this must be implemented in the derived class), the derived method can then call back to a base method; but this in itself is a bit of a work around that is really a waste of time unless some of the derived classes are actually going to add some functionality to Run().
One other approach to consider is to use a product like PostSharp - it allows you to use attributes on methods to achieve a cross cutting pattern. This still doesn't force a derived class to call base implementations, but it may be a convenient way to achieve what you are wanting (cross cutting is used for auditing or logging patterns, where a specific method must be called when another method is invoked).
i have a question, why there is a partial class and a virtual method in c#?
i mean what is the difference when i have a normal or abstract class and then inherit from it or make it partial?
the other question is why i need virtual methods? when i inherit from a class i also can override the method if i want.
Partial classes: they're mostly there to allow machine-generated code to be combined with manually-generated code at compile time, to avoid abusing inheritance etc. It can be used for other reasons, but that's the main purpose of them. No more source files with "don't edit this bit - it belongs to the designer" etc.
Virtual methods: no, you can't override a member if it's not declared virtual (or abstract) in the base class. You can shadow it with new, but that's not the same as overriding it - the new method won't be called polymorphically.
Partial classes and methods allow you to spread code across different files. This is useful when you use code generation - the generated code is in one file that can get overwritten without a problem, the rest of the code can be changed safely.
As for virtual - in C#, if you want to override a method, you must use virtual (or abstract) in the base class and override in the overriding class. You can't simply override without them.
If you don't use virtual/abstract and override you are in danger of hiding/shadowing a method, which may or may not be what you want. Using virtual/abstract and override make things explicit and predictable.
Partial classes lets you split a class definition across multiple files, which is practical in some scenarios.
No; you can only override a method if it is marked as virtual in the base class. If the base class' method is not virtual and you create a method with the same name in the subclass, you have created an entirely new, unrelated method.
Partial classes allow you to split up a class definition across several files.
A virtual method may be overridden using the keyword override. If the method is not defined as virtual you can only hide it in a child class using the new keyword.
I guess you can read all this up in any C# 101 material. Just take a look at the MSDN library.
A partial class let's you define the same class in multiple declaration which are mostly in different files also. Like:
public partial class MyClass{
public void MethodOne(){}
}
public partial class MyClass{
public void MethodTwo(){}
}
A virtual method can be used if a subclass of the baseclass has the ability to override the method. Use abstract if your subclass MUST override the method. So,
public class MyBaseClass{
public virtual void MethodOne(){} // CAN be overridden...
public abstract void MethodTwo(){} // MUST be overridden.
}
Partial classes are useful to divide a single class in multiple files in the same project.
This is very useful for tools that generates code for you, like windows form or WPF.
Partial classes allow you, for example, to write your code in one file and let the IDE write his code in another file.
About virtual and override, look at this other thread: Why do we use virtual and override?
If I have a project that contains similar classes and some may use the same implementation, but in most cases they implement their own way of handling the methods defined in an interface or abstract class. I am trying to figure out if an interface/abstract class is better or not. I don't get the point of an interface if you can just use an abstract class with virtual abstract methods.
Here is an interface:
public interface IAthlete
{
void Run();
}
Here is an abstract class:
public abstract class Athlete
{
public abstract void Run();
}
Here is an implementation of the interface:
public class Sprinter : IAthlete
{
public void Run()
{
Console.WriteLine("Running Fast....");
}
}
Here is an extension of the abstract class:
public class MarathonRunner : Athlete
{
public override void Run()
{
Console.Write("Jogging....");
}
}
Now if I decide to add a method called Stop to either the interface or abstract method, Sprinter and MarathonRunner both break and because I can provide some default implementation to abstract, it seems like a better choice. Am I missing something?
There are 2 main differences between Interfaces and abstract super-classes:
Abstract Classes
code reuse is possible by using an abstract super-class
you can only inherit one super-class
Interfaces
every method has to be implemented in each sub-class
a class can inherit more than 1 interface (multiple inheritance)
In the case where all you have is one piece of commonality to extract, you're quite right that there isn't a substantive difference between the two. But this is rather like saying "in the case of adding 1 to 2, there's no difference between an int and a double" - it's technically true, but not a particularly useful guide to how to think.
In case with any more complexity than this (that is, in most cases) there will be more classes, and pieces of common baheaviour to extract. Then you have to start making a significant choice between class inheritance and interface implementation, taking into account things like:
you only get one shot at choosing a base class, but you can implement as many interfaces as you like
if you want your 'parent' to do any work, it needs to be a class not an interface
and so on.
In general, the semantics of your classes should guide you - where the 'things' have an "IS A" relationship (like MarathonRunner to Athlete), inheritance is suggested; where the 'things' have an "I CAN FULFIL THE CONTRACT OF A" (like, say, Person to Runner), interface implementation is suggested.
Interfaces are a btter way to go as the current consensus amongst the .NET developer comunity is that you should favour composition over inheritance, so Interfaces are a much better strategy (think of Injection Containers and how usefull they are as well, and lets not get started on unit testing).
also, classes can implement many interfaces but can only inherit from one class (abstract or otherwise). also structs can implement interfaces but not inherit from another class.
At the runtime level, interfaces are more efficient as the runtime doesnt have to walk the inheritance stack in order to work out the polymorphic implications of calling a specific member.
Interfaces are a very useful feature, and are very similar to abstract classes, and in some circumstances, exchangable with abstract classes.
But, don't jump straight to interfaces, unleass you have to (very common antipattern in Java developers). I suggest, by reading your example, to stick to abstract classes.
Most of the times I only use interfaces, when I have several non related classes, and I need them to have common members, as If these classes came from the same base class.
In your example, you are trying to find what happen if you need a new stop method, when adding a base virtual method. These can be solved in a different approach, that is not Abstract Classes versus interfaces.
There are 3 choices:
(1) Add an abstract method that coerce the programmer to override it, in order to instantiate objects.
(2) Add a new virtual method that does something, but doesn't have to be overriden.
(3) Add a new method that does nothing, maybe applies to your case.
// cannot instantiate an abstract class
public abstract class Athlete
{
// helper method:
public /* non-abstract */ void DoNothing()
{
// does nothing on purpouse !!!
}
// (1) virtual & abstract method, must be overriden
public abstract void Run();
// (2) new virtual method, doesn't need to be overriden,
// but, maybe you dont like what it does
public virtual void Stop()
{
Message.Show("Stop !!!");
}
// (3) new virtual method, doesn't need to be overriden,
// its safe to be called
public virtual void TakeBreak()
{
// works like an abstract virtual method, but, you don't need to override
DoNothing();
}
} // class Athlete
// in a non abstract class, you must override all abstract methods
public /* non-abstract */ class Runner: Athlete
{
public override void Run()
{
DoNothing();
}
public override void Stop()
{
DoNothing();
}
// don't need to override this method
// public virtual void TakeBreak();
} // class Trekker
// ...
Runner ARunner = new Runner();
ARunner.Run();
ARunner.Stop();
ARunner.TakeBreak();
The third kind of virtual method, that may apply to your example, doesnt' have a special name, I already post a question about it on stackoverflow, but, nobody knew an special name for this case.
Cheers.
An important difference between interfaces and abstract classes is how their members handle multi-generational inheritance. Suppose there's an abstract class BaseFoo with abstract method Bar and interface IFoo with method Boz; class Foo inherits BaseFoo and implements IFoo, and class DerivedFoo inherits from Foo.
If DerivedFoo needs to override BaseFoo.Bar, it may do so, and its override may call base.Bar() if it needs to use its parent's implementation. If Foo implements Boz implicitly using a virtual method, then DerivedFoo may override that method and call base.Boz() (the override being a function of the class rather than the interface) but if Foo explicitly implements IFoo.Boz, then the only way for DerivedFoo to change the behavior of IFoo.Boz will be to re-implement it. If it does so, then Foo's implementation of IFoo.Boz will become inaccessible, even within DerivedFoo's implementation of the same interface member.
Whenever i override a method of a base class, other than my implementation of this method, i seem to have 3 choices.
1) Call base.Method(), and then provide my implementation.
2) Provide my implementation and then call base.Method()
3) Just provide my implementation.
Recently while using a library i have realized few bugs that were introduced because of not implementing the method as expected by the library. I am not sure if that is bad on part of library, or something wrong in my understanding.
I will take one example.
public class ViewManager {
public virtual void Customize(){
PrepareBaseView();
}
}
public class PostViewManager {
public override void Customize(){
base.Customize();
PreparePostView();
}
}
public class PreViewManager {
public override void Customize(){
PreparePreView();
base.Customize();
}
}
public class CustomViewManager {
public override void Customize(){
PrepareCustomView();
}
}
My question here is that how could a child class know (without taking a look at base class implementation) which order (or option) is being expected by the parent class?
Is there a way in which parent class could enforce one of the three alternates to all the deriving classes?
how could a child class know (without taking a look at base class implementation) which order (or option) is being expected by the parent class?
There is no way to "know" this when you are subclassing and overriding a method. Proper documentation is really the only option here.
Is there a way in which parent class could enforce one of the three alternates to all the deriving classes?
The only option here is to avoid the issue. Instead of allowing the subclass to override the method, it can be declared non-virtual, and call a virtual method in the appropriate place. For example, if you want to enforce that subclasses "call your version first", you could do:
public class BaseClass {
public void Method() // Non-virtual
{
// Do required work
// Call virtual method now...
this.OnMethod();
}
protected virtual void OnMethod()
{ // Do nothing
}
}
The subclasses can then "override" OnMethod, and provide functionality that happens after "method"'s work.
The reason this is required is that virtual methods are designed to allow a subclass to completely replace the implementation of the parent class. This is done on purpose. If you want to prevent this, it's better to make the method non-virtual.
This is why I feel virtual methods are dangerous when you ship them in a library. The truth is you never really know without looking at the base class, sometimes you have to fire up reflektor, read documentation or approach it with trial and error.
When writing code myself I've always tired to follow the rule that says:
Derived classes that override the protected virtual method are not required to call the base class implementation. The base class must continue to work correctly even if its implementation is not called.
This is taken from http://msdn.microsoft.com/en-us/library/ms229011.aspx, however this is for Event design though I believe I read this in the Framework Design Guidelines book (http://www.amazon.com/Framework-Design-Guidelines-Conventions-Libraries/dp/0321246756).
However, this is obviously not true, ASP.NET web forms for example require a base call on Page_Load.
So, long and short, it varies and unfortunately there is no instant way of knowing. If I'm in doubt I will omit the call initially.
The short answer is no. You can't enforce in what order the child calls the base method, or if it calls it at all.
Technically this information should be included in the base object's documentation. If you absolutely must have some code run before or after the child class' code than you can do the following:
1) Create a non-virtual function in the base class. Let's call it MyFunction
2) Create a protected virtual function in the base class. Let's call it _MyFunction
3) Have deriving classes extend the _MyFunction method.
4) Have MyFunction call _MyFunction and run the code it needs to run before or after calling it.
This method is ugly and would require a lot of extra code, so I recommend just putting a notice in the documentation.
The requirements of the base class should be documented by the library designer.
This issue is the reason why some libraries contain mainly sealed classes.