For instance, if I have an class:
public class StuffHolder
{
List<Stuff> myList;
public StuffHolder()
{
myList = newList<Stuff>();
myList.Add(new Stuff(myList));
myList[0].stuffHappens();
}
}
and a Stuff Object:
public class Stuff
{
List<Stuff> myList;
public Stuff(List<Stuff> myList)
{
this.myList = myList;
}
public void stuffHappens()
{
myList.Remove(this);
}
}
What are the disadvantages of calling stuffHappens() rather than having stuff pass the information that it should be removed to the StuffHolder class and having the StuffHolder class remove that specific Stuff?
There’s a hazard if stuffHappens() ever occurs in more than one thread at a time, as the
List<T>collection is not thread-safe.The bigger hazard is the confusion of responsibility, as it probably shouldn’t be the job of Stuff to know about it being stored in a collection. This kind of design ‘fuzziness’ causes steadily increasing confusion as systems grow and evolve.