I want to move a bunch of similar methods to an external class. The class is initialized with the original class instance. From there I can access it either by property (persistent instance) or by method (new instance each time).
Which approach is favorable? In a real system I will have many of these classes holding many methods. I would like to hear your opinions and knowledge.
EXAMPLE:
I have a class, let's call it Zoo, and in my Zoo class I hold Lists of animals.
(These animals have no common properties or methods where an interface or inheritance would be applicable, this is purely to paint an example.)
public class Zoo
{
public List<Monkey> MonkeyList;
public List<Lion> LionList;
public List<Turtle> TurtleList;
public Zoo()
{
MonkeyList = new List<Monkey>();
LionList = new List<Lion>();
TurtleList = new List<Turtle>();
}
}
Now I want to add animals to my Zoo, so I create some Add methods.
Instead of putting them directly to my Zoo class, I add them to a separate class and pass my Zoo instance, like so:
public class ZooAdd
{
private Zoo _zoo;
public ZooAdd(Zoo zoo)
{
_zoo = zoo;
}
public void Monkey(Monkey monkey)
{
_zoo.MonkeyList.Add(monkey);
}
public void Lion(Lion lion)
{
_zoo.LionList.Add(lion);
}
public void Turtle(Turtle turtle)
{
_zoo.TurtleList.Add(turtle);
}
}
Now I need to add the animals, but faced with two options, unsure which is preferable:
Option 1: I create a property
public class Zoo
{
public ZooAdd Add;
public Zoo
{
Add = new ZooAdd(this);
}
}
...
Zoo zoo = new Zoo();
Monkey monkey = new Monkey();
zoo.Add.Monkey(monkey);
Option 2: I create a method returning an instance (Factory pattern?)
public class Zoo
{
public ZooAdd Add()
{
return new ZooAdd(this);
}
}
...
Zoo zoo = new Zoo();
Monkey monkey = new Monkey();
zoo.Add().Monkey(monkey);
Both approaches satisfy the requirements and have little difference in appearance.
I believe that the second option may prove more useful for memory efficiency as the object created through the method is presumably eaten up by the GC after it's used but I have no concrete knowledge regarding that statement.
Please, lend me your wisdom.
EDIT:
You've all raised some justified concerns about my approach and I agree that it can be improved. I will be revising the structure of my classes with your suggestions and assistance in mind. Thank you all for your answers.
List<Animal>
? (assuming all mentioned animals inherit from a baseAnimal
class) Do you have an actual need to separate the animals in separate lists?