This week's book giveaway is in the Jython/Python forum.
We're giving away four copies of Murach's Python Programming and have Michael Urban and Joel Murach on-line!
See this thread for details.
Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Discuss- When to use local variable and instance variable?  RSS feed

 
Lim Cody
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I've a DAO class (not a singleton) like below
code 1( instance variable):

ArrayList "parametes" would be reused for more than one method if there are more methods are added in the future



code 2(local variable):


What is your view of the performance, best practice and etc on both sample code?
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13078
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the code you show, parametes is created new (line 6) for every query so why not keep it local.

In any case, since a database query is involved, the query takes almost all the time and there will be no measurable difference.

Just go for clarity of expression and security rather then trying to shave microseconds.

Bill
 
Saifuddin Merchant
Ranch Hand
Posts: 607
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For one I'll keep the query as a final static string of the class. Its more from the maintenance/readability and style benefit rather than performance.

As for the ArrayList its better to have it as a local variable inside the method. One reason is if the Object is involved in multi-threaded invocations it would be thread safe. Having the ArrarList as a member variable gives no benefit.

Also in simple O-O terms, parametes does not seem to be a 'property' of UserDaoImpl.
 
Poobhathy Kannan
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i would prefer to keep the parameters list inside the method as it would be thread safe in a multi thread environment. And i would suggest to load the quarries form a properties file,cache it and use it, so that you will not need to change the source code for any changes in query

Apart from 'parameters' list and query, i would also suggest to change the method signature to return List than ArrayList. Always better to have the return type as an interface unless you have any special reasons to return the concrete class.it hides the internal implementation and also flexible for any internal changes.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!