Wednesday, February 25, 2009

Object relationship oriented programming

Lately, functional programming seems to be getting a lot of attention (so much so that OOP no longer looks like the cool kid on the block). But, at least for me, OOP is still very much alive and is useful to organize code.

What I have noticed about my code as I read more about FP and play with languages like clojure is that I now try to make objects represent not objects, but generic concepts that encapsulate relationships between objects.

The main difference between thinking in terms of relationship containers and how I used to think about OOP is that methods that deal with more than one thing don't live within one of the objects that it applies to; it lives in a separate object where the interaction happens.

For example, instead of

I'd now call a feed function from an object where both person and dog are part of. The hard part is figuring out what this object should be. It depends on the application. Maybe I could have written it this way:

class CountrySideLife extends Lifestyle {
  public void feed(Person person, Animal pet) {}

Maybe that's overkill and I can get away with "class Main", since this is a throw-away example.

The point, though, is to not think so much in terms of object x does y, but function y happens in x.

The downside of thinking about relationships is that you don't always have a clear cut idea of what they are (especially if your business requirements change a lot), so designing the relationship classes prematurely could mean shooting yourself in the face.

The upside is that code written like this looks top-down and is easy to read and understand.

Of course, the old paradigm of object x does y still has its place. Sometimes a self-contained class just makes sense. But for higher level code paths that deal with a lot of objects and relationships, the paradigm of function y happens in x helps me organize code when I'm not sure which object should encapsulate what function.

No comments:

Post a Comment