Coming from PHP, one of my struggles in learning OOP was figuring out what good Encapsulation did. I mean, if you make everything publicly accessible from anywhere, then you can accomplish everything you want.
That is a brute force mentality, and doesn't work if you need to maintain a large amount of code, or you need to work with other people.
There are a few reasons for this:
1. Some code never needs to be accessed outside of the class.
2. Some code never should be accessed outside of the class
3. If you're working with a lot of code and a lot of classes, you don't want to have to remember which method (or property) is the most important, from outside of the class. Some classes may have only 1 or 2 methods that need to be accessed from outside of the class, so why would you publicly expose all the other methods that you don't care about?
Consider a common example. Humans speak. Human is the noun, speak is the verb, therefore Human is the class, and speak is the method. A lot of the body systems of a human are required to do something in order for the Human to speak. The person or object a Human is speaking to does not care about the synapses that need to fire in the brain for the Human to speak, nor does the other object care about what the lungs need to do, what the vocal chords need to do, or what the mouth needs to do. Therefore, it would make sense to publicly expose Human's Speak() method, and make those other things private. That is encapsulation in a nutshell.
The concept of encapsulation is particularly important in a development environment like .NET's, because .NET's development environment provides a lot of functionality to make life easier, such as dropdown boxes that appear (I believe this feature is called "Completion List"), to make it easier and faster for you to select the methods or properties available from the class. If you get the dropdown list of all the availble members of an object, you don't want to have to scroll through 20 pages of irrelevant methods in order to find the right method.
I think overall, the main value of encapsulation comes with its ability to help you organize your apps, and to provide an extra layer of safety, in that if you only allow a very small subset of your code to accomplish certain functionality, then you reduce the risk (and the detective work afterwards) of non-authorized code to perform tasks it shouldn't be performing.
My struggles in understanding and learning about Object Oriented design, and the tools and knowledge I've taken from them.
- ▼ October (9)
Powered by Blogger.