Too many local variables in ASP.NET
I wrote a control, and use a tool to do the code analysis. There is a test that I didn't pass. Avoid excessive locals, http://msdn.microsoft.com/library/ms182263(VS.90).aspx.
In my CreateChildControls function, I built a big table with lots of field. I need to create a lot of TableRow and TableCell to construct the table. But these are not field or property of control. Thery are local variables in the function, which are created dynamically.
Should I make the开发者_C百科se TableCells and TableRows as fields of the control? Or I just keep them as the local variables in the CreateChildControl function?
Best Regards,
First of all, I would suggest that you consider using a Repeater control instead of dynamically creating lots of rows and cells in the backend code. By using a Repeater
, you can more easily modify the actual markup without having to go through hundreds of lines of code to find it.
But if that's not an option, then consider the question: Do you actually need to have a unique variable for each one? Could you instead do something like this:
TableRow tr;
TableCell tc;
tr = new TableRow();
tc = new TableCell();
tc.Text = "whatever";
tr.Cells.Add(tc);
table.Rows.Add(tr);
tr = new TableRow();
tc = new TableCell();
tc.Text = "whatever # 2";
tr.Cells.Add(tc);
table.Rows.Add(tr);
That is, reuse the same variable for multiple rows/cells.
Code analysis rules should always be used as a guideline - if you're satisfied with a solution that violates a rule, add an exception and move on to harder problems.
That said, eliminating local variables is often as easy as extracting methods (and classes if appropriate) to implement the desired logic. In your case, you may have a method to construct a TableRow
which calls other methods to construct each TableCell
. This has the additional benefit of making your CreateChildControls
method easier to read and test.
Update: To answer your question about promoting the variables to fields, I would suggest avoiding fields unless they are absolutely necessary. In this case, they don't appear to be, so you would be better off keeping them as local within the relevant method.
精彩评论