How Long Should Variable Names Be?

variable name

 

Large functions have their problems. As a general rule, the longer a function, the more descriptive we should name our variables. 

Why is this necessary? When a function has many variables floating around—parameters, locals, return values, fields—it’s easy to get them mixed up. Long and descriptive names allow us to remember the purpose of each reference more reliably.  

On the other hand, when a function has few lines, a short variable name will do.

For example:

  private void Validate(CustomerRegistration reg)
  {
     if (reg == null)
        throw new MissingCustomerRegistration();            
     reg.Validate();
     var cust = Repository.GetCustomer(reg.EmailAddress);
     if (cust != null)
        throw new CustomerAlreadyExists(reg.EmailAddress);
  }

This method is only six lines. The parameter is reg. Even though the parameter name is abbreviated, the meaning of reg is clear. Temporary variable cust is unambiguous as well – it holds the looked-up customer.

Could we have named the parameter registration? Yes, sure, that would be OK, although it’s starting to get a bit long. How about customerRegistration? Hmm, maybe not. The customer prefix only adds length to the variable, not further understanding. After all, there is only one registration. customerRegistration is so long it’s making the function less readable. 

Let’s try it out:

  private void Validate(CustomerRegistration customerRegistration)
  {
     if (customerRegistration == null)
        throw new MissingCustomerRegistration();            
     customerRegistration.Validate();
     var cust = Repository.GetCustomer(customerRegistration.EmailAddress);
     if (cust != null)
        throw new CustomerAlreadyExists(customerRegistration.EmailAddress);
  }

Beauty is obviously in the eye of the beholder; however, I perceive customerRegistration as too long. Fully spelling out the parameter is starting to obscure the function logic.

The longer the function, the more descriptive variable names should be to avoid confusion with other variables. Long functions tend to have much going on. Labelling the many moving parts becomes essential to understanding.

Here is an example of a more extended function:

   public ApiResponse Post([FromBody]CourseCreationRequest course)
   {
      Course returnCourse = new Course();
      if (string.IsNullOrWhiteSpace(course.name))
      {
         throw new ExceptionFromBadRequest("Course attributes missing") { userMessage = "Course Name is missing." };
      }
      if (course.Id != null && course.Id.Length > 1)
      {
         returnCourse = _courseService.UpdateCourse(course);
         if (returnCourse.Id == null)
         {
            throw new Exception("Error in updating course. ");
         }
         else
         {
            var topics = _topicService.GetTopicByCourse(returnCourse.Id);
            var premiumTopics = topics.Select(t => t.Id).Except(course.freeTopics == null ? new List<string>() : course.freeTopics).ToList();
            _topicService.updateTopicsPremiumStatus(course.freeTopics, premiumTopics);
            topics = _topicService.GetTopicByCourse(returnCourse.Id);
            var courseResponse = new CourseDetailsResponse(returnCourse);
            courseResponse.freeTopics = topics.Where(c => c.paidContent != true).Select(c => c.Id).ToList();
            response.payload = getCourseView(new List<Course> { returnCourse }, false).Single();
         }
         return response;
      }
      returnCourse = _courseService.InsertCourse(course);
      if (returnCourse.Id == null)
         throw new BaseException("Error in inserting course Please check the course body. ");
      else
         response.payload = getCourseView(new List<Course> { returnCourse }, false).Single();
      return response;
   }

At over 20 lines of code, this method is a bit long. It appears to be doing a few things with courses. There are at least two course-related variables, the parameter course and a local returnCourse. returnCourse becomes part of the returned payload. Thus the naming of returnCourse sort of works.

Imagine returnCourse had been abbreviated to rc. Readability would have been adversely affected. When trying to understand the detailed operation of longer methods, developers must often keep several variables at the forefront of their minds. Encountering a highly abbreviated, non-descriptive variable, like rc, a developer may need to review the declaration and use of rc multiple times. This refamiliarisation with the variable is a disruptive process and makes the function challenging to read and understand. A descriptive variable name contains meaning and requires fewer lookups of declaration and usage.

So, variable names should vary in length and descriptiveness in proportion to function length. Short functions ought to have short variable names. For clarity’s sake, large functions need extended, more descriptive variables.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply