Another Reason for Encapsulation

Everyone knows the common reasons for Encapsulation…

  • It hides the implementation.
  • It hides the data from prying eyes who might want to manipulate it.
  • It encourages reuse and can reduce the duplication of similar functionality.
  • It can encourage documentation since you only have to write the explanation once.

But last week, I found another reason perfect for Encapsulation:

Encapsulation is a defense against incompetence.

That's right!  By wrapping a particular piece of functionality together in a little package, someone that doesn't have a freakin' clue can actually protect themselves.  The separation of interface and implementation is the key here.

The clueless person – alright, I'll be more polite… the newbie – can be helped by someone with a little more skill.  That second person can come along and clean up the implementation without changing anything else.  In some cases, this could be a small optimization or completely gutting everything and rebuilding it from the ground up.

The instance where I saw it, the friend passed along a 40+ line function to handle date formatting.  It converted a date from a 12 hour am/pm time to a 24 hour clock, parsed out the minutes and seconds to know whether they should be displayed as plural, and a few other things that I don't want to think about.  It was a complete mess filled with nested if's, a loop, usage of a three of globals, and a even a lost book of the Bible*.

The clueful friend managed to replace all of that mess and chaos with two lines of code… using the language's underlying date/string functionality.

*  Ok, I'm exagerating a bit… he only used two globals.