Illustrations of encapsulation violation (-ation, -ation, ...)

Dave Astels recently wrote about encapsulation violation.  It's a helpful reminder of some OO basics that are all too easy to forget, especially for those of us who came from a procedural programming background.

In my early career, I had the notion of encapsulation explained to me a couple of ways that really stuck:

1) If you want to borrow five dollars from me, you don't grab my pocket with my wallet, extract the wallet from it, open the wallet, start leafing through the bills until you find five dollars, extract the five dollars, put the wallet back in my pocket, and say "Thanks."  You just ask me, "Can I borrow five dollars?"  I'll do the rest -- I'll even track the IOU.  (Thanks, Darryl.)

2) If you want to know what I had for breakfast this morning, you don't cut my stomach open, scrape a sample of not-completely-digested food, gastric juices and all, and perform a spectroscopic analysis on it to determine the chemical content and probable original food form (and then, hopefully, sew me back up).  You just ask me, "What did you have for breakfast this morning?"  I promise to be honest.  (Thanks, Brett.)

Written on October 21, 2005