Declare Variables Close To First Use

What’s wrong with this function?

  private void ValidateCustomerOrders(int customerId)
  {
     Customer customer;

     // 23 lines of code

     // First use of variable customer
     customer = _database.GetCustomer(customerId);

     string customerName;

     // Another 8 lines of code

     // First use of variable customerName
     customerName = customer.Name;

     // ...
  }

It’s simply this: variables customer and customerName are declared too early—way before they are assigned.

Let’s fix this:

  private void ValidateCustomerOrders(int customerId)
  {
     // 23 lines of code

     Customer customer = _database.GetCustomer(customerId);

     // Another 8 lines of code

     string customerName = customer.Name;

     // ...
  }

As much as possible, I like to combine variable declaration and assignment on the same line. 

Why? 

Code is easier to understand when variable declaration and assignment use are close together—ideally on the same line. Spacial distance produces a disconnect in people’s minds.

For example, when I read through an unfamiliar function and come across a newly declared local variable, I expect it to be used immediately. Yet, when that’s not the case, I start forgetting about the variable—in a long function, there is usually too much other behaviour to understand. Then, when the variable reappears, I need to interrupt my flow and jump back to its declaration to understand its purpose.

This process makes for a frustrating, disruptive programming experience.

To the best of our abilities, we want to avoid frustrating our fellow programmers as well as our future selves. Our code ought to be readily understandable without having to jump back and forth. It’s a sign of a master programmer to produce clear code that avoids taxing our cognition.

 

Keep in mind that sometimes we cannot combine declaration and first use on the same line:

  bool haveCustomers = true;
  int pageNumber = 1;
  var customerList = new List<Customer>();
  while (haveCustomers)
  {
     var customers = Database.GetPagedCustomers(pageNumber, PAGE_SIZE);
     if (customers.Count < PAGE_SIZE)
        haveCustomers = false;
     customerList.AddRange(customers);
     pageNumber++;
  }

Variables haveCustomers, pageNumber and customerList are declared before being used in the loop. And that’s as it should be. Notice that these variables are declared immediately before the loop.

 

I recommend you initialise variables when you declare them. 

A variable’s declaration should be close to its first use.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply