Encapsulation is the first pillar of Object Oriented Programming and maybe the most important. This is how wikipedia.org defines encapsulation:
Encapsulation is one of the fundamentals of OOP (object-oriented programming). It refers to the bundling of data with the methods that operate on that data. Encapsulation is used to hide the values or state of a structured data object inside a class, preventing unauthorized parties' direct access to them. Publicly accessible methods are generally provided in the class (so-called getters and setters) to access the values, and other client classes call these methods to retrieve and modify the values within the object.
Since I have become a full-time contractor, I rarely see even senior developers get encapsulation right. I would easily say that over 90% of the code I analyze does not follow proper encapsulation rules. If encapsulation isn’t done right then the code isn’t following proper OOP. In most of my conference sessions, I state that if proper OOP isn’t done right then the code will become a house of cards, and all house of cards will fall.
My Mantra
For many years speaking at conferences I have shared my mantra about encapsulation which is bad data in, bad data out! If you let invalid data into your type, then it can cause issues. It’s even worse when this data gets into the database because then it’s very difficult to fix.
Validation
The first rule of encapsulation is, validate all data coming into your type. First, never expose fields, EVER! Fields cannot be validated when being set, so they break encapsulation. All data must be set or retrieved via properties or methods. This way, the data can be validated, events are raised etc. Here is an example of my open source code,
- public void Add(T item) {
- if (item == null) {
- throw new ArgumentNullException(nameof(item), "Value cannot be null.");
- }
- var hashCode = item.GetHashCode();
- lock(this._lock) {
- if (this._hashCodes.Contains(hashCode) == false) {
- base.Add(item);
- this._hashCodes.Add(hashCode);
- }
- }
- }

Muhafil SaiyedPosted Jun 20, 2018, 11:48 PM
Thanks for sharing
imran osmanzaiPosted May 30, 2018, 1:08 AM
Thank you Sir>