Improve class coherency with local functions
I was full of doubt about local functions at first. They break some dogmas for me. For example, return from the method isn't the last statement anymore.
Then I started to use them. Now I can say that this idea makes code more readable and keep classes more coherent.
Before introducing local functions in C# 7, extracting part of the code required a private method. Of course, one can say that it's still hidden from the outside, but it always felt awkward.
Take this code:
class PersonCreator {
public Person CreatePerson(string login, string email)
{
if (!string.IsNullOrWhiteSpace(login) && EmailIsValid(email))
return new Person(login, email);
return null;
}
private bool EmailIsValid(string email) =>
Regex.IsMatch(email,
@"^[^@\s]+@[^@\s]+\.[^@\s]+$");
}
public record Person(string Login, string Email);
This approach isn't flawed. But like EmailIsValid method shouldn't be part of the PersonCreator class, even a private one.
How can we refactor this to a local function?
Our method could look like this:
Person CreatePerson(string login, string email)
{
if (!string.IsNullOrWhiteSpace(login) && EmailIsValid())
return new Person(login, email);
return null;
bool EmailIsValid() =>
Regex.IsMatch(email,
@"^[^@\s]+@[^@\s]+\.[^@\s]+$");
}
We can skip a parameter because of closure.
In the end, it will get compiled to the private method anyway. But I found this code cleaner and easier to maintain.
What's your approach to local functions?