Alex Rivera | Logout

Is it good practice to create once-used variables?

Asked 2009-02-20T08:41:08.010
26

A colleague of mine refactored this code:

private void btnGeneral_Click(object sender, RoutedEventArgs e)
{
    Button button = (Button)e.OriginalSource;
    Type type = this.GetType();
    Assembly assembly = type.Assembly;
    string userControlFullName = String.Format("{0}.{1}", type.Namespace, button.Name);
    UserControl userControl = (UserControl)assembly.CreateInstance(userControlFullName);
}

to this code:

private void btnGeneral_Click(object sender, RoutedEventArgs e)
{
    Button button = (Button)e.OriginalSource;
    Type type = this.GetType();
    Assembly assembly = type.Assembly;
    UserControl userControl = (UserControl)assembly.CreateInstance(String.Format("{0}.{1}", type.Namespace, button.Name));
}

saying that you don't need to create a variable if it is only going to be used once.

My response was that making once-used variables is good practice since it:

  • functions as and reduces comments (it is clear what "userControlFullName" is)
  • makes code easier to read, i.e. more of your code "reads like English"
  • avoids super-long statements by replacing parts of them with clear variable names
  • easier to debug since you can mouse over the variable name, and in the cases of e.g. PHP programming without debuggers, it is easier to echo out these variable names to get their values

The arguments against this way "more lines of code", "unnecessary variables" are arguments to make life easier for the compiler but with no significant speed or resource savings.

Can anyone think of any situations in which one should not create once-used variable names?

Edit
Report

2 Answers

6

I'm completely with you on this one.

I especially use this if a method takes a lot of booleans, ie

public void OpenDocument(string filename, bool asReadonly, bool copyLocal, bool somethingElse)

To me this is a lot more readable:

bool asReadonly = true;
bool copyLocal = false;
bool somethingElse = true;

OpenDocument("somefile.txt", asReadonly, copyLocal, somethingElse);

..than:

OpenDocument("somefile.txt", true, false, true);
answered 2009-02-20T08:47:12.910
0

That's how I used to code. Nowadays I tried to minimize intermediate variables. The use of intermediate variables is perfectly fine if it's immutable.

answered 2009-02-20T09:29:58.783

Your Answer