Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# constructor design

Tags:

c#

constructor

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");
like image 478
Coding Monkey Avatar asked Jun 08 '09 05:06

Coding Monkey


2 Answers

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
}
like image 198
Tom Anderson Avatar answered Oct 24 '22 15:10

Tom Anderson


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();
like image 42
Cerebrus Avatar answered Oct 24 '22 15:10

Cerebrus