I am working on trying to understand the SOLID object oriented design principles. I was able to get the "SOL" pretty easily, though "L" required some hand holding because I am bad at definitions. I think I understand the "I" (I might not, which may belie my confusion). But "D" or Dependency Inversion is tripping me up. Depending on abstractions, rather than concretions makes sense in a way, but the actual application is tripping me up, especially when the term "new is glue" is thrown around in there. Can you tell me where I am going wrong in a code example as I am struggling to make the leap from concept to concrete.
Say I have some abstract class in C#:
public abstract class IMakeAnIntSetArray
{
public void Populate(int FirstItem, int NumberOfItems)
{
mySet.Add(FirstItem);
NumberOfItems--;
for (int i = 0; i < NumberOfItems; i++)
{
mySet.Add(GetNext());
}
}
protected abstract int GetNext();
protected List<int> mySet;
public List<int> Set
{
get { return mySet; }
}
}
It is implemented by the classes
public class CountNumbersLikeAHuman : IMakeAnIntSetArray
{
protected override int GetNext()
{
int next = mySet.Last();
next++;
return next;
}
}
and
public class SomeMathInvolved : IMakeAnIntSetArray
{
protected override int GetNext()
{
int next = mySet.Last();
if(next % 2 == 0)
{
return next / 2;
}
else
{
return ((next * 3) + 1);
}
}
}
Is either of the following a correct way to apply the dependency inversion principle or am I missing something? How would I tweak this to properly utilize the DIP? Or Am I just hung up on "new is glue"?
class Program
{
static void Main()
{
CountNumbersLikeAHuman simpleEnough = new CountNumbersLikeAHuman(); //wrong?
SomeMathInvolved akaChangeYourMajorToEnglish = new SomeMathInvolved(); //also wrong?
//Or . . .
IMakeAnIntSetArray useYouFingersAndToes = new CountNumbersLikeAHuman();
IMakeAnIntSetArray makeItWayMoreComplicated = new SomeMathInvolved();
//Or am I completely off here?
}
}
I
prefix, such as withIMakeAnIntSetArray
for abstract classes in C#.I
denotes an interface, not an abstract class. You'll cause great confusion for others reading your code if you do this.