tags:

views:

242

answers:

3

I've been spending some time refactoring my C# code, and I'm struck by how large my parameter lists are getting for local variables, especially when you start getting several levels deep and have to pass local variables from higher up the call stack.

As an example, I have some rather complex code that uses Linq to sql. I instantiate a data context early in a procedure and use it throughout the procedure. However, after refactoring, I find that i'm passing this DC throughout all my sub-methods, along with various other state variables.

One solution, of course, is to make these local variables into member variables, but that makes the entire class non-thread safe, and when dealing with async i/o that means crippling things with locks and mutexes to make them safe.

What are your best practices when factoring in regards to local variables? Do you give in and make them members? or do you carry around the state baggage? Or do you do something else?

EDIT: I'm not sure what more detail you need. I don't want to dump a bunch of code, because by it's nature in order to illustrate this I have to show a very complex set of procedures.

I have a number of local variables, such as a Linq to Sql DC, various stages of processing, various stages of updates of a lot of raw data processed and written to a database.

I thought about creating a state context and passing that, but it seems kind of hackish to me, although I suppose that's precisely what the Linq to SQL dc is.

+3  A: 

Potentially, make them members of another type. Nested types work well here, too. That makes a lot of sense if they form a logical group, and let you write several methods using the same type.

Beyond that, we'd have to know details of what you're doing to comment further I suspect.

Jon Skeet
+3  A: 

Do not turn them into member/global variables. They make reasoning about application state an order of magnitude more difficult, even without multithreading - and with it, as you say, it becomes a total nightmare.

You might try collapsing them into simple objects and passing those around instead, if you notice that certain parameters are always being passed around in groups.

levand
+2  A: 

Depends on the project. I try to aim towards the Single Responsibility Rule which allows me to refactor like a madman.

It happens I create dummy holder classes to hold the information I need to pass around. I don't like to have more than 1 or 2 parameters for my methods either but it depends on how important the information is and most of all how important the project is.

mhenrixon