在具有副作用的方法中最大化代码可读性?

Chr*_*ley 3 c# readability pass-by-reference

我正在使用一种方法,该方法会对传递的参考参数造成副作用.我对代码的主要关注点之一是可读性,这种情况我觉得可能导致混淆.

举个例子:

class Program
{
    static void Main(string[] args)
    {
        var simplePOCO = new SimplePOCO();

        // Method 1: causes side effects, but potentially unclear
        Method1(simplePOCO);

        // Method 2: assignment makes intentions clearer, but unnecessary
        simplePOCO = Method2(simplePOCO);

        // Method 3: ref/out makes intentions clearer, but (very?) unnecessary
        Method3(ref simplePOCO);

        // Method 4: avoid the problem altogether
        simplePOCO.SimpleProperty = Method4();
    }

    public static void Method1(SimplePOCO simplePOCO)
    {
        simplePOCO.SimpleProperty = 1;
    }

    public static SimplePOCO Method2(SimplePOCO simplePOCO)
    {
        simplePOCO.SimpleProperty = 1;
        return simplePOCO;
    }

    public static SimplePOCO Method3(ref SimplePOCO simplePOCO)
    {
        simplePOCO.SimpleProperty = 1;
        return simplePOCO;
    }

    public static int Method4()
    {
        return 3;
    }
}

class SimplePOCO
{
    public int SimpleProperty { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我倾向于使用方法2,但我意识到它只是使用自我赋值.方法4看起来也不错,但在这种情况下需要进行一些重构才能实现 - 值得吗?我很好奇是否有人对此有任何强烈的感情.显然,方法的正确命名将有很长的路要走.是否存在解决这一问题的思想流派?还有其他我没想过的款式吗?

Bro*_*ass 7

如果这是唯一的副作用,我会把它的方法属于:inside,SimplePOCO以便将它修改的方法和数据封装在一起:

class SimplePOCO
{
    public int SimpleProperty { get; set; }
    public void Method5()
    {
       SimpleProperty = 3;
    }
}
Run Code Online (Sandbox Code Playgroud)

方法名称也应表明由于调用而预期会发生变化,即UpdateSimplePropertyRandomly().