views:

49

answers:

2

The title to this question isn't written very well. Sorry 'bout that.

I'm curious what the pros or cons would be to increasing the scope of an object instance within a method to the class level.

As a specific example, I have a non-static service class that wraps access to a repository class which is used to manage CRUD activity as well as some other tasks that don't necessarily mix well with other business logic. As I'm building this out, each method creates it's own instance of this repository. Assuming an average amount of traffic (nothing huge), I'd like to know if there's any benefit to creating a class level instance of this repository in the service class' constructor as opposed to the method level scope I'm currently using. This app is not currently using DI, although that might be an option. I'm also considering making the class static, but I have some other hurdles to jump through before that's an option.

Thanks in advance.

+3  A: 

Your code doesn't even work yet, and already you're optimizing. Stop! Make your code work, then analyze the performance and optimize for the performance problems you actually have, instead of the problems you think you might turn out to have.

Don't guess wrong and solve the wrong problem, or make things worse!

John Saunders
This is definitely good advice. I'm looking to create good habits or modify bad, and that was the real intent of the question (trying to gauge what other more seasoned developers are doing).
mannish
A: 

+1 to John Saunders

In addition to that, let me comment:

I'd like to know if there's any benefit to creating a class level instance of this repository in the service class' constructor as opposed to the method level scope I'm currently using

Is it expensive to create the repository class? By "expensive" I mean has a profiler shown you that it is making a noticeable contribution to the running time of your application.

If so, you might want to cache it in an instance variable. If not, keep it local. As soon as you promote it to an instance variable you bring upon yourself a host of problems such as

  • Who creates it first?
  • What happens when 2 threads access the same instance?
  • Who cleans it up? Does anyone? (the using statement is no longer an option)
  • Does this mean you need to write a finalizer for your class? (ugh)
  • If it needs parameters to create it, who supplies them?
  • What happens if it needs to change or get re-created between method calls?

The old "Global Variables are Evil" quote is IMHO just the most common case of "shared state is evil", which is the actual problem.

Orion Edwards
This is what I was looking for, examples of what could crop up if I globalized the repository within the class. Add it to John's response and I have what I need. I haven't gotten so far as to run this against a profiler, but I will do so as I get further along. Thanks again for the tips fellas.
mannish