c# - 将参数中的字段传递给外部方法调用是否违反了开放/封闭原则?

标签 c# oop private-members open-closed-principle

在下面的代码中,确实从 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.

据我了解,实体应该对扩展开放,但对修改关闭。但是,在这种情况下,_fieldFoo 的构造函数中设置了一次,并且是 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/

相关文章:

c# - 声明匿名类型的列表

c++ - 如何在 C++ 中处理对象的混合集合

polymer - 在 Polymer 中声明自定义元素的私有(private)属性(property)的最佳实践是什么

c++ - 如何设置获取类的私有(private)成员 : looking for a better approach

c# - 可以在闭包中 Lock() 吗?这在 Lambda 和代码输出中是什么样子的?

c# - 星际争霸 2 之类的游戏是否使用 Windows 窗体来构建其 UI?

c# - 如何在 Entity Framework 中的导航属性上放置过滤器或条件

c# - 当前上下文中不存在名称 'ConfigurationManager'

java - 使用迭代器

javascript - Jquery 事件和对象?