Why does overriding a method only occur after I implement an interface? - c#

I've been reading through the book Working Effectively with Legacy Code and I've been playing around with the concept of overriding difficult to test methods in unit tests via the creation of a fake. I put together an example of what I thought would work and it ended up behaving differently than I had been expecting. I think I've just discovered a hole in my understanding of how inheritance and method overloading works in C# and I was wondering if someone could help me understand what's going on here.
I've got the following interface:
public interface IAnimal
{
void MakeSound();
void Move();
}
I then create an implementation of the animal interface as follows:
public class Dog : IAnimal
{
public void MakeSound()
{
Console.WriteLine("Woof");
}
public void Move()
{
Console.WriteLine("Moved");
}
}
When I use this class as follows:
IAnimal myanimal = new Dog();
myanimal.MakeSound();
myanimal.Move();
I get the following output:
Woof
Moved
Now, lets pretend that I'm needing to unit test the Dog class but one of the methods, MakeSound(), needs to be overridden because it is making the class difficult to test for some reason.
I create a fake dog by extending the Dog class and creating a method for MakeSound
public class FakeDog : Dog
{
public void MakeSound()
{
Console.WriteLine("Bark");
}
}
When I use this class as follows:
IAnimal myanimal = new FakeDog();
myanimal.MakeSound();
myanimal.Move();
I get the following output:
Woof
Moved
I had been expecting it to have been:
Bark
Moved
However, if I then have the FakeDog class implement the animal interface and use it:
public class FakeDog : Dog, IAnimal
{
public void MakeSound()
{
Console.WriteLine("Bark");
}
}
I get the following output:
Bark
Moved
I'm just wanting to understand the reason why this now overrides the method as I had been expecting when I had just been extended the Dog class. Can anyone set me straight on this?

In the first case you're creating a new method which hides the original implementation of IAnimal.MakeSound. You should have seen a warning suggesting that you use the new keyword to make this explicit.
In the second case you're re-implementing IAnimal. Implementing an interface doesn't require the override keyword (although it might have been nice if the language designers had required that).
To avoid re-implementing the interface, you could make MakeSound virtual in Dog, and then explicitly override it in FakeDog. At that point there's only one possible resolution involved, and everything is simpler to understand. I try to avoid reimplementation and method hiding whenever possible.

