Misuse of Delegates???
In the evolution of the ideas presented in Java, C# has provided the idea of method delegation and delegates, which I'm sure you are well aware of. In C# 3.0 with the introduction of the LINQ, Lambdas were born. With Lambdas, we are able to provide an easy and elegant way to declare delegates. With great power, however, comes great responsibility. Is there a way to overuse Lambdas and Delegates? Here is a sample of code I've written:
/// <summary>
/// If GZIP or DEFLATE compression is accepted
/// by the user's browser, we will go ahead
/// and compress the file upon the controller action
/// </summary>
/// <param name="controller">Controller to invoke Compression</param>
public static void Compress(this Controller controller)
{
string gzip = "gzip";
string deflate = "deflate";
//DELEGATES
Func<string, bool> isAccepted = (encoding) => controller.Request.Headers["Accept-encoding"] != null && controller.Request.Headers["Accept-encoding"].Contains(encoding);
Action<string> setEncoding = (encoding) => controller.Response.AppendHeader("Content-encoding", encoding);
if (isAccepted.Invoke(gzip))
{
controller.Response.Filter = new GZipStream(controller.Response.Filter, CompressionMode.Compress);
setEncoding.Invoke(gzip);
}
else if (isAccepted.Invoke(deflate))
{
controller.Response.Filter = new DeflateStream(controller.Response.Filter, CompressionMode.Compress);
setEncoding.Invoke(deflate);
}
}
As you can see from the code, I use the .NET built-in delegates of Action and Func to do the setting of the encoding and the determination of the encoding, respectively.
So here is my question: Is this a misuse of delegates? Should I be putting the code into a separate private method? What are your thoughts?