故意依赖Linq副作用是否不好? [英] Is it bad practice to purposely rely on Linq Side Effects?

查看:79
本文介绍了故意依赖Linq副作用是否不好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经常出现这样的编程模式:

A programming pattern like this comes up every so often:

int staleCount = 0;

fileUpdatesGridView.DataSource = MultiMerger.TargetIds
    .Select(id =>
    {
        FileDatabaseMerger merger = MultiMerger.GetMerger(id);

        if (merger.TargetIsStale)
            staleCount++;

        return new
        {
            Id = id,
            IsStale = merger.TargetIsStale,
            // ...
        };
    })
    .ToList();

fileUpdatesGridView.DataBind();
fileUpdatesMergeButton.Enabled = staleCount > 0;

我不确定是否有更简洁的编码方式?

I'm not sure there is a more succinct way to code this?

即使是这样,这样做也是不好的做法吗?

Even if so, is it bad practice to do this?

推荐答案

不,这不是严格的坏习惯"(例如使用用户输入的字符串连接或使用goto构造SQL查询).

No, it is not strictly "bad practice" (like constructing SQL queries with string concatenation of user input or using goto).

有时,这样的代码比几个查询/foreach或无副作用的Aggregate调用更具可读性.最好至少尝试编写foreach和无副作用版本,以查看哪个版本更易读/更容易证明正确性.

Sometimes such code is more readable than several queries/foreach or no-side-effect Aggregate call. Also it is good idea to at least try to write foreach and no-side-effect versions to see which one is more readable/easier to prove correctness.

请注意:

  • 通常很难推断此类代码将在何时发生. IE.您可以通过.ToList()调用懒惰地执行LINQ查询这一事实来对黑客进行采样,否则将无法计算该值.
  • 纯函数可以并行运行,一旦出现副作用就需要多加小心
  • 如果您需要将LINQ-to-Object转换为LINQ-to-SQL,则必须重写此类查询
  • 通常LINQ查询倾向于无副作用的函数式编程样式(因此,按照惯例,读者不会期望代码中有副作用).
  • it is frequently very hard to reason what/when will happen with such code. I.e. you sample hacks around the fact of LINQ queries executed lazily with .ToList() call, otherwise that value will not be computed.
  • pure functions can be run in parallel, once with side effects need a lot of care to do so
  • if you ever need to convert LINQ-to-Object to LINQ-to-SQL you have to rewrite such queries
  • generally LINQ queries favor functional programming style without side-effects (and hence by convention readers would not expect side-effects in the code).

这篇关于故意依赖Linq副作用是否不好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