(Sorry for answering with a question, but you might genuinely find this experiment informative) What happens when you implement dog as follows:
public class Dog : IAnimal
{
public virtual void MakeSound()
{
Console.WriteLine("Woof");
}
//...
Note the "virtual"

You need to declare the MakeSound method as virtual in the Dog class and override it in the FakeDog class:
public class Dog : IAnimal
{
public virtual void MakeSound()
{
Console.WriteLine("Woof");
}
public virtual void Move()
{
Console.WriteLine("Moved");
}
}
public class FakeDog : Dog
{
public override void MakeSound()
{
Console.WriteLine("Bark");
}
}

Related

Why we do create object instance from Interface instead of Class?

I have seen an Interface instance being generated from a class many times. Why do we use interface this way? An interface instance is created only itself with the help of the derived class and we can access only these interface members through this instance. How does this give an advantage? I'm so confused.
interface IPrint
{
void Print();
}
class Sample : IPrint
{
public void Print()
{
Console.WriteLine("Print...");
}
public void Sample()
{
Console.WriteLine("Sample...");
}
}
class Program
{
static void Main(string[] args)
{
IPrint print = new Sample();
print.Print();
}
}
Interfaces define that a class MUST be able to do something. This means that you know the object being worked on will do what you want to be able to do. It allows you greater freedom and is one of the advantages of OOP. This is a deep topic but a very basic example would be this:
public interface IAnimal
{
string Speak();
}
public class Dog : IAnimal
{
public string Speak()
{
return "Woof, woof";
}
}
public class Cat : IAnimal
{
public string Speak()
{
return "Meow";
}
}
public class Parrot : IAnimal
{
public string Speak()
{
return "Sqwark!";
}
}
Then you could use any animal you like!
class Program
{
static void Main(string[] args)
{
// Writes Woof, Woof
IAnimal animal = new Dog();
Console.WriteLine(animal.Speak());
// Now writes Meow
animal = new Cat();
Console.WriteLine(animal.Speak());
// Now writes Sqwark etc
animal = new Parrot();
Console.WriteLine(animal.Speak());
}
}
This also allows you to then get into things like Inversion Of Control where you would take an item in like this and you could pass a dog, cat or parrot and the method would always work, not knowing or caring which animal it was:
public void ShoutLoud(IAnimal animal)
{
MessageBox.Show("Shout " + animal.Speak());
}
This then makes ShoutLoud unit testable because you could use a mock object rather than a real animal. It basically makes your code flexible and dynamic rather than rigid and tightly coupled.
Also, expanding on Matthew's question. In C# you can only inherit from one base class but you can have multiple interfaces. So, you could have:
public class Dog : IAnimal, IMammal, ICarnivor
This allows you to have small interfaces (recommended) that then allow you to build up so giving maximum control over what an item can / must do.
Using an interface this way gives you the ability to create methods that use standard template of the interface. So here you might have many classes of printer that all inherit from IPrinter
class SamsungPrinter : IPrinter
{
// Stuff and interface members.
}
class SonyPrinter : IPrinter
{
// Stuff and interface members.
}
interface IPrinter
{
void Print();
}
So for each type SamsungPrinter, SonyPrinter, etc. you can pre-process using something like
public static void PreProcessAndPrint(IPrinter printer)
{
// Do pre-processing or something.
printer.Print();
}
You know from inheriting from IPrinter and using that type in the method parameters that you can always safely use the Print method on what ever object is passed.
Of course there are many other uses for using interfaces. One example of their use is in design patterns, in particular the Factory and Strategy patterns. The description of which and examples can be found here.
I hope this helps.
But how does this differ from, for example, using a base class with virtual methods?
You are all in the assumption that one programmer or one program writes the interface and the classes, but this doesn't always have to be this way.
Maybe you have a complete finished program that works with animals and you have this worked out using:
public abstract class Animal { public abstract string Speak(); }
And then some day you download some awesome DLL from nuget that shows pictures for animals. The class library contains a contract - interface - 'IAnimal':
namespace AwesomeAnimalLibrary
{
public interface IAnimal
{
string AnimalName;
}
}
The class library also maybe contains :
namespace AwesomeAnimalLibrary
{
public class AnimalPhotos
{
[Byte] GetPhotos(IAnimal animal);
}
}
What could you do now ? Your bas class Animal can implement the AwesomeAnimalLibrary IAnimal interface and that's it.
Don't assume that other people will use you abstract base classes but work together using interface contracts.
Interface can not have instance because interface implements only signatures of properties or methods. Interface is just a pointer to an instance of some class:
interface IExample
{
// method signature
void MyMethod();
}
public class MyClass : IExample
{
// method implementation
public void MyMethod()
{
ConsoleWriteline("This is my method");
}
}
// interface pointing to instance of class
IExample ie = new MyClass();
ie.MyMethod();

Inherit from a base class and provide the inheritance type to overridden method

I have a base class with a method that can be overridden. If I inherit a class from this base class how can I make the method return the inherited type?
Like:
public class ClassA : BaseClass
{
public override ClassA TestMethod(...)
{
// ...
}
}
Do I need to provide a type manually to the base class ? Or can I make it provide that type automatically?
You could use a generic type to do it.
public class BaseClass<T> where T : BaseClass<T> {
public abstract T TestMethod(...);
}
public class ClassA : BaseClass<ClassA>
{
public override ClassA TestMethod(...)
{
// ...
}
}
Why do you need it? Might lead to better suiting answers...
The feature you want has a name; this is return type covariance.
The reasons it is not supported in C# are here:
Why C# doesn't allow inheritance of return type when implementing an Interface
The other answers are all suggesting that you use the C# version of the curiously recurring template pattern to solve your problem. My opinion is that the pattern makes more problems than it solves. See my article on that subject for more details:
http://blogs.msdn.com/b/ericlippert/archive/2011/02/03/curiouser-and-curiouser.aspx
A better way to solve this problem is to use this pattern:
abstract class Animal
{
protected abstract Animal ProtectedGetMother();
public Animal GetMother()
{
return this.ProtectedGetMother();
}
}
class Cat : Animal
{
protected override Animal ProtectedGetMother()
{
do the work particular to cats here
make sure you return a Cat
}
public new Cat GetMother()
{
return (Cat)this.ProtectedGetMother();
}
}
The problem is that you cannot override a virtual method with a different return type. So don't. Make a brand new method with a different return type and make the virtual method an implementation detail of the class hierarchy.
This technique is approximately one billion times easier to understand than this Cat : Animal<Cat> "a cat is an animal of cat" nonsense.
You can do this in a generic way:
public abstract class Base
{
public abstract T AbstractTestMethod<T>() where T : Base;
public virtual T VirtualTestMethod<T>() where T : Base, new()
{
return new T();
}
}
public class ClassA : Base
{
public override ClassA AbstractTestMethod<ClassA>()
{
return new ClassA();
}
public override ClassA VirtualTestMethod<ClassA>()
{
return new ClassA();
}
}
Using virtual methods behaves not as strict as using abstract methods. Using the abstract way you can force developers to implement the method on their own. Using the virtual way you can tell them something like "meet my constraints and feel free to use the default behaviour".

Class inheritance, forcing new classes to implement certain functions

Ok so i'm messing around with a few things, specifically interfaces.
Say I have a class 'Cat' with its base as 'Animal' Animal has a method in it like so
public virtual void Walk()
{
// Do walking stuff
}
So Cat would override it with:
public override void Walk()
{
// Do cat specific walking stuff
}
Simple right?
Here's my question though, is there a way to force cat to override the base Walk() method? So if another developer added a Dog class they would be forced to implement their own Walk method (even if it was just base.Walk()) ?
So interfaces kind of solves this, this is what i've tried
Cat : Animal : Interface
Animal has to implement the Walk method, but Cat doesn't
Cat : Animal, Interface
Cat has to implement the Walk method, but if the developer doesn't add or forgets the ',Interface' then it will 'break' it.
can someone give me some pointer as to go about this ?
Thanks.
Edit 1
Here's what I am aiming for, i hope it makes it clearer.
public class Animal
{
public Animal()
{
Console.WriteLine("Animal");
}
public virtual void Walk()
{
}
}
public class Cat : Animal
{
public Cat() : base()
{
Console.WriteLine("Cat");
}
public override void Walk()
{
}
}
class Dog : Animal
{
public Dog()
{
}
public override void Walk()
{
// Dog implementation
// and / or calls base method
base.Walk();
}
}
This would create an error
class Dog : Animal
{
public Dog()
{
}
}
This is when you want to mark the base class and the base method as abstract.
abstract class Animal
{
public abstract void Walk();
}
Derived classes will have to implement Walk in order to be instantiated.
class Cat : Animal
{
public override void Walk() { }
}
Note: this change makes Animal not instantiable on its own, all references to it would be via more derived classes.
Animal animal = new Cat();
Here's my question though, is there a way to force cat to override the
base Walk() method? So if another developer added a Dog class they
would be forced to implement their own Walk method (even if it was
just base.Walk()) ?
This is where you have a disconnect, or opposing goals. To force children to implement a method, you mark it abstract. To allow the child to elect to use the base implementation, it would need to be virtual, which would then make it optional to override. Even if you were to basically use a template method pattern and make parts of the algorithm abstract to push the implementation into lower classes, the problem remains the same: you cannot force an override while also leaving a default implementation.*
You need to determine if you want to have a base implementation, in part or in whole.
*You chould theoretically have abstract void Walk(); protected void WalkImpl() { } in the base, which would allow the children to choose to invoke WalkImpl if they didn't want to provide their own implementation.
class Cat : Animal
{
protected override void Walk() { base.WalkImpl(); }
}
I'm not sure how I feel about this, however. You're basically making the derived classes' authors' lives more difficult by forcing an override while still allowing them to use a default behavior. If the default behavior can be used, simply go with virtual and trust authors of derived classes to override when they feel it is appropriate.

Best way to refer to my own type

abstract class A<T> where T:A<T>
{
public event Action<T> Event1;
}
class B : A<B>
{
//has a field called Action<B> Event1;
}
Is there a more elegant way to do this? I want stuff (events, etc) in the base class to be able to use the subclass' type.
The pattern you are using does not actually implement the constraint you want. Suppose you want to model "an animal can only be friendly with something of its own kind":
abstract class Animal<T> where T : Animal<T>
{
public abstract void GetFriendly(T t);
}
class Cat : Animal<Cat>
{
public override void GetFriendly(Cat cat) {}
}
Have we succeeded in implementing the desired constraint? No.
class EvilDog : Animal<Cat>
{
public override void GetFriendly(Cat cat) {}
}
Now an evil dog can be friendly with any Cat, and not friendly with other evil dogs.
The type constraint you want is not possible in the C# type system. Try Haskell if you need this sort of constraint enforced by the type system.
See my article on this subject for more details:
http://blogs.msdn.com/b/ericlippert/archive/2011/02/03/curiouser-and-curiouser.aspx
What you have works very well. In fact it's very similar to other .NET interfaces and types where you want the interface implementer to use your type, like:
public class MyClass : IEqualityComparer<MyClass>
{
// From the interface IEqualityComparer
public bool Equals(MyClass other) { ... }
...
}
I don't think you need to specify where T:A.
T will be B when you use class B:A
This is also known as CRTP or Curiously recurring template pattern and is a known idiom.
Since A is abstract, you can add abstract methods to A and invoke them from A and B, which will be forced to implement the method, will be the invoker:
abstract class A<T> where T:A
{
public event Action<T> Event1;
public abstract void Method();
public A(){Method();}
}
class B : A<B>
{
//has a field called Action<B> Event1;
public void Method(){ //stuff }
}
On instantiation of B, the base class constructor will call Method() which is only implemented in B, forcing B's instance to be called.
This allows A to invoke subclass specific methods without requiring A to have specific knowledge of Children. The downside is that ALL children must implement Method or re-abstract it to their own children.
My most recent question was marked as a duplicate of this one. I totally agree on that matter. So I came here to take a look at the answers and to read Eric's post on that (very interesting indeed). You can not enforce this at compile time with the type system but you can do this at runtime. The way I implemented this is:
abstract class FooBase<T>
{
protected FooBase()
{
if (typeof(T) != GetType())
{
throw new InvalidOperationException();
}
}
}
By doing this we can plant the seed of an evil dog, but that dog will be aborted at runtime.

Writing a generic API for a type 'family'

I'm working with a smallish type hierarchy, something like the following, and lets say there won't ever be any other Animal types in my sad safari-less world (I'm not at all worried about resilience to expanding):
public abstract class Animal {};
public sealed class Dog : Animal {};
public sealed class Cat : Animal {};
public sealed class Turtle : Animal {};
public sealed class Bird : Animal {};
I'd like to treat all of the animals similarly as far as the API is concerned, but obviously they respond just a little differently in the below situations:
public class AnimalCare {
public void Feed<T> (T pet) where T: Animal;
public T PickUp<T> (PetStore store);
}
At first blush the idea of performing feedings without putting a feed method on the Animal class (sorry, I know the example is reaching at this point, but lets pretend for the sake of argument that AnimalCare is the view to my Animal models and I'm pretty adamant about separation of concerns) would suggest a visitor. But what I would really like to do is let the above be the only sort of API consumers of AnimalCare need to worry about, while I do something like the following:
public class AnimalCare {
public void Feed<T> (T pet) where T : Animal;
public T PickUp<T> (PetStore store);
public void Feed<Dog> (Dog rover)
{
// dump out alpo, lift toilet seat
}
public void Feed<Turtle> (Turtle franklin)
{
// do turtles eat? let him figure it out himself.
} // ...etc.
public Dog PickUp<Dog> (PetStore store)
{
// get bone, tennis ball, leash
}
public Bird PickUp<Bird> (PetStore store)
{
// make sure not dead, nailed to perch
} // ...etc.
}
And so on. I know the first part (the Feed () methods) are fine to just overload without even needing generics, but that still leaves me with an awkward implementation for PickUp (since its not legal to implement as I've sketched it above), something miserable like PickUpDog//PickUpBird etc. I would very much like to avoid having a separate "view" for consumers of AnimalCare and its like-minded friends to have to be concerned with.
I've been playing around with nesting specialized classes and other bizarre attempts at composition or interface refactoring, but I can't seem to get it right and I'm stuck. Is there a clean way to do something like what I want, or am I resigned to implementing an AnimalCare for each concrete Animal?
EDIT
Joel's point about factory/repository made me think some more. Let's instead call the methods of interest a little more reasonable:
public class AnimalPresentation {
public void Show (Dog dog);
public void Show (Cat cat);
//..etc.
public Animal Get (PetStore store);
}
That would have made more sense in the first place I suppose. The type of Animal to be gotten out of PetStore isn't known at the time Get is called, but in the general implementation of Get, once the type is determined, it branches to the specific overload. Is specific subtypes of PetStore the best/only way forward here?
I think the problem with AnimalCare is that it is essentially a factory for Animal instances, or at least access to an Animal repository. So maybe your PickUp function should return an Animal object instead of a specific type.
Alternatively, could you not base AnimalCare on a specific type (AnimalCare<T>) ? The example is little hard to gauge in terms of actual intention, so apologies if these ideas don't seem to hit the mark.
edit
You might consider something like this:
First you have an interface IAnimal with your animals on there. They don't know about any methods. Then create a new interface like
interface IAnimalCareClient<T>
{
void Init(T animal);
void Feed();
T Pickup(PetStore store);
}
Then create clients for every animal type like
class DogClient : IAnimalCareClient<Dog>
{
void Init(Dog animal) { //bla }
void Feed() {}
Dog Pickup(PetStore store) { //bla again }
}
Your clients should then be stored in some list, and the types can reside in various dll's etc. You just need to grab a reference.
Then just
class AnimalCare
{
void Feed<T>(T animal)
{
//GrabWorkerFromStack<T>() should return the type IAnimalCareClient<T>
IAnimalCareClient<T> worker = Activator.CreateInstance(GrabWorkerFromStack<T>());
worker.Init(animal);
worker.Feed();
}
}
original answer
Basically you want to lay the responsibility at the animal itself, as you cannot force your AnimalCare class to implement all properties for all animals. Then becomes something simple like:
interface IAnimal
{
void Feed();
IAnimal Pickup(PetStore store);
}
class Dog : IAnimal
{
void Feed() { /* feed */ }
IAnimal Pickup(PetStore store) { /* grab animal and return */ }
}
class AnimalCare
{
void Feed(IAnimal animal)
{
animal.Feed();
}
T Pickup<T>(T animal, PetStore store) where T: IAnimal
{
return (T)animal.Pickup(store);
}
}
You can use interfaces, I don't know what specific requirements there is, but if an animal may have one trait that might be shared with other animals, but doesn't have to an interface is a good start.
For example:
interface IFeedable
{
void Feed();
}
interface IMammal<TChild>
where TChild: IMammal<TChild>
{
IEnumerable<TChild> Reproduce();
}
class Dog: IFeedable, IMammal<Puppy>
{
// ...
}
I use interfaces all the time (probably overusing them), especially in a case as this were normal inheritance might not be the best way.

Categories