Why should I use OOP to hide information?

Why should I use PHP to hide information?

<?php function foo($bar) { echo $bar; } foo('foobar'); ?> 

COMPARISONS

 <?php class foo { private $bar; function __construct($b){ $this->bar = $b; } function display() { echo $this->bar; } } $foobar = new foo('bar'); $foobar->display(); ?> 
+4
source share
5 answers

You will do this to encapsulate the functionality and protect the usage code from being changed. Take this example:

 class Person { protected $legs; public function setLegs($number){ $this->legs = $number; } } 

Suppose we now have code that uses this class ...

 if ($_POST['legs']) { $person = new Person; $person->setLegs($_POST['legs']); } 

Ofcours you can do it with the following class

 class Person { public $legs; } 

$ person = new face; $ person-> legs = $ _POST ['legs'];

The problem arises if you need to provide some kind of foot test or if you want to make changes later. Let's say you have to make changes to the rules about a person (for example, the maximum number of legs a person can have is ten) - if you have not encapsulated the logic that you now need to bypass the application that finds its use ...

 class Person { protected $legs; public function setLegs($number){ if ( ! is_int($number) || $number > 10){ throw new Exception('incorrect user input'); } $this->legs = $number; } } 

Encapsulation is important for the following reasons:

  • This allows you to reuse application logic.
  • This makes it easier to make changes later.
+3
source

Everything that you publish becomes your public contract. Other people begin to depend on your social practices, use them and expect them to be there and work the same way. “Other people,” maybe six months later.

So be extremely conservative about what to make public. This gives you the freedom to develop code and fix errors in it without violating the public interface.

+7
source

Information hiding (encapsulation) is good, because it reduces the possibility of customers using "undocumented" information.

The whole point of encapsulation is to minimize the interface to your code so that you can change the unpublished bits whenever you want, without affecting its clients.

For example, let's say you have a dictionary class that maps one line to another. Let me say again that you implemented this as a quick and dirty solution with two arrays, because you were behind the schedule - apparently this sometimes happens :-) And that you did not encapsulate the array and the methods that use it.

So, it was in the field for a while, and millions of customers bought it. Half of them complain about speed, since dictionaries have one hundred thousand entries.

The other half uses it, going behind your back and using your internal but hidden data structures.

What do you do? If you do nothing, half a million of your customers will not renew their contracts, and they will not work well with your product.

If you change your code to use a balanced tree or hash, the remaining half a million customers will moan about your decision.

Here is what you do. As a result, you support two versions: one for people with big data, and the other for mean people. This greatly increases your costs and efforts.

If you encapsulated your data and methods correctly, you could replace internal wholesale without affecting any of your customers.

+4
source

In your example, there seems to be no clear demonstration of how this sounds like you ask. You wonder why people will use different protection qualifiers for class members and not just make everything public?

This is the concept of encapsulation, essentially. Think of the externally visible “trace” of a class as a “contract”. A class defined and visible from the outside provides a specific set of functions. Just as this class provides functionality, internally, it has nothing to do with anything other than this class. Not only should it not be known outside the class, it clearly should not be known.

This leads to further concepts of the key to an object-oriented design called separation of problems, dependency inversion, open / closed principle, etc. If other classes / objects / etc. had direct access to all the internal elements of this particular class, you could write code to use these internal elements. Private members, private methods, etc.

This creates a dependency between this external code and the internal logic of the class, which should not reveal this internal logic. This makes it difficult to re-implement this class, replaces it with another that implements the same “contract” (albeit with different internal functionality), transparently adding additional internal functions without changing the “contract”, etc.

Edit:. You may additionally wonder why people would create a private member variable, and then expose a public getter and setter to control this variable. Why go through this extra nuisance when you can just make the variable publicly available, right?

Well, in some cases this may be good. But keep in mind that the concept of encapsulation and contract maintenance. What if you want to change the internal implementation of the class and variable? Maybe you need to change its type a little? If a variable is publicly exposed, especially in statically typed environments (not in PHP, but you get the idea), any such change will be a “violation of the changes” for the contract.

If public getter / setter methods exist instead, you can change the private variable as needed and perform any conversion or logic in the methods, while maintaining transparency.

Or maybe you want to audit changes to this variable ... Just do it in the setter method (register it, raise the event, what you need to do), and not everywhere in the code accessed by the public variable (including the code that still not written).

The habit of making private variables and wrapping them in public getters / seters (if necessary ... not every private member variable needs public access) is a good habit to maintain as a whole. It is entirely possible, even likely, that the vast majority of your class members will never go beyond this simple logic. But in relatively rare cases when this happens, getters / setters will be much easier.

Basically, this is a design that adds essentially a very small foreground code (one-time getter / setter creation, as opposed to constantly servicing access to an element variable) to allow you to make changes to the class without violating the binary compatibility of the object and violating it " the contract".

Edit: @mario made a good point in his comment, and I would like to clarify something. It is definitely not a good habit to always write getters / setters for all private members. The idea is to use getters / setters for members that logically should be public. For example, if a class defines a piece of text on a display, and members modified by getters / setters are the font, size, weight, etc. There you will logically see access methods (which are handled differently in different languages) to set these class properties.

These properties can be internally maintained by one private member each, or by a combination of either members, or in some other way, etc. This part that should not be displayed outside the class. Everything that is outside the class knows: "I'm talking about this object in order to change its font weight." Not "I'm telling this object to set its _font variable to this value."

Note also that externally, what is considered as a member using accessories may not be possible to access the private member at all, or at least not in the same way. A good example of this is read-only accessors (getters) that represent some given state of an object. IsValid for example, can execute business validation logic throughout the model and return a bool representing the state of the object. It does not return the contents of some private bool member.

+3
source

When developing a library, for example, you might want to make the insides of your class hidden to users of your API so that if you decide to change the way your class works, you don’t have to worry about breaking all the programs because they got access to members that they should not . You only see the visible interface, which, as you know, will not change, and in this way you can safely change how these functions work.

+2
source

Source: https://habr.com/ru/post/1338597/


All Articles