Encapsulation is one fundamental concept of 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.
That’s it, the object properties (and some of its methods) should be
private (or, sometimes,
Let’s see an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
The code above uses the keyword “class” and because of that, according to many developers, it is object-oriented code. In fact, it is pure procedural code.
Let’s put it side-by-side against the same code written in C, a procedural language that does not provide any object-oriented feature.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
Letting apart the inherent differences due to syntax, can you spot any difference of style in the two fragments above? I cannot.
It is the same code, procedural beyond a shadow of a doubt.
Addendum: There are cases when public properties are the way to go. I’ll write about them in a future post.