Dwight's blog
we all overuse objects in our programs

Well I do anyway.  Was thinking about this when coding recently.  There is an opportunity to code in a more functional style, even when not using purely functional languages, to make code easier to read and reason about.  

There is a natural tendency (at least for me) to objectize everything, in part just because many languages make it so easy and it’s such a natural form of encapsulation and packaging.  However it could be bad.  Consider:

class Cruncher {
public:
    void crunch(string context, int a, int b) { 
        _context = context;
        // do some things...
        f();
        // do some things
        g();
        // do some things
    }
private:
    void f();
    void g();
};
Cruncher c;
c.crunch(...);

Seems pretty natural, our private methods are hidden from the outside interface. Yet what about _context — do f() or g() change it? As the code scales up to hundreds or thousands of lines, it’s not so obvious. Better to pass them around if not changing I think. In fact maybe we don’t need an object at all. It would be nice though to hide private things. Perhaps

class Crunch2 {
public:
    static void crunch(string context, int a, int b) { 
        // do some things...
        f(context);
        // do some things
        g(context);
        // do some things
    }
private:
    static void f(string);
    static void g(string);
};

Or we could make a namespace, or use static functions…

In real work we often need an object anyway — the point here is just that perhaps half of the member variables one adds to a class can perhaps be parameters on invocations instead.

  1. dmerr posted this
blog comments powered by Disqus