Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OOP in General and C# in Particular - Should the constructor return quickly?

Tags:

c#

oop

I'm currently refactoring some old code for my work. Some idiot (me, 2 years ago) wrote a few things that I think stink. I have this feeling in my gut (I've might read somewhere and forgotten the source) that a constructor in C# should return quickly, because of some technical detail, possibly to do with garbage collection. I.e. the following

class A
{
     public object Result {get; private set;}
     private object RunLongOperation(){/* ... */}
     public A(){
         Result = RunLongOperation();
     }
}

is bad practise. So my question is twofold - Is it actually bad, and if so why? The above can be rewritten as

class A
{
     public object Result {get; private set;}
     private static object RunLongOperation(){/* ... */}
     private A() { }
     public static A Make(){
        return  new A { Result = RunLongOperation() };
     }
}

through a kind of factory static method. This to me just seems more code than necessary, but the actual object is constructed quickly.

To shine a light, the constructor takes a few parameters and renders an image in RunLonOperation(), and does some other stuff based on the input parameters. The class then reduces to immutable result container. The operation takes about 10 to 20 seconds, based on parameters.

like image 323
Gleno Avatar asked Nov 04 '11 22:11

Gleno


2 Answers

Yes doing real work in a constructor is a bad thing from a testability point of view.

It is very hard to write a test for a class that does heavy work in the constructor because you don't have any means left to change the dependencies needed for that object or to inject some custom behaviour by mocking the object.

See http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/ for a good explanation of this design flaw.

like image 182
catalin.costache Avatar answered Oct 05 '22 22:10

catalin.costache


I don't think there should be a general rule for this, but in fact it's better to use factory pattern and do not handle too many things in constructor.

like image 26
Saeed Amiri Avatar answered Oct 05 '22 23:10

Saeed Amiri