I\'m a newbie in software development. Just wondering which code is better and w
ID: 645943 • Letter: I
Question
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.
Explanation / Answer
It actually depends. I would only create a Class which contains instance attributes if more than one of its methods uses it. On the other hand, if an attribute (or variable) is only used inside the method, then it should be defined local to the method it uses.
In the example you describe, I think that you are using functions instead of methods, which to me seems like they are independent between each method execution. (This comes from the "test" word).
If both objects instances you plan to use are the same, maybe define in the class level and instantiate both in the setup method.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.