Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a value multiple times or store as a variable first time round?

Basically, is it better practice to store a value into a variable at the first run through, or to continually use the value? The code will explain it better:

TextWriter tw = null;
if (!File.Exists(ConfigurationManager.AppSettings["LoggingFile"]))
{
   // ...
   tw = File.CreateText(ConfigurationManager.AppSettings["LoggingFile"]);
}

or

TextWriter tw = null;
string logFile = ConfigurationManager.AppSettings["LoggingFile"].ToString();
if (!File.Exists(logFile))
{
    // ...
    tw = File.CreateText(logFile);
}
like image 610
Neil Knight Avatar asked Oct 13 '22 17:10

Neil Knight


1 Answers

Clarity is important, and DRY (don't repeat yourself) is important. This is a micro-abstraction - hiding a small, but still significant, piece of functionality behind a variable. The performance is negligible, but the positive impact of clarity can't be understated. Use a well-named variable to hold the value once it's been acquired.

like image 104
Rex M Avatar answered Nov 16 '22 22:11

Rex M