I’m writing a method and depending on a config field I need to change where I get my data from. What this results in me having to write code that looks like this:
List<string> result = new List<string>();
if (configField)
{
result.Add(fieldA);
}
else
{
result.Add(...BusinessLogic...);
}
I’ll have to write that if statement many many times so of course I want to turn it into a method instead so I can just write result.Add(newMethod(configField, fieldA, dataForBusinessLogicToParse))
. This method would be useless to anyone not writing the specific method I’m writing so does it make sense to declare this method as a separate private
method or can I just declare it inline as a delegate
like this:
Func<Enum, int, int> newMethod =
(configField, fieldA, dataForBusinessLogicToParse) => ...businessLogic...
I’m worried declaring it inline might make the code more difficult to understand but I think it makes the class cleaner.
5
As far as I know, declaring a helper method as a lambda like this is not commonly done in C#, so I would advise against doing this unless you have a good reason.
Good reasons include:
- The lambda could do something a separate method can’t, like closing over a local variable or using anonymous type.
- Others in your team agree with you that this is a good practice.
That being said, starting with C# 7.0, C# supports local functions, which are similar to such helper lambdas, but generally better: they have more succinct syntax and are more efficient. So if you used a local function for this purpose, I think that would be perfectly fine.
2
If newMethod
never changes its value after initialization (it could be declared const
or readonly
, I guess), you should better write a standard private method. Using delegates without a reason can make the code confusing (at least in C#), even for experienced programmers. Comparing
private Action<Enum, int, int> newMethod = (configField, fieldA, dataForBusinessLogicToParse) ...
vs.
private void NewMethod(Enum configField, int fieldA, int dataForBusinessLogicToParse)
{
}
the latter is much more readable for me, because I see immediately which parameter has which type, whilst for the first construct I have to count parameters (especially when the number of parameters becomes more than 3).
1
Since C# 7, it supports inner functions. These combine the locality and closure benefits of lambdas with the nicer (for non-one-liners) syntax of functions. You have the option to use those.