Creating an object that is ready to be used & unset properties - with IoC
Posted
by
GetFuzzy
on Programmers
See other posts from Programmers
or by GetFuzzy
Published on 2014-06-01T20:10:47Z
Indexed on
2014/06/01
21:53 UTC
Read the original article
Hit count: 253
I have a question regarding the specifics of object creation and the usage of properties. A best practice is to put all the properties into a state such that the object is useful when its created. Object constructors help ensure that required dependencies are created.
I've found myself following a pattern lately, and then questioning its appropriateness.
The pattern looks like this...
public class ThingProcesser
{
public List<Thing> CalculatedThings { get; set; }
public ThingProcesser()
{
CalculatedThings = new List<Thing>();
}
public double FindCertainThing()
{
CheckForException();
foreach (var thing in CalculatedThings)
{
//do some stuff with things...
}
}
public double FindOtherThing()
{
CheckForException();
foreach (var thing in CalculatedThings)
{
//do some stuff with things...
}
}
private void CheckForException()
{
if (CalculatedThings.Count < 2) throw new InvalidOperationException("Calculated things must have more than 2 items");
}
}
The list of items is not being changed, just looked through by the methods. There are several methods on the class, and to avoid having to pass the list of things to each function as a method parameter, I set it once on the class. While this works, does it violate the principle of least astonishment?
Since starting to use IoC I find myself not sticking things into the constructor, to avoid having to use a factory pattern. For example, I can argue with myself and say well the ThingProcessor really needs a List to work, so the object should be constructed like this.
public class ThingProcesser
{
public List<Thing> CalculatedThings { get; set; }
public ThingProcesser(List<Thing> calculatedThings)
{
CalculatedThings = calculatedThings;
}
}
However, if I did this, it would complicate things for IoC, and this scenario hardly seems appropriate for something like the factory pattern.
So in summary, are there some good guidelines for when something should be part of the object state, vs. passed as a method parameter? When using IoC, is the factory pattern the best way to deal with objects that need created with state? If something has to be passed to multiple methods in a class, does that render it a good candidate to be part of the objects state?
© Programmers or respective owner