This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Hi! I have a question about where to create objects, I m wondering whether it is better to create an class variable in instance, or to put the direct declaration in a method if the object is used by only one method of the class. I m wondering about this because it might be more efficient to create a class variable (and hence an object of the class which method is called) in the single method interested in in using it. Hope the question was clear, Daniel
Si altas son las torres, el valor es alto - Alberti
Dan, one of the points of Java programming is to efficiently utilize your system memory. Your point about instantiating objects in only the methods that require them is valid, however you have to look at the scope of the project. You may ask yourself, does this use up more memory if I declare the Object now or declare it in the main method? I usually try to only create "new" memory space when it is absolutely necessary. Soon you will learn about big O notation and omega and theta and little o for better memory usage. But for now, just stick to the formats that you are instructed with. You will soon see which is the best way to do it.
If, as you say, only one method needs the variable, and as long as the value does not need to persist between successive calls to that method, then yes definitely put it inside the method. That's better design, plus then you needn't worry about possible threading issues as well, as each thread invoking the method will get their own copy.
Joined: Mar 02, 2003
Yo, BB, sorry it got out of hand on the other page bro. I shouldn't have said anything. You are a great contributor to this forum. You da man bro. Gabe