axiac@web

Public Properties Are Not OOP

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, protected) and not public.

Let’s see an example:

1
2
3
4
5
6
7
8
9
10
class User {
public $name;
public $age;
}

$user = new User();
$user->name = "John Doe";
$user->age = 45;

printf("Name: %s, age: %d\n", $user->name, $user->age);

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
/* "Object-oriented" PHP code */          |      /* Procedural C code */
|
| #include <stdlib.h>
| #include <stdio.h>
|
class User { | typedef struct {
public $name; | char *name;
public $age; | int age;
} | } User;
|
| int main()
| {
$user = new User(); | User *user = malloc(sizeof(User));
$user->name = "John Doe"; | user->name = "John Doe";
$user->age = 45; | user->age = 45;
|
printf("Name: %s, age: %d\n", | printf("Name: %s, age: %d\n",
$user->name, $user->age); | user->name, user->age);
|
| return 0;
| }

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.
Case closed.


Addendum: There are cases when public properties are the way to go. I’ll write about them in a future post.

Comments