Using Lambdas To Increase Code Readability
December 13, 2011 Leave a comment
I was having a spirited debate with Rob Seder yesterday about the use of lambdas – the question was weather using them increases or decreases the codes readability. For example, here is a basic for…each:
1 foreach (Employee employee in employeeFactory.GetAllEmployees()) 2 { 3 if (employee.Name == "Moe") 4 { 5 Console.WriteLine(employee.ToString()); 6 } 7 }
Replacing with a lambda:
1 var moe = employeeFactory.GetAllEmployees().Where(e => e.Name == "Moe").FirstOrDefault(); 2 Console.WriteLine(moe.ToString());
Readability suffers for three reasons: the function chaining. the use of single letters for the variable, and the use of the var keyword. A more readable use of lambda is like so:
1 List<Employee> employeeList = employeeFactory.GetAllEmployees().ToList(); 2 Employee selectedEmployee = employeeList.Where(employee => employee.Name == "Moe").FirstOrDefault(); 3 Console.WriteLine(selectedEmployee.ToString());
Taking the problems in reverse, Rob mentioned that he uses the var keyword when he is knocking something out, then he goes back and refactors the var keyword to the correct type. I would agree with this. As for the single varaible, I am less convinced that readability suffers because
- Everyone does it – making this convention readability by default
- You actually don’t use the variable – it is not returned or acted on beyond the line of code.
As for function chaining, I can see why readability suffers. Breaking out the functions into logic units of work with each getting their own line seems reasonable.