C# Paradigms: Side effects on Lists

前端 未结 6 1712
隐瞒了意图╮
隐瞒了意图╮ 2020-12-29 10:43

I am trying to evolve my understanding of side effects and how they should be controlled and applied.

In the following List of flights, I want to set a property of e

6条回答
  •  天涯浪人
    2020-12-29 11:23

    Your LINQ code does not "directly" violate the guidelines you mention, because you are not modifying the list itself; you are just modifying some property on the contents of the list.

    However, the main objection that drives these guidelines remains: you should not be modifying data with LINQ (also, you are abusing Select to perform your side effects).

    Not modifying any data can be justified pretty easily. Consider this snippet:

    fResults.Where(flight => flight.NonStop)  
    

    Do you see where this is modifying the flight properties? Neither will many maintenance programmers, since they will stop reading after the Where -- the code that follows is obviously free of side effects since this is a query, right?

    [Nitpick: Certainly, seeing a query whose return value is not retained is a dead giveaway that the query does have side effects or that the code should have been removed; in any case, that "something is wrong". But it's so much easier to say that when there are only 2 lines of code to look at instead of pages upon pages.]

    As a correct solution, I would recommend this:

    foreach (var x in fResults.Where(flight => flight.NonStop))
    {
        x.Description = "Fly Direct!";
    }
    

    Pretty easy to both write and read.

提交回复
热议问题