Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to put a database initialization call in a C# constructor? [closed]

I've seen this is various codebases, and wanted to know if this generally frowned upon or not.

For example:

public class MyClass
{
   public int Id;

   public MyClass()
   {
      Id = new Database().GetIdFor(typeof(MyClass));
   }
}
like image 533
casademora Avatar asked Oct 01 '08 21:10

casademora


3 Answers

There are several reasons this is not generally considered good design some of which like causing difficult unit testing and difficulty of handling errors have already been mentioned.

The main reason I would choose not to do so is that your object and the data access layer are now very tightly coupled which means that any use of that object outside of it original design requires significant rework. As an example what if you came across an instance where you needed to use that object without any values assigned for instance to persist a new instance of that class? you now either have to overload the constructor and then make sure all of your other logic handles this new case, or inherit and override.

If the object and the data access were decoupled then you could create an instance and then not hydrate it. Or if your have a different project that uses the same entities but uses a different persistence layer then the objects are reusable.

Having said that I have taken the easier path of coupling in projects in the past :)

like image 95
user9930 Avatar answered Nov 21 '22 22:11

user9930


Well.. I wouldn't. But then again my approach usually involves the class NOT being responsible for retrieving its own data.

like image 30
NotMe Avatar answered Nov 21 '22 20:11

NotMe


You can use the disposable pattern if you refer to a DB connection:

public class MyClass : IDisposable
{
    private Database db;
    private int? _id;

    public MyClass()
    {
        db = new Database();
    }

    public int Id
    {
        get
        {
            if (_id == null) _id = db.GetIdFor(typeof(MyClass));
            return _id.Value;
        }
    }

    public void Dispose()
    {
        db.Close();
    }
}

Usage:

using (var x = new MyClass()) 
{
    /* ... */

} //closes DB by calling IDisposable.Dispose() when going out of "using" scope
like image 40
Mark Cidade Avatar answered Nov 21 '22 21:11

Mark Cidade