David Vogel
David Vogel

Reputation: 465

Does passing a field in a parameter to an external method call violate the Open/Closed principle?

In the code below, does passing a private member, _field, from class Foo as an external method parameter (Bar.DoSomething(_field)) violate the Open/Closed principle in SOLID programming practices?

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.

As I understand it, entities should be open for extension, but closed to modification. However, in this case, _field is set once in the constructor of Foo and is readonly. Is passing a private member to an external method's prameter violate Open/Closed principle or some other best practice?

  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
    }
  }

Upvotes: 1

Views: 133

Answers (1)

Scott Hannen
Scott Hannen

Reputation: 29222

No, this does not violate the open/closed principle. From the standpoint of Bar, input isn't an internal field belonging to Foo. It's just an integer. The internal state of Foo remains hidden inside the class.

Going a step further, unless you were to specify ref when passing the parameter,

Bar.BarDoSomething(ref _field);

Bar can't even modify the value of _field. The interaction is one-way. Foo is telling Bar to do something. That's good.

To clarify - even if ref was used and Bar could modify the value that wouldn't have any bearing on the open/closed principle. But if the purpose of Bar.DoSomething was to return a value then it would be better as a function that returns an int rather than a method that modifies one. That way the caller could get the value and decide whether it wanted to update _field.

Upvotes: 3

Related Questions