Monday, February 13, 2012

Objects or Data Structures?

Here's a great (and old) article from Bob Martin called Active Record vs Objects.  You should read it.  I think it might be one of the best treatments of the theoretical underpinnings of Object Oriented design I've read, especially because it pays a lot of heed to what OOP is good at, and what it's not good at.

Here's some of my highlights:
  • Objects hide data and export behavior (very tell-don't-ask)
  • Data structures expose data and have no behavior
  • Algorithms that use objects are immune to the addition of new types
  • Algorithms that use data structures are immune to the addition of new functions
  • Apps should be structured around objects that expose behaviors and hide the database
This all feels right and stuff, but it's all pretty theoretical and doesn't help me decide if my code is designed as well as it could be.  And that's what I'm going to be writing about.  In one post a day for the rest of the week I'll look at various elements of "good design," and try to fit the pieces together in some way I can apply to my code.
Good designers uses this opposition to construct systems that are appropriately immune to the various forces that impinge upon them.
He's talking about the opposition between objects and data structures in terms of what they're good for.  So apparently a good designer is a psychic who can see the future.

But that is the hard part, how do you know where you'll need to add "types" vs. where you'll need to add "functions"?  Sometimes it's really obvious.  But what I'm starting to think about is, maybe I need to get more clever about the way I think about types.  Because if Uncle Bob thinks apps should be structured around objects, that means he thinks there are lots of examples where you're going to need to add a new type.  Whereas, when I think about my code, I'm not really finding very many examples where I could leverage polymorphism to any useful effect.

This could simply be because the problems I'm solving for my application are simply better suited for data structures and functions.  Or it could be because I'm just not approaching it from a clever enough OO angle.

Recently, my co-workers and I had pretty well settled on a design approach for our application, and it has been working extremely well for us.  However, this article and it's clear preference for objects and polymorphism has me wondering if there may be another perspective that could be useful.  I'll talk more about this in the next post.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.