I have a c# Class that has lots of virtual methods, some of these methods are essentially abstract ( they are fully implemented in subclasses and the base class is empty).
To get it to compile i am throwing an InvalidOperationException in the base class with a comment on what should be done. This just feels dirty.
Is there a better way to design my classes?
edit:
It is for the middle tier of an application that will be ran in canada, half of the methods are generic hence the virtual. and half of the methods are province specific.
Public class PersonComponent()
{
public GetPersonById(Guid id) {
//Code to get person - same for all provinces
}
Public virtual DeletePerson(Guid id) {
//Common code
}
Public virtual UpdatePerson(Person p) {
throw new InvalidOperation("I wanna be abstract");
}
Public Class ABPersonComponent : PersonComponent
{
public override DeletePerson(Guid id)
{
//alberta specific delete code
}
public override UpdatePerson(Person p)
{
//alberta specific update codecode
}
}
hope this makes sense
Mark the base class as abstract, as well as the methods that have no implementation.
Like so
public abstract class BaseClass
{
public abstract void AbstractMethod();
}
public class SubClass: BaseClass
{
public override void AbstractMethod()
{
//Do Something
}
}
You can't have abstract methods outside of an abstract class. Marking a class as abstract means you won't be able to instantiate it. But then it doesn't make any sense to. What are you going to do with a class that doesn't implement the methods anyway?
Edit: From looking at your class, yeah I'd make PersonComponent abstract along with the UpdatePerson method. Either that, or if UpdatePerson just doesn't do anything for a PersonComponent keep it as is, but make the UpdatePerson method empty for PersonComponent.
Think about your object hierarchy. Do you want to share common code for all your derived classes, then implement base functionality in the base class.
When having shared base code, please notice the Template pattern. Use a public method and chain it to a protected virtual method with the core/shared implementation. End the shared implementation methodname with "Core".
For example:
public abstract class BaseClass
{
protected virtual void DeletePersonCore(Guid id)
{
//shared code
}
public void DeletePerson(Guid id)
{
//chain it to the core
DeletePersonCore(id);
}
}
public class DerivedClass : BaseClass
{
protected override void DeletePersonCore(Guid id)
{
//do some polymorphistic stuff
base.DeletePersonCore(id);
}
}
public class UsageClass
{
public void Delete()
{
DerivedClass dc = new DerivedClass();
dc.DeletePerson(Guid.NewGuid());
}
}
Related
I have a base class and a class inheriting base. The base class has several virtual functions that the inherited class may override. However, the virtual functions in the base class has code that MUST to run before the inherited class overrides get called. Is there some way that I can call the base classes virtual functions first then the inherited class overrides. Without making a call to base.function().
I know I can simply make two functions, one that gets called, the other virtual. But is there a way I can keep the same names as well? I know I may need to change some things around.
class myBase
{
public virtual myFunction()
{ /* must-run code, Called first */ }
}
class myInherited : myBase
{
public override myFunction()
{ /* don't use base.myFunction();,
called from base.myFunction(); */ }
}
Similar question here.
C# doesn't have support for automatically enforcing this, but
you can enforce it by using the template method pattern. For example, imagine you had this code:
abstract class Animal
{
public virtual void Speak()
{
Console.WriteLine("I'm an animal.");
}
}
class Dog : Animal
{
public override void Speak()
{
base.Speak();
Console.WriteLine("I'm a dog.");
}
}
The trouble here is that any class inheriting from Animal needs to call base.Speak(); to ensure the base behavior is executed. You can automatically enforce this by taking the following (slightly different) approach:
abstract class Animal
{
public void Speak()
{
Console.WriteLine("I'm an animal.");
DoSpeak();
}
protected abstract void DoSpeak();
}
class Dog : Animal
{
protected override void DoSpeak()
{
Console.WriteLine("I'm a dog.");
}
}
In this case, clients still only see the polymorphic Speak method, but the Animal.Speak behavior is guaranteed to execute. The problem is that if you have further inheritance (e.g. class Dachshund : Dog), you have to create yet another abstract method if you want Dog.Speak to be guaranteed to execute.
A common solution that can be found in the .NET Framework is to split a method in a public method XXX and a protected, virtual method OnXXX that is called by the public method. For your example, it would look like this:
class MyBase
{
public void MyMethod()
{
// do something
OnMyMethod();
// do something
}
protected virtual void OnMyMethod()
{
}
}
and
class MyInherited : MyBase
{
protected override void OnMyMethod()
{
// do something
}
}
public abstract class BaseTemp
{
public void printBase() {
Console.WriteLine("base");
print();
}
public abstract void print();
}
public class TempA: BaseTemp
{
public override void print()
{
Console.WriteLine("TempA");
}
}
public class TempB: BaseTemp
{
public override void print()
{
Console.WriteLine("TempB");
}
}
There is no way to do what you're seeking other than the 2 ways you already named.
Either you make 2 functions in the base class, one that gets called and the other virtual.
Or you call base.functionName in the sub-class.
Not exactly. But I've done something similar using abstract methods.
Abstract methods must be overriden by derived classes. Abstract procs are virtual so you can be sure that when the base class calls them the derived class's version is called. Then have your base class's "Must Run Code" call the abstract proc after running. voila, your base class's code always runs first (make sure the base class proc is no longer virtual) followed by your derived class's code.
class myBase
{
public /* virtual */ myFunction() // remove virtual as we always want base class's function called here
{ /* must-run code, Called first */
// call derived object's code
myDerivedMustcallFunction();
}
public abstract myDerivedMustCallFunction() { /* abstract functions are blank */ }
}
class myInherited : myBase
{
public override myDerivedMustCallFunction()
{ /* code to be run in derived class here */ }
}
What do you think of this?
class myBase
{
public void myFunctionWrapper()
{
// do stuff that must happen first
// then call overridden function
this.myFunction();
}
public virtual void myFunction(){
// default implementation that can be overriden
}
}
class myInherited : myBase
{
public override void myFunction()
{
}
}
I have a base class that has some abstract methods on it and there are 21 classes that are inheriting from this base class. Now for one of those abstract methods I want to implement it with a common implementation for 6 of the 21 classes so I thought about creating another base class that would do this.
I am open to suggestions but my main purpose of creating another base class between the current base class and the 21 classes is to keep from repeating the same code in 6 of the 21 classes if I didn't have to.
Here is a sample of code to illustrate the situation:
public abstract class FooBase
{
public abstract string Bar();
public abstract string SomeMethod();
public virtual string OtherMethod()
{
return this.SomeMethod();
}
}
public abstract class AnotherBase : FooBase
{
public abstract string Bar();
public abstract string SomeMethod();
public override OtherMethod()
{
//this is the common method used by 6 of the classes
return "special string for the 6 classes";
}
}
public class Foo1 : FooBase
{
public override string Bar()
{
//do something specific for the Foo1 class here
return "Foo1 special string";
}
public override string SomeMethod()
{
//do something specific for the Foo1 class here
return "Foo1 special string";
}
}
public class Another2 : AnotherBase
{
public override string Bar()
{
//do something specific for the Another2 class here
return "Another special string";
}
public override string SomeMethod()
{
//do something specific for the Another2 class here
return "Another2 special string";
}
}
Yes, you can derive an abstract class from another abstract class
public abstract class FooBase
{
//Base class content
}
public abstract class AnotherBase : FooBase
{
//it is "optional" to make the definition of the abstract methods of the Parent class in here
}
When we say it is optional to define the abstract methods of the parent class inside of the child class, it is mandatory that the child class should be abstract.
public abstract class FooBase
{
public abstract string Bar();
public abstract string SomeMethod();
public abstract string OtherMethod();
}
public abstract class AnotherBase : FooBase
{
public override string OtherMethod()
{
//common method that you wanted to use for 6 of your classes
return "special string for the 6 classes";
}
}
//child class that inherits FooBase where none of the method is defined
public class Foo1 : FooBase
{
public override string Bar()
{
//definition
}
public override string SomeMethod()
{
//definition
}
public override string OtherMethod()
{
//definition
}
}
//child class that inherits AnotheBase that defines OtherMethod
public class Another2 : AnotherBase
{
public override string Bar()
{
//definition
}
public override string SomeMethod()
{
//definition
}
}
So I'm guessing that there will be 5 more classes like Another2 which inherits from AnotherBase that will have a common definition for OtherMethod
Yes, that is entirely possible and frequently done. There is no rule that says that you can have only one base class at the bottommost level of your class hierarchy; subclasses of that class can just as well be abstract and thereby become (somewhat more specialized) base classes for one group of classes indirectly derived from your general base class.
You should specify what exactly those classes do, but.. given the information you provided:
This is the exact problem that the Strategy pattern aims to solve, as shown in the example given in the Head First Design Patterns book.
You have an abstract Duck class, from which other ducks (e.g., RedheadDuck, MallardDuck) derive. The Duck class has a Quack method, that simply displays the string "quack" on the screen.
Now you are told to add a RubberDuck. This guy doesn't quack! So what do you do? Make Quack abstract and let the subclasses decide how to implement this? No, that'll lead to duplicated code.
Instead, you define an IQuackBehaviour interface with a Quack method. From there, you derive two classes, QuackBehaviour and SqueakBehaviour.
public class SqueakBehaviour: IQuackBehaviour
{
public void Quack(){
Console.WriteLine("squeak");
}
}
public class QuackBehaviour: IQuackBehaviour
{
public void Quack(){
Console.WriteLine("quack");
}
}
Now, you compose your ducks with this behaviour as appropriate:
public class MallardDuck : Duck
{
private IQuackBehaviour quackBehaviour = new QuackBehaviour();
public override void Quack()
{
quackBehaviour.Quack();
}
}
public class RubberDuck : Duck
{
private IQuackBehaviour quackBehaviour = new SqueakBehaviour();
public override void Quack()
{
quackBehaviour.Quack();
}
}
You can even inject an instance of IQuackBehaviour through a property if you want the ducks to change their behaviour at runtime.
I want to override an abstract method, but keep it abstract so derived classes are required to implement it themselves.
public abstract class ComponentController
{
public abstract void CreateCustomColumns();
}
public abstract class ClientComponentController : ComponentController
{
public override void CreateCustomColumns()
{
// All grids to do with clients should show these columns.
Grid.AddColumn("Client" ...
Grid.AddColumn("ClientLocation" ...
Grid.AddColumn("ClientPhoto" ...
}
}
public class ClientInvoicesComponentController : ClientComponentController
{
public override void CreateCustomColumns()
{
base.CreateCustomColumns();
// On top of the generic columns, I also want to show these.
Grid.AddColumn("InvoiceNumber" ...
Grid.AddColumn("InvoiceDate" ...
}
}
public class ClientCommunicationsComponentController : ClientComponentController
{
public override void CreateCustomColumns()
{
base.CreateCustomColumns();
// On top of the generic columns, I also want to show these.
Grid.AddColumn("CommunicationDate" ...
Grid.AddColumn("CommunicationType" ...
}
}
In this code, ClientInvoicesComponentController is not required to implement CreateCustomColumns() because this is not allowed:
public abstract class ClientComponentController : ComponentController
{
public abstract override void CreateCustomColumns()
{
Grid.AddColumn("Client" ...
Grid.AddColumn("ClientLocation" ...
Grid.AddColumn("ClientPhoto" ...
}
}
--> "Abstract method cannot declare a body"
So, how can I override CreateCustomColumns() in ClientComponentController, but still force it to be overridden again in derived classes like ClientInvoicesComponentController?
Of course it still CAN be overridden anyway, but there is nothing to indicate to the developer that it MUST be overridden... which is my aim.
-Brendan
In a word: Not.
A method being abstract means that it is declared but not defined. Being defined but abstract does not really make sense in this context, so it is not possible.
I would also very much like to know your use case. If there is some behaviour you want subclasses to inherit, but also add their own functionality, you could so something like this:
public abstract class BaseClass
{
public void DoSomething()
{
// Base class behaviour goes here.
DoSomethingInternal();
}
protected abstract void DoSomethingInternal();
}
public class SubClass : BaseClass
{
protected override void DoSomethingInternal()
{
// Sub class behaviour goes here.
}
}
In this case, I think it would be better to divide your logic into 2 methods, one method you play with and the other method your users play with. Assuming the "CreateCustomColumns" method is the name you want your users to override, you create another method, say "CreateCustomColumnsCore", for yourself. The classes may look like this:
public abstract class ComponentController
{
protected abstract void CreateCustomColumnsCore();
}
public abstract class ClientComponentController : ComponentController
{
protected override void CreateCustomColumnsCore()
{
// your code here
CreateCustomColumns(); // call users' implementation
}
public abstract void CreateCustomColumns();
}
public class ClientInvoicesComponentController: ClientComponentController
{
public override void CreateCustomColumns()
{
// user must implement this method.
}
}
Users can still override your CreateCustomColumnsCore method, this could be a feature or a bug based on if you can permit users to do this.
Let's say I make a major class Car - and I want this class to be abstract. Abstract because this is my major class, nobody should make an object of this class. This class should be only there as "backbone".
I want that classes can be created only from subclasses of Car (lets say Mercedes, Ferrari...). Because every car should have methods like StartEngine I put it into the major class. Let's say I have this:
abstract class Car
{
public string Name { get; set; }
public abstract void StartEngine();
private abstract bool CheckGasoline();
//and so on...
}
class Mercedes : Car
{
private override bool CheckGasoline()
{
//somehow check gasoline and return whatever...
}
public override void StartEngine()
{
if (CheckGasoline())
//start engine...
}
}
Well this is not gonna work. Because of private abstract:
virtual or abstract members cannot be private
So ill make every private method to protected:
abstract class Car
{
public string Name { get; set; }
public abstract void StartEngine();
protected abstract bool CheckGasoline();
//and so on...
}
class Mercedes : Car
{
protected override bool CheckGasoline()
{
//somehow check gasoline and return whatever...
}
public override void StartEngine()
{
if (CheckGasoline())
//start engine...
}
}
Is this alright? I mean it's working, but is that how it should be? Using protected when I just need a method in the same class (like here: CheckGasoline() is only needed for StartEngine() ). Somehow private would look better.
Any suggestions? Thank you.
Yes that is fine. A sub-type cannot see private methods, therefore cannot override them: they must be protected (or public etc). There is no such thing as "private to method X" in c#, so it'll have to suffice as-is.
Private methods are inaccessible to any class other than the classes that they are in - this includes derived classes.
Protected methods, on the other hand, are accessible both to the classes that they are in AND their derived classes.
Your usage of protected is correct.
You may find this article to be of help: http://msdn.microsoft.com/en-us/library/ba0a1yw2(v=vs.80).aspx.
You can build in override hooks. Microsoft does this with FrameworkElement.ArrangeCore(...) (which utilizes ArrangeOverride) and FrameworkElement.MeasureCore(...) (which utilizes MeasureOverride).
For example:
abstract class Car
{
public string Name { get; set; }
public void StartEngine()
{
if (CheckGasoline())
StartEngineOverride();
}
protected abstract void StartEngineOverride();
protected abstract bool CheckGasoline();
// ...
}
class Mercedes : Car
{
protected override bool CheckGasoline()
{
//somehow check gasoline and return whatever...
}
protected override void StartEngineOverride()
{
// CheckGasoline was already checked, so just do the override portion.
}
}
I reccomend the following:
Try using protected for your member variable declarations in the abstract class. Then use public for your abstract methods, as well.
Next, within your derived class, you should use public and override for your methods in that derived class. However, this is another option that you have, and that is that you could use virtual as well. Therefore, instead of using a single abstract class, nest all of your potential Car type class within one public CarClass class, or whatever you want to call it.
Use the virtual method for a shared method in the first declared class which is an Abstract Car class. Then use public override for the remainder of the declared derived classes that are nested also within the CarClass class which can override the virtual method that you declared in your asbstract Car class. This is another option that you have, although it may limit you to only whatever you declare in the CarClass than a distinct and separate abstract class.
I have a abstract class named Vehicle:
public abstract class Vehicle {
public void run() {
addToRunningVehicleList();
}
}
I want that every classes that extends Vehicle must call super.run() if they override run method. For example:
public class Car {
#Override
public void run() { // Error here because does not call super.run()
carRunningAnimation();
}
}
Is it possible in OOP concept, or Java/C#?
EDIT: Following Petar Ivanov, I have this code:
public abstract class Vehicle {
public final void run() {
Log.e("Run", "Add To List");
runImp();
}
public void runImp() {}
}
public class Car extends Vehicle {
#Override
public void runImp() {
Log.e("Run", "Run in Car");
}
}
However, it's not very good for public APIs. When extending Vehicle, the end-users must override runImp, but then they have to call run() method, so I have to make public both run and runImp, which make nothing better.
Here is how I would do it (C#):
public abstract class Vehicle {
public void Run() {
//code that will always run
addToRunningVehicleList();
//code that can be overriden
RunImpl();
}
protected virtual void RunImpl() { }
}
public class Car : Vehicle {
protected override void RunImpl() {
carRunningAnimation();
}
}
You can make the RunImpl protected to make sure it can't be called outside the subclasses of Vehicle.
If you need to require certain code to run in addition to the child class' implementation, perhaps you need to split this into multiple methods:
(C# example)
public abstract class Vehicle
{
public void Run()
{
// Code that always runs before...
RunCore();
// Code that always runs after...
}
protected virtual void RunCore()
{
}
}
Remember who you are designing for. If it's an internal piece of code a comment will suffice. If it's a public API and you want people to inherit then you need to write a piece of documentation telling them to do it.
In C# you can do some sneaky stuff with virtual and non-virtual methods but in Java as all inheritence is virtual it's a lot harder to enforce this without using an abstract base class.
Using an ABT may limit your ability to provide further inheritence and force modification of other code.