Working Around Encapsulation
Encapsulation is good, but can cause problems
Issue: 12.4 (July/August 2014)
Author: Marc Zeedar
Author Bio: Marc taught himself programming in high school when he bought his first computer but had no money for software. He's had fun learning ever since.
Article Description: No description available.
Article Length (in bytes): 10,961
Starting Page Number: 49
Article Number: 12409
12409project.zip Updated: 2014-07-03 00:14:42
Related Link(s): None
Excerpt of article text...
At XDC 2014, I gave a talk on object-oriented programming (OOP). I explained that one of the key benefits is
encapsulation—the idea of separating your objects and their data so that different parts of your code don't know about other parts of your code.
This concept is fairly easy to understand: any bit of code that talks to another becomes dependent upon that other code. For example, if we have a
getTaxRatefunction that returns the current sales tax rate and we call it during our invoice calculation routine, the two sections of code are invisibly linked. Changes to
getTaxRatecould break the invoice routine. Too many such links create hidden complexity (see Figure 1) and make your code fragile.
Of course, that's a tiny example that's not likely to cause much of a problem. What's far more common—and much worse—is when routines make
assumptionsabout data in another part of the program.
Let's say you are storing some data in an array of strings. Several other parts of the program directly access that array. Now it's years later and you decide to add some new features to your program. To do this, you realize that your array is insufficient—you need to change it to a
dictionary. This isn't very difficult as the two data structures are similar (though the actual code is, of course, different). However, when you do this, you inadvertently break all those other parts of the program that are attempting to directly access the array. They all need to be rewritten to support a dictionary instead.
If you'd written your program in an object-oriented fashion, this wouldn't have happened. You would have
encapsulatedthe array data structure inside an object. That object would have had public methods that exposed the data in a specific manner. For instance, it could have had a function that returned string data based on the integer
idsent. All parts of your code that needed access to the string data wouldn't directly access the array—they'd pass an
idto the method and receive back the string. (Internal to the object would be the code that accessed the actual data structure.) When you later decided to change the array to a dictionary, you would only have to change the code inside the object: all the outer code would remain unchanged!
That's the key benefit of encapsulation: it makes your code more durable and you have to do less work when you make changes in the future.
...End of Excerpt. Please purchase the magazine to read the full article.