I'm a newbie in software development. Just wondering which code is better and why should I continue which pattern I should 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.