Saturday, November 20, 2010

Learn to Love Lambdas Session Questions

Here are a couple of questions that came up during the Learn to Love Lambdas sessions at recent Code Camps.  If you would like to review the session, you can check out the walkthrough and code samples here: Learn to Love Lambdas.

Extension Methods
Question: Could the AddSort() and AddFilter() methods be rewritten as extension methods?

Answer: This question came up during two presentations, so there are at least two people who are curious about this.  The answer in this case is no.  Let's look at the signuatures of the methods as we created them:

If we wanted to convert these to extension methods, we would need to make these methods "public" (instead of private) and "static" (instead of instance methods).  For a quick review of how to create and use extension methods, you can check here: Quick Byte: Extension Methods.  The problem is that we cannot make these methods static since they reference specific UI elements on the form.  We could do some refactoring and pass in values (for example, the check box true/false values) as parameters.  That would allow us to make these methods static; however, this may not be a good idea.

First, I like to reserve extension methods for generic methods that I am planning on re-using.  In this case, we have a very specific use case that we are implementing based on UI elements.  Second, in making these methods public and static, it exposes them to broader usage than simply as private members of the class.  Because these methods are so specific, this may just end up resulting in errors if they are used elsewhere.  So, even though it is technically possible to convert these to extension methods, I would not recommend it in this case.

Captured Variables
Question: You metioned that if the callback method grew any larger, you would be tempted to refactor it out into a separate method.  How would this affect the captured variable?

Answer: Even if we refactored the method, we would not eliminate the lambda expression itself; we would simply move the body of the lamba to another method.  In this case, we could add the captured variable as a parameter, and it would remain available to the separate method.

Here's the refactored code:

Here, you can see that we take the "selPerson" variable (the variable that is captured by the lambda expression) and pass it as a parameter to the "UpdateUI" method.  Since the "UpdateUI" method is called within the body of the lambda expression, we still has access to the captured variable which we can pass through to the method.  This maintains the same functionality that we have before and allows us to keep the "selPerson" variable as a method-level variable.

Thank you for the great questions.  Feel free to drop me a note if you have any more.

Happy Coding!

No comments:

Post a Comment