This post originated from an RSS feed registered with Agile Buzz
by Keith Ray.
Original Post: Encapsulation Wasn't Meant To Mean Data Hiding
Feed Title: MemoRanda
Feed URL: http://homepage.mac.com/1/homepage404ErrorPage.html
Feed Description: Keith Ray's notes to be remembered on agile software development, project management, oo programming, and other topics.
Martin Fowler: "the point of encapsulation isn't really about hiding the data, but in hiding design decisions, particularly in areas where those decisions may have to change. ... When you are thinking about encapsulation I think it's better to ask yourself "what peice of variability are you hiding and why" rather than "am I exposing data. (Craig Larman wrote a nice column for me on this.)" Larman quotes Parnas: We propose instead that one begins with a list of difficult design decisions or design decisions which are likely to change. Each module is then design to hide such a decision from the others.
In Cocoa programming, we often have to declare a bunch of getter methods in certain objects using "key-value-coding/observing/binding" conventions so that user-interface views can synchronize their data with controllers and model objects. It's explained rather well here.
Outside of special purpose getters required by a framework, it is appropriate to look for opportunities to move methods closer to the data they work with. If a method in one class is calling several getters of another class, perhaps that method belongs to that other class. Fowler writes: "...a simple rule of thumb ... that I first heard from Kent Beck, ... always beware of cases where some code invokes more than one method on the same object. This occurs with accessors and more reasonable commands. If you ask an object for two bits of data, can you replace this with a single request for the bit of data you're calculating? If you tell an object to do two things, can you replace them with a single command? Of course there are plenty of cases where you can't, but it's always worth asking yourself the question."
Allan Shallowaywrote (starting with a quote from Design Patterns: "Consider what should be variable in your design. Focus on encapsulating the concept that varies. This mandate was a bit confusing to me at first. To me, encapsulation meant "data-hiding". But to the Gang of Four, it means something else: Encapsulating the concept that varies is encapsulation of type."