C# – Functional vs object-oriented style in C#

cfunctional programmingobject-oriented

I'm learning functional programming and face the following confusion when applying it to my C# projects:

  • I begin by writing pure, static functions and use function composition.
  • After the code reaches a certain size, I realize some of these functions tend to "cluster" about some types. For example, there exist >5 functions having the same type as parameter.

  • Next step, my object-oriented background takes over and I move these functions to this type (class) as methods. As a result, their signatures simplify and they often become more cohesive. However, I lose the benefits of functional style.

I've grown very fond of functional approach, but I cannot convince myself that my initial code was better above.
Which approach would you prefer in this situation (in C# or another mixed language)?

Related: Design in "mixed" languages: object oriented design or functional programming?

class MyType { }

class Functions
{
    public static void X(MyType t) { }
    public static void Y(MyType t) { }
    public static void Z(MyType t) { }
    public static void T(MyType t) { }
    public static void U(MyType t) { }
}

class Class1
{
    public MyType T { get; private set; }
    public Class1(MyType t) { T = t; }
    public void X() { }
    public void Y() { }
    public void Z() { }
    public void T() { }
    public void U() { }
}

Best Answer

However, I lose the benefits of functional style.

If you always lose the benefits of functional style code when converting bundles of functions to objects, you're doing it wrong (or have an usual idea of what the benefits of functional style are).

After all, instance functions are the same thing as static functions but simply have an additional implicit parameter. If you're making these functions impure, that's your problem, not a problem inherent to OO code. If you make your classes mutable, then yes, you're going to lose functional style benefits.

But if you keep your classes immutable (except for collections/DTOs), I find that you can maintain many of the benefits of functional style coding while getting some OO goodness as well.

Related Topic