Saturday, 25 May 2013

Going Functional

As more functional features get added to C# I'm writing code rather differently.

Splitting Data & functions

Instead of having classes that combine data and functions, I'm increasing splitting the two. The functions take data as parameters rather than modifying members on the class. This is a move towards more pure functions.

So instead of this:
    class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public void Add()
        {}
    }

I'm more likely to write this:
    class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    class CustomerService
    {
        public Customer Add(Customer customer)
        {}
    }

Passing functions to functions

I'm also increasingly using functions as more first class objects to be passed around.

So instead of this (contrived example):
    class CustomerService
    {
        public Customer Add(Customer customer)
        {
            // add customer
            CustomerModificationNotifier.Notify("customer added");
        }
    }

    static class CustomerModificationNotifier
    {
        public static void Notify(string message)
        {}
    }

I might write this:
    class CustomerService
    {
        public Customer Add(Customer customer, Action<string> notifier)
        {
            // add customer
            notifier("customer added");
        }
    }

    static class CustomerModificationNotifier
    {
        public static void Notify(string message)
        {}
    }

Everything Old is New Again

This feels all very new and shiny. Except that it really doesn't feel that new.

Say for example this:

    struct customer
    {
int id;
char name[50];
    };

    void add_customer(customer*);

    void add_customer(customer* cust)
    {
        /* add customer */
    }

Or this:

    struct customer
    {
int id;
char name[50];
    };

    void add_customer(customer*);

    void add_customer(customer* cust, void (*notifier)(int))
    {
notifier(1);
    }

    void notify(int);

    void notify(int number)
    {
        /* add customer */    }

It's funny how everything that is new really isn't that new after all.

Sometimes it really feels like all we've achieved in the last 40 years is better string management and bounds checking of arrays.

No comments:

Post a Comment