Is it a good practice to use Action delegates as Inline functions?

核能气质少年 提交于 2019-12-13 00:28:52

问题


I often have some piece of code that repeats.

Usually, I put them in a function, but sometimes I hate to do this because :

  • it requires too many parameters
  • the code is usually very specific to a little part of the whole. So I finally have two or three function that are only used in one place.

So, to simulate Inline code which is missing from C#, I use Action delegates :

public void Display(DateTime from, DateTime to)
{
    var start = from.ToOADate();
    var end = to.ToOADate();

    [...]

    // This Action delegate helps me not to repeat the code.
    var removePoints = new Action<Series>(serie =>
    {
        var pointsToRemove = serie.Points.Where(pt => pt.XValue < start || pt.XValue > end).ToArray();

        foreach (var pt in pointsToRemove)
            serie.Points.Remove(pt);
    });

    removePoints(FlameTemperatureSerie);
    removePoints(BoshGasFlowRateSerie);
    removePoints(PercCOSerie);
    removePoints(PercH2Serie);

    [...]
}

This is quite helpful, especially because the Action delegate execution context can use the local variables.

I seems good to me, but I never saw nowhere Action delegates used this way. That's why I would like to know if this practice could be recommended, or if might causes issues I dont know.


回答1:


As long as it doesn't get too confusing, there is nothing wrong with that.




回答2:


It is perfectly valid to have a function that is only called once if it makes the code easier to read and maintain.



来源:https://stackoverflow.com/questions/14647668/is-it-a-good-practice-to-use-action-delegates-as-inline-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!