Note that there are some explanatory texts on larger screens.

plurals
  1. POIs it good practice to create once-used variables?
    text
    copied!<p>A colleague of mine refactored this code:</p> <pre><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); } </code></pre> <p>to this code:</p> <pre><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)); } </code></pre> <p>saying that you don't need to create a variable if it is only going to be used once.</p> <p>My response was that making once-used variables is good practice since it:</p> <ul> <li>functions as and reduces comments (it is clear what "userControlFullName" is)</li> <li>makes code easier to read, i.e. more of your code "reads like English"</li> <li>avoids super-long statements by replacing parts of them with clear variable names</li> <li>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</li> </ul> <p>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.</p> <p>Can anyone think of any situations in which one should not create once-used variable names?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload