which declaration/instantiation is better and WHY ?
public class MainWindow
{
private Test _test;
public MainWindow()
{
_test = new Test();
}
}
OR
public class MainWindow
{
private Test _test = new Test();
public MainWindow()
{
}
}
Ask yourself this question: what happens when you add other constructors to MainWindow
? Do you want to then have to remember to invoke other constructors to ensure that _test
is correctly initialized? Or is it okay for _test
to not be initialized if another constructor is used?
Personally when creating a UI component I would move as many points of failure out of the constructor as possible, and I would move something like that to either the Loaded
event handler, or keep it as you did in option 2 (which keeps the initialization nicely localized in the file).
I'd go for a third option:
public class MainWindow
{
private Test _test;
public MainWindow(Test test)
{
_test = test;
}
}
By injecting the dependency you make your code easier to unit test.
It's better to do it inside the constructor to make it plain what's happening when the object is created, especially when you go to write subclasses.
Generally though it's a matter of taste and the most important thing is to be consistent in your choice.
This is the same as the difference between
int i;
...
i = 0;
and
int i = 0;
My opinion is that the initialization should be close to the declaration if possible, in ideal case a part of it. Beside the bonus in readability you get smaller chances to forget the initialization. So the 2nd variant is a better one.
I don't think you can say that one declaration is better then the other, it's all about the logic of your form, if you don't want to initiate Test on the form start-up, but on a button click then the first declaration is better.
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