In principle, the whole question in the title. It turns out that one of the main tasks of encapsulation is not at all, namely, hiding methods or fields of an object from unwanted use by hackers.

  • Is there reflection in C ++ too? - Vlad from Moscow
  • As far as I know, no, but there is another zaparka with pointers. - BORSHEVIK
  • 7
    Part of the intruders you actually came up with yourself. Encapsulation does not prevent access, but removes from the scope of those things that are not needed by the user of a particular functionality. - etki
  • one
    Listen, honestly. Well, at least a little logic. If X is used for Y, does that mean that X and Y are the same? There are people who love to ride on other people, I'm not a means of transportation now. - etki
  • 2
    @Qwertiy: This is even worse. So, they came up with those who say so. - VladD

5 answers 5

The purpose of encapsulation is to give the developer a hint on what can and what should not be used. What data is meant to be read or modified, and which is not at all. What data is a “contract” is guaranteed, and what is not. What you need to know about the object, and what not to waste gray cells.

The purpose of encapsulation is not security at all. You cannot protect yourself this way from a malicious programmer who can use a Java code decompiler, find out the binary layout of your object, and do anything with it from native code. Or execute reinterpret_cast in C ++, and analyze, or even change the bytes of your object.

There are other means to protect against malicious code. In .NET, for example, loading it into an AppDomain with reduced permissions, in which reflection, Marshal.Copy native code and functions like Marshal.Copy .

    Yes there is.

    Because encapsulation makes sense only if the object is considered as a black box: the type has a certain public contract, and all entrails (implementation details) are hidden (encapsulated). Clients use a contract without knowing how it works inside.

    By applying reflection, you no longer see the object as a black box. Because you have already looked inside and looked at what and how you need to pull and to which private field to turn. With the use of a public contract, this has little to do.

    • So I meant a specific part of the encapsulation, namely security, as far as the correct code is concerned , there are no questions here, the encapsulation works - BORSHEVIK
    • @BORSHEVIK against scrap, as you know, there is no reception. - andreycha

    I don’t know how in Java, but in C # to access private entities, code that uses reflection must be executed with full confidence (FullTrust). I did not understand how it works in detail, but there is an opportunity to remove complete trust for potentially malicious code (for example, plug-ins). Erik Lippert has a few posts related to the prevention of malicious influence from the code, however, in those that I read, it was already assumed that that code does not have FullTrust-capabilities and is trying to "harm" regular means.

      As already noted by the responders, encapsulation is very mediated by security — as a possible mechanism for data hiding and implementation.
      This is just a very useful pattern that, as it were, draws the line of authority and responsibility - that inside the black box you shouldn’t touch and you shouldn’t go into it. All you need to worry about - the interface that implements this box, use it for health.

      Well, from a purely historical and not only point of view, this is also a way to “not accidentally intersect with names. Imagine that you have no support for namespaces and the ability to combine logical structures into classes / objects / something else, i.e. where any data (read, variables) is global - programming in such an environment is very dangerous and fraught with collisions. As I understand it, encapsulation is used for this, including, as in the case of security, this is a secondary result.

        About encapsulation and reflection answered quite fully, the only thing I would like to add is that reflection is not the only thing that can break / bypass encapsulation. Suffice it to recall the transfer of the object "by reference" and "by value."

        Let's consider a simple block of code: Let there be a class A :

         public class A { private List<String> privateList; public A(List<String> privateList) { this.privateList = privateList; } public List<String> getPrivateList() { return privateList; } } 

        It would seem that everything is quite standard, but what is wrong here?

         List<String> myList = new ArrayList<>(); myList.add("Меня передадут в коструктор"); A myObj = new A(myList); myList.add("Так мы изменили состояние приватного поля экземпляра класса A"); myList.add("И даже не использовали рефлексию"); myObg.getPrivateList().add("Так тоже меняется приватное поле"); 

        On the one hand, we did not violate the principles of encapsulation (we called only public methods that were visible to us), on the other hand, the state of the private field changed.

        Thus, we conclude that in full, out of the box, in our usual form, encapsulation in Java works only for immutable objects, such as primitives ( byte, short, int ), strings, etc. For mutable objects, you must return copies of them.

         public class A { private List<String> privateList; public A(List<String> privateList) { this.privateList = new ArrayList<>(privateList); } public List<String> getPrivateList() { return new ArrayList<>(privateList); } } 

        An article on this topic on DZone: https://dzone.com/articles/encapsulation-i-dont-think-it-means-what-you-think