In: Computer Science
Refactor the code below so that it isn't awful! Justify your design decisions!
public class BrownBear { public String roar(){ return "bear"; } } public class SilentBrownBear { public String roar(){ return ""; } } public class PolarBear { public String roar(){ return "brrrr"; } } public class SilentPolarBear { public String roar(){ return ""; } }
Based on the names of the class it looks like these are types of different Bears. Each class's Roar method either return something or return empty string.
You can use abstract class as below
abstract class Bear
{
// Abstract method (does not have a body)
public abstract string Roar();
}
class BrownBear : Bear
{
public override string Roar()
{
return "bear";
}
}
class SilentBrownBear : Bear
{
public override string Roar()
{
return "";
}
}
class PolarBear : Bear
{
public override string Roar()
{
return "brrrr";
}
}
class SilentPolarBear : Bear
{
public override string Roar()
{
return "";
}
}
class Program
{
static void Main(string[] args)
{
Bear b = new BrownBear();
Console.WriteLine(b.Roar());
b = new SilentBrownBear();
Console.WriteLine(b.Roar());
b = new PolarBear();
Console.WriteLine(b.Roar());
b = new SilentPolarBear();
Console.WriteLine(b.Roar());
Console.ReadLine();
}
}
Here I have Choose abstract class because
1- You can not instantiate the abstract class.
2- Here every class is having Roar method which is either returning something or empty string. So we defined Roar method as abstract method in abstract class and implemented Bear class by all other classes.
3- As Roar method is abstract in Bear class then all the classes which are implementing the Bear class should override the Roar method.
4- Even further you can add static method to the abstract class.
5- The performance of the abstract class is faster.
6- As Roar is common behaviour in all the classes, then abstract class is best suitable to use.
Hope this will help you. I would really appreciate if you give thums up. Thank you :)