在下面的代码中,确实从 class Foo
传递了一个私有(private)成员 _field
作为外部方法参数 (Bar.DoSomething(_field)
) 违反了 Open/Closed principle在 SOLID 编程实践中?
In object-oriented programming, the open/closed principle states "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification"; that is, such an entity can allow its behaviour to be extended without modifying its source code.
据我了解,实体应该对扩展开放,但对修改关闭。但是,在这种情况下,_field
在 Foo
的构造函数中设置了一次,并且是 readonly
。 将私有(private)成员传递给外部方法的参数是否违反了开放/封闭原则或其他一些最佳实践?
public class Foo
{
private readonly int _field;
public Foo(int input)
{
_field = input;
}
private void FooDoSomething()
{
Bar.BarDoSomething(_field); //Breaking Open/Closed Principle?
}
}
public static class Bar
{
public static void BarDoSomething(int input)
{
//Something happens
}
}
最佳答案
不,这不违反开闭原则。从 Bar
的角度来看,input
不是属于 Foo
的内部字段。它只是一个整数。 Foo
的内部状态仍然隐藏在类中。
更进一步,除非你在传递参数时指定ref
,
Bar.BarDoSomething(ref _field);
Bar
甚至不能修改_field
的值。交互是单向的。 Foo
告诉 Bar
做某事。那挺好的。
澄清 - 即使使用了 ref
并且 Bar
可以修改对打开/关闭没有任何影响的值原则。但是,如果 Bar.DoSomething
的目的是返回一个值,那么作为一个返回 int
的函数而不是一个方法会更好修改一个。这样调用者就可以获取值并决定是否要更新 _field
。
关于c# - 将参数中的字段传递给外部方法调用是否违反了开放/封闭原则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36899693/