I have a class which you pass in a folder and then it goes off and processes a lot of data within the specified folder.
For instance:
MyClass myClass = new MyClass(@"C:\temp");
Now it goes off and reads say a couple of thousand files and populates the class with data.
Should I move this data out from the constructor and have it as a separate method, such as the following?
MyClass myClass = new MyClass();
myClass.LoadFromDirectory(@"C:\temp");
Maybe you should try it this way with a static method that returns an instance of the object.
var myClass = MyClass.LoadFromDirectory(@"C:\temp");
This will keep the initialization code outside of your constructor, as well as giving you that "one line" declaration you are looking for.
Going on the comment from below from the poster, by adding State an implementation could be like so:
public class MyClass
{
#region Constructors
public MyClass(string directory)
{
this.Directory = directory;
}
#endregion
#region Properties
public MyClassState State {get;private set;}
private string _directory;
public string Directory
{
get { return _directory;}
private set
{
_directory = value;
if (string.IsNullOrEmpty(value))
this.State = MyClassState.Unknown;
else
this.State = MyClassState.Initialized;
}
}
#endregion
public void LoadFromDirectory()
{
if (this.State != MyClassState.Initialized || this.State != MyClassState.Loaded)
throw new InvalidStateException();
// Do loading
this.State = MyClassState.Loaded;
}
}
public class InvalidStateException : Exception {}
public enum MyClassState
{
Unknown,
Initialized,
Loaded
}
It depends. You should evaluate the basic purpose of the class. What function does it perform?
What I usually prefer is to have a class constructor do the initialization necessary for the functioning of the class. Then I call methods on the class which can safely assume that the necessary initialization has been done.
Typically, the initalization phase should not be too intensive. An alternative way of doing the above may be:
// Instantiate the class and get ready to load data from files.
MyClass myClass = new MyClass(@"C:\temp");
// Parse the file collection and load necessary data.
myClass.PopulateData();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With