After researching for an hour regarding SOLID Principles, I tried to do it myself. Please note that most of these codes were from the ideas of others.
I created a simple program which returns specific value from array, depends on what you choose.
public interface IArrayPerformer
{
int GetAnswer(int[]arr);
}
public class HighestNumber : IArrayPerformer
{
public int GetAnswer(int[] arr){ //return highest number }
}
public class LowestNumber : IArrayPerformer
{
public int GetAnswer(int[] arr) { //return lowest number }
}
public class MiddleNumber : IArrayPerformer
{
public int GetAnswer(int[]arr) { // return middle number }
}
public class HighestPrimeNumber : IArrayPerformer
{
public int GetAnswer(int[] arr) { // return highest prime number }
}
public class LowestPrimeNumber : IArrayPerformer
{
int GetAnswer(int[] arr) { // return lowest prime number }
}
Then, I created a class and enum which only purpose is to choose what action to be done in arrays..
class ActionChooser
{
public IArrayPerformer imath(MathAction mathAction)
{
IArrayPerformer getMath = null;
switch(mathAction)
{
case MathAction.HighestNumber:
getMath = new HighestNumber();
break;
case MathAction.LowestNumber:
getMath = new LowestNumber();
break;
case MathAction.MiddleNumber:
getMath = new MiddleNumber();
break;
case MathAction.LowestPrimeNumber:
getMath = new LowestPrimeNumber();
break;
case MathAction.HighestPrimeNumber:
getMath = new HighestPrimeNumber();
break;
}
return getMath;
}
}
public enum MathAction
{
LowestNumber = 1,
HighestNumber = 2,
MiddleNumber = 3,
LowestPrimeNumber = 4,
HighestPrimeNumber = 5
}
Lastly, I created a class for making it all possible..
public class Math
{
private ActionChooser mathChooser = new ActionChooser();
public int ReturnAnswer(MathAction mathAcs, int[]arr)
{
return mathChooser.imath(mathAcs).GetAnswer(arr);
}
}
Then, I implemented it like this..
static void Main()
{
int[] arr = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
//This is what I see when I am implementing .NET built-in codes
//which is I only have to create object, use its method,
//pass a small count of arguments, and see the output without
//knowing the logic behind the codes. I think this is what they
//called abstraction. Am I right? It's awesome.
Math math = new Math();
Console.WriteLine(math.ReturnAnswer(MathAction.LowestNumber, arr));
Console.ReadKey();
}
Now, my question is, am I doing it right or wrong? If i'm wrong (which is I know most probably), which part of this code is wrong. Could you explain why and suggest a better solution.