Monday, February 20, 2012

Meaning Over Implementation


Conveying the meaning of code is more important than conveying the implementation of code.

This is a lesson I've learned that I thought was worth sharing.  It may sound pretty straight forward, but I've noticed it can be a hurdle when you're coming from a spaghetti code background.  Spaghetti code requires you to hunt down code to understand how the system works because the code is not 'meaningful.'

There are really two major components to this.  The first is, if you're used to spaghetti code, you've been trained to mistrust the code you're reading.  That makes it hard to come to terms with hiding implementation details behind well named methods, because you don't trust those methods to do what you need unless you know every detail of HOW they do it.

The second is in naming.  Generally I try to name methods so that they describe both what the method does as well as how it does it.  But this isn't always possible.  And when it's not possible, I've learned to always favor naming what the method is for as opposed to how the method is implemented.

There are a number of reason why this works out.  The first is that issue of trust.  If your code base sucks, you're forced to approach every class and every method with a certain amount of mistrust.  You expect it to do one thing, but you've been bitten enough times to know it's likely it does some other thing.  If this is the kind of code base you find yourself in, you're screwed.  Every programming technique we have at our disposal relies on abstraction.  And abstraction is all about hiding complexity.  But if you don't trust the abstractions, you can't build on them.

The other reason this works is the same reason SRP (the Single Responsibility Principle) works.  You can selectively pull back the curtain on each abstraction as needed.  This allows you to understand things from a high level, but then drill down one layer at a time into the details.  I like to think of this as breadth-first programming, as opposed to depth-first programming.

So when you're struggling with naming things, remember your first priority should be to name things so that others will understand WHAT it does.  They can read the implementation if they need to understand HOW it does it.

No comments:

Post a Comment

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