C# – How to use the “Non-Member Functions Improve Encapsulation” pattern from C#

cencapsulationextension-methodstatic methods

In 2000, Scott Meyers argued that non-member functions improve encapsulation. In C++, a non-member function is a C-style global function:

http://www.drdobbs.com/cpp/how-non-member-functions-improve-encapsu/184401197

If you subscribe to his theory, how would you implement this in C#?

If you don't subscribe to his theory, and wish to debate the topic, please do it outside of this post (I suggest her: Feel free the comment here with regard to the actual pattern: — https://plus.google.com/105106301233937725736/posts/QvhKbB3y7F2 .)

This question is about how to best implement that pattern in C#. Acceptable answer describes a set of rules to use this pattern from C#

Best Answer

Use the following rules:

  1. For any non-static method of a class which a) does not access private fields directly and b) only calls public methods, move the method to a static helper class and turn it into an extension method.

  2. Any public static method can also be moved to a helper class.

By convention, a helper is a new static class with the same name as the original class but with the word Helper appended to it.

Example:

ORIGINAL CODE:

public class Foo
{
    int _intField;

    public void Method1()
    {
        doing something with _intField;
    }

    public void Method2()
    {
        Method1();
    }

    public static void Method3()
    {
        ....
    }

    private void Method4()
    {
        ....
    }

    public void Method5()
    {
        Method4();
    }
}

PROPOSED TRANSOFORMATION:

public class Foo
{
    int _intField;

    public void Method1()
    {
        doing something with _intField;
    }

    private void Method4()
    {
        ....
    }

    public void Method5()
    {
        Method4();
    }
}

public static class FooHelper
{
    public static void Method2(this Foo foo)
    {
        foo.Method1();
    }

    public static void Method3()
    {
        ....
    }
}
  • Method 1 cannot move because it's using a private field
  • Method 2 can move because it's not using a private field and it's calling a public method. It can be turned into an extension method.
  • Method 3 can be moved because it's a static public method
  • Method 4 cannot move because it's a private method
  • Method 5 cannot move because it's calling a private method.