Code inspection: Add explicit 'return' or 'continue' before local functions
Category: Common Practices and Code Improvements
ID: SeparateLocalFunctionsWithJumpStatement
EditorConfig: resharper_separate_local_functions_with_jump_statement_highlighting
Language: C#
Requires SWA: No
tip
When you have one or more local functions defined at the end of a method, JetBrains Rider suggests adding an explicit return
between the last executable statement and the local function definition. The method will return at that point anyway, but making this explicit will enhance the clarity of the method's control flow for readers. This is particularly beneficial if the local function definition is lengthy, or if there are multiple local functions. In these instances, the reader will not have to scroll to the end of the method to check for more executable statements after the local function definitions.
Here is an example:
Suboptimal code
void Process(string[] lines){ foreach (var line in lines) { if (IsValid(line)) { Console.WriteLine(line); } } Console.WriteLine("finishing"); bool IsValid(string str) { return str.Length > 0; }}
After the fix
void Process(string[] lines){ foreach (var line in lines) { if (IsValid(line)) { Console.WriteLine(line); } } Console.WriteLine("finishing"); return; bool IsValid(string str) { return str.Length > 0; }}
The same applies when a local function is defined inside a block. In such cases, adding an explicit continue
statement makes the structure of the block more comprehensible:
Suboptimal code
void Process(string[] lines){ foreach (var line in lines) { if (IsValid(line)) { Console.WriteLine(line); } bool IsValid(string str) { return str.Length > 0; } }}
After the fix
void Process(string[] lines){ foreach (var line in lines) { if (IsValid(line)) { Console.WriteLine(line); } continue; bool IsValid(string str) { return str.Length > 0; } }}