Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an object in the constructor or at top of the class

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()
   {

   }
}
like image 987
Elisabeth Avatar asked Nov 18 '10 21:11

Elisabeth


5 Answers

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

like image 194
slugster Avatar answered Nov 15 '22 11:11

slugster


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.

like image 36
Jackson Pope Avatar answered Nov 15 '22 11:11

Jackson Pope


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.

like image 34
izb Avatar answered Nov 15 '22 11:11

izb


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.

like image 1
Vlad Avatar answered Nov 15 '22 10:11

Vlad


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.

like image 1
Stefan P. Avatar answered Nov 15 '22 11:11

Stefan P.