How often do you use lambda expressions? I use them a great deal, mostly when I am making method assertions in Rhino Mocks. Their use is also on the rise with the popularity of fluent interfaces growing. If you do the bare minimum, which i see a lot, the expression can be somewhat cryptic.
Users.Find(x => x.Id == selectedUserId)
I am guilty of doing this as well, without even realizing. Maybe I am just being nit picky.
I think it is much more readable if you use something more descriptive than some arbitrary letter in the alphabet.
Users.Find(user => user.Id == selectedUserId)
This becomes much more useful when you are coding more complex lambda expressions. One example is when making a method assertion using Rhino Mocks.
x => x.Save(newUser),
o => o.IgnoreArguments()
With that assertion we have two arbitrary letters, what the heck does ‘x’ and ‘o’ represent. Are we talking about hugs and kisses. I don’t think so.
So to remedy this, lets change ‘x’ to ‘userRepository’ and ‘o’ to ‘method assertion’. I believe these terms will make the assertion much more readable and concise.
userRepository => userRepository.Save(newUser),
assertionOptions => assertionOptions.IgnoreArguments()
With that little change it is much easier to understand what is being asserted and what options are being set on that assertion.
The hardest part is breaking the habit of using arbitrary letters. In the long run a more descriptive expression improves the readability of the code. It will also decrease the amount of time it takes a new person to understand the lambda expressions in the code base.
Post Footer automatically generated by Add Post Footer Plugin for wordpress.