Putting The Fun In C# Local Functions

Many popular languages support the use of local functions and in C# 7, support for them was announced with relatively little fanfare. As someone that would consider themselves a C# power-user, I seldom took advantage of the feature until I realized just how much it could help with making code more readable, specifically in the context as a replacement for comments/hacks, unit tests, and in general just to clean things up.
 

What are local functions exactly?

 
Local functions are private methods of a type that are nested in another member. They can only be called from their containing member. Local functions can be declared in and called from,
  • Methods, especially iterator methods and async methods
  • Constructors
  • Property accessors
  • Event accessors
  • Anonymous methods
  • Lambda expressions
  • Finalizers
As with most things, sometimes, it's easier to just show you what a local function looks like,
  1. public static IEnumerable<Address> SanitizeAddresses(List<Address> addresses)    
  2. {  
  3.       foreach(Address address in addresses)   
  4.       {  
  5.            yield return Anonymize(address);  
  6.       }  
  7.   
  8.       // This is a local function  
  9.       Address Anonymize(Address address) { ... }  
  10. }  

Cleaning Up Comments with Local Functions

 
Putting The Fun In C# Local Functions 
 
One of the first use cases that comes to mind that functions can help alleviate is any pesky sanitation or business logic rules, particularly those around string manipulation, etc. If you've worked in enough business applications, you've undoubtably seen something terrible with some massive comment as to why it's being done,
  1. public static User ProcessUser(User user)    
  2. {  
  3.       // All names must conform to some crazy Dr. Seuss-eqsue rhyming scheme  
  4.       // along with every other character being placed by its closest numerically  
  5.       // shaped equivalent  
  6.       var seussifyExpression = new Regex("...");  
  7.       user.Name = seussifyExpression.Replace(user.Name, "...");  
  8.       user.Name = user.Name  
  9.                       .Replace(..., ...)  
  10.                       .Replace(..., ...)  
  11.                       .Replace(..., ...);  
  12.   
  13.       // Other processes omitted for brevity  
  14.   
  15.       return user;  
  16. }  
As you can see here, we have a series of chained replacements, some relying on strings, and others relying on regular expressions, which can make a method pretty clunky, especially if there's multiple operations to perform. Now, this is where you can define a local function to encapsulate all this business logic to replace your crazy comment,
  1. public static User ProcessUser(User user)    
  2. {  
  3.       SanitizeName(user)  
  4.   
  5.       // Other processes omitted for brevity  
  6.   
  7.       return user;  
  8.   
  9.       void SanitizeName(User user)  
  10.       {  
  11.           var seussifyExpression = new Regex("...");  
  12.           user.Name = seussifyExpression.Replace(user.Name, "...");  
  13.           user.Name = user.Name  
  14.                           .Replace(..., ...)  
  15.                           .Replace(..., ...)  
  16.                           .Replace(..., ...);  
  17.   
  18.           return user;  
  19.       }  
  20. }  
You could easily name your local function whatever you like, even ApplyBusinessLogicNamingRules() and include any necessary comments for reasoning that you'd like within there (if you absolutely need to answer why you are doing something), but this should help the rest of your code tell you what it's doing without a comment explicitly writing it all out.
 

Going All Reading Rainbow with Local Functions

 
Putting The Fun In C# Local Functions 
 
If readability isn't the single most important thing about code, then it's damn close to the top.
 
LINQ is another popular area that local functions can assist with, especially if you have to do any type of crazy filtering logic over a series of records. You can define a series of local functions that can cover each step of your filtering process (or any process really), and more easily reason about your code from a readability perspective:
  1. public List<int> FindPrimesStartingWithASpecificLetter(List<int> numbers, int startingDigit)    
  2. {  
  3.     return numbers.Where(n => n > 1 && Enumerable.Range(1, n).Where(x => n % x == 0).SequenceEqual(new [] {1, n }))  
  4.                   .Where(n => $"{n}".StartsWith($"{startingDigit}"));  
  5. }    
While succinct, it doesn't exactly read well. Let's take a gander at what it looks like after rubbing some local functions on it,
  1. public List<int> FindPrimesStartingWithASpecificLetter(List<int> numbers, int startingDigit)    
  2. {  
  3.     return numbers.Where(x => IsPrime(x) && StartsWithDigit(x, startingDigit));  
  4.   
  5.     bool IsPrime(int n) => return n > 1 && Enumerable.Range(1, n).Where(x -> n % n == 0).SequenceEqual(new [] { 1, n }));  
  6.     bool StartsWithDigit(int n, int startingDigit) => return $"{n}".StartsWith($"{startingDigit}");  
  7. }   
As you can see, local functions are assisting with wrapping up all the ugly/nasty logic within their own tiny little functions. This is a really trivial case, but as you might imagine if you have lines-upon-lines of code that isn't touching anything outside of one method, it's likely a solid candidate for a local function.
 

Testing, Testing, Lo-ca-lly!

 
Putting The Fun In C# Local Functions 
 
If you've spent any amount of time writing tests, either unit or integration, you are probably familiar with the fabled 'Arrange-Act-Assert` pattern, which is used to separate each piece of functionality when testing a given piece of code as follows,
  • Arrange all necessary preconditions and inputs.
  • Act on the object or method under test.
  • Assert that the expected results have occurred.
As you might imagine, this could lend itself to the pattern well for complex test cases,
  1. public void IsThisAnArrangeActAssertLocalFunction()    
  2. {  
  3.      Arrange();  
  4.      Act();  
  5.      Assert();  
  6.   
  7.      Arrange() { ... }  
  8.      Act() { ... }  
  9.      Assert() { ... }  
  10. }  
Is it practical? Does it fit all use cases? Is it something that you'd ever find yourself using? The answers to all of these might be an overwhelming no, but it does seem like a scenario where local functions could play a role.
 

Choose Your Own Adventure

 
Putting The Fun In C# Local Functions 
 
Local functions present a few interesting options that fit some scenarios better than others. As a replacement for large comments or very messy business logic - absolutely. In unit tests or little one liners - probably not. With most new features, especially those that are sugary, it's really up to you and your team to see if they work for you. While they may seem appealing in some situations, they also seem ripe for abuse, potentially cluttered methods, and other issues that would completely defeat the purpose of using them in the first place.
 
So, if you choose to go down this road of local functions, proceed with care.