Recently, codereview shows that the writing of the two methods is very similar, except for different operation types. I want to merge these two methods into one to improve the code reuse rate.
First, let's explain the background:
There are two classes:
Public class Dog
{
Public string Name {get; set ;}
}
Public class Cat
{
Public string Name {get; set ;}
}
Now there is a requirement to print the names of Dog and Cat, and write two methods for printing the names of Dog and Cat:
// Print the Dog name
Public static void PrintDogName (Dog dog)
{
Console. WriteLine (dog. Name );
}
// Promise the Cat name
Public static void PrintCatName (Cat cat)
{
Console. WriteLine (cat. Name );
}
To print a name, instantiate Dog and Cat and call two methods to print the name:
Static void Main (string [] args)
{
// Instantiate Dog
Dog Spot = new Dog () {Name = "WangWang "};
// Instantiate Cat
Cat Persian = new Cat () {Name = "Mimi "};
// Print the Name of the Dog instance
PrintDogName (Spot );
// Print the Cat Instance Name
PrintCatName (Persian );
}
During codereview, we found that these two methods are so similar that only the processing types are different. In this example, you can merge:
// The merge method in this example
Public static void PrintName (string name)
{
Console. WriteLine (name );
}
The following describes how to combine the two methods into a method to improve code reuse:
Public static void PrintName <T> (T t)
{
// Print Dog
If (t is Dog)
{
Console. WriteLine (t as Dog). Name );
Return;
}
// Print Cat
If (t is Cat)
{
Console. WriteLine (t as Cat). Name );
Return;
}
// Print neither Dog nor Cat
Console. WriteLine ("This method only support Dog and Cat .");
}
This method combines methods into one, but the total amount of code is not reduced. I just got the code from the original two methods to a method, and then I thought about a merge method. The steps are as follows:
First, abstract the Dog class and Cat class into an interface:
// Interface containing name attributes
Interface IName
{
String Name {get; set ;}
}
Both the Dog and Cat classes must inherit this interface:
// The Dog class inherits the IName Interface
Public class Dog: IName
{
Public string Name {get; set ;}
}
// Cat class inherits the IName Interface
Public class Cat: IName
{
Public string Name {get; set ;}
}
Rewrite this generic method:
// Restrict the implementation of the IName interface for generics
Public static void PrintName <T> (T t) where T: IName
{
Console. WriteLine (t. Name );
}
In this way, the code in the method body does not need to be repeated, and in the future, it will print any name that inherits the IName interface, and the code can be expanded.