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.
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.
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.
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