Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Two Tales: Object Oriented Programming & Functional Programming

DZone's Guide to

Two Tales: Object Oriented Programming & Functional Programming

· DevOps Zone
Free Resource

The DevOps Zone is brought to you in partnership with Sonatype Nexus. The Nexus Suite helps scale your DevOps delivery with continuous component intelligence integrated into development tools, including Eclipse, IntelliJ, Jenkins, Bamboo, SonarQube and more. Schedule a demo today

Introduction

I was terrible at keeping an ongoing blog and (as a natural part of being a developer) I've produced lots of crap. Recently, while crawling in old scrap repositories, I've found something that ironically still makes sense! And that was a different point of view about the relation between OOP (Object Oriented Programming) and FP (Functional Programming). Some assumptions are made here about the reader, She/he:

  • Knows and understands OOP
  • Understands FP (familiar a bit, a hobbyist maybe)
  • Knows and understands phrase "Closure"

Background

As this multi-core thing emerges, the more (real) need shows up to find new ways to instruct machines to use those cores; and it's pretty much a whole new way of thinking in compare to that nice peaceful flow of good old computations that took place line by line in harmony. This caused a flashback to nearly 20 to 30 years ago (and in some cases even before that), when some alien-cult started strange things that were about strange ways of handling state and composing computations; a forgotten codex. Some names comes up frequently these days like Erlang which has no modifiable state and some names that does not comes up that much, like Smalltalk (A whole virtual machine as a state) but are in effect as influential protocols.

Why this flashback now? Because that old fashioned designs (like it or not) were (mostly) work of mathematician scientists, those whom strive for (mathematical) perfection. Not by "Enterprise" solution-provider companies that what they do is essentially producing new problems for people and organizations and then charge them for solving that problems. That's why work of those minds, which once started this world (of computers) comes up again to shine; beginning of a new era (actually we are just out of dark spaghetti forest and can barely see the road).

There OOP and back again FP

Let's start speaking in a more natural way (to us!). For this part, we call a combination of state (mutable or not) and functionalities that applies to them a Computation. C# is used as the pseudo language for describing things which is pretty much nearly enough like any other programming language in C family. For avoiding complexities causes by handling reference-types and value-types, we wrap all of our states in a reference type called Ref<T>; defined as:

public class Ref<T>
{
    public Ref() { }
    public Ref(T t) { Value = t; }

    public T Value { get; set; }
}

Our Computation is about just adding values to an initial value (0) and keeping number of operations:

class Computation
{
    Ref<int> _counter = new Ref<int>(0);
    Ref<int> _accumulated = new Ref<int>(0);

    void Increase(int count)
    {
        _counter.Value += count;
    }

    public int Add(int i)
    {
        _accumulated.Value += i;
        Increase(1);

        return _accumulated.Value;
    }

    public int AccumulatedValue()
    {
        return _accumulated.Value;
    }

    public int NumberOfOperations()
    {
        return _counter.Value;
    }
}
What do we have here? A State, which resides in _counter and  _accumulated and bunch of computations that are applicable to that state. Pretty OOPish, right? Now one can call those methods to mutate the state or read it (Ofcourse OOP in it's original definition was about sending messages between objects, not calling methods; which plays the same role now. But that's another story).

For example this computation can be used like:
var computation = new Computation();

computation.Add(10);
computation.Add(3);

var numberOfComputationsSoFar = computation.NumberOfOperations();
var accumulatedValueSoFar = computation.AccumulatedValue();
All of us write some pieces of code like this on a daily basis. Initialize some state, do some work and put the result into work.

Now we are going to make the twist by going FPish. Look at this closely:

var _counter = new Ref<int>(0);
var _accumulated = new Ref<int>(0);

Action<int> increase = (int count) => { _counter.Value += count; };
Func<int, int> add = (int i) =>
{
    _accumulated.Value += i;
    increase(1);

    return _accumulated.Value;
};
Func<int> accumulatedValue = () => _accumulated.Value;
Func<int> numberOfOperations = () => _counter.Value;

What do you see? Bunch of functions, right? We are doing Functional Programming here after all (if you are a veteran FP, please pretend you are comfortable with this point of view about FP for the time being). And they share the same Closure.

So to put it in perspective an object can be seen as bunch of functions sharing same closure. Or FP is OOP inside-out. There is a pattern of duality here. And we actually use this on a daily basis like Extension Methods in C#. They share a (public) closure, which is the object that they extend. Some of this Extension Methods alter the object state and some of them are transformers that produce a new object with a new state based on the previously given state by the original object (like LINQ).

Further Thoughts

Some friends may have been read this patiently; watching me ignoring immutability as a core part of FP. Well, I simply do not agree with this point of view. Immutability was not part of many big daddies of FP like Lisp and O'Caml in the first place. I agree that immutability has many (even countless) benefits. But I can ("can" here implies the boundaries of a human mind and it's content that I have access to it) not see any practical or rather pragmatic way of merging that into our current environment. The most practical way I like most is the Erlang way (not Erlang itself; just try to use it's FFI, let the syntax alone - which has many lovers - I hope Elixir brings some [DllImport] macros into BEAM); message passing (back to original definitions of OOP). Another approach would be having some local mutable context. Or something like this:

class Computation
{
    readonly object _lock = new object();

    lock(_lock)
    {
        Ref<int> _counter = new Ref<int>(0);
        Ref<int> _accumulated = new Ref<int>(0);
    }

    //...
}

In C# would help cheerfully with many situations.

If you ever wonder where these concepts come together and shape up something, you should meditate on these three words: "function", "this", "JavaScript".

But I would like very much hear from everybody their stories!

The DevOps Zone is brought to you in partnership with Sonatype Nexus. Use the Nexus Suite to automate your software supply chain and ensure you're using the highest quality open source components at every step of the development lifecycle. Get Nexus today

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}