samedi 28 février 2015

Create the fields in class level then instantiate inside methods or create and instantiated inside methods


I'm a newbie in software development. Just wondering which code is better and why should I continue which pattern should I follow.


First Snippet:



Class TestClass
{
private Object1 field = null;
private Object2 field2 = null;

public void TestMethod1()
{
field = new Object1();
field2 = new Object2();
}

public void TestMethod2()
{
field = new Object1();
field2 = new Object2();
}
}


As you can see, I created fields in Class level and instantiate them inside the method.


Second Snippet:



Class TestClass
{

public void TestMethod1()
{
Object1 field = new Object1();
Object2 field2 = new Object2();
}

public void TestMethod2()
{
Object1 field = new Object1();
Object2 field2 = new Object2();
}
}


Here I created and instantiated the fields.


These fields are being used over and over in many methods in a class.





Aucun commentaire:

Enregistrer un commentaire