Home>

I am learning about object orientation.

Encapsulation and data hiding are keywords for object-oriented programming.

However, for me who has only written an introductory small program, I cannot imagine the importance of this data hiding. I don't really understand why a situation occurs when someone tries to rewrite a member variable of a class. . .

Tell me about the benefits of data hiding with specific examples.

  • Answer # 1

      

    Why is a situation where someone tries to rewrite a member variable of a class?

    Since other people, including myself in the future, do not share the implicit assumptions when writing the code, it is possible for the author to use it unexpectedly.

    Is

    … not enough?

  • Answer # 2

    Hello.

      

    Tell me about the benefits of data hiding with specific examples.

    For example, make sure that the first name and last name are separated by a space.
    And since name strings are used very frequently, they are stored as data internally.
    Use a method like setName (last name, first name) to set the internal "name" variable, separated by single-byte spaces.

    In this case, from an object-oriented perspective, the "name" variable should be private and returned by a method such as getName (). Then, the following scenario will not occur.

    If you define a "name" variable in public. A few years later, or some other early programmer, might have set the name string directly to the "name" variable because he had a name string at hand.
    The name only needs to be separated by a single-byte space, but I think that it may be separated by a full-width space.

    It will malfunction because the process that accesses the "name" frequently is not supposed. It may be unexpectedly inconspicuous, and it may become a problem that the person does not get caught in the search. If it is a program that adds salary allowances, there may be people who secretly reduce their allowances. I really hate it if it was me. I hate maskey too.

    It is impossible to completely eliminate such problems, but the concealment of data can reduce the probability of occurrence and reduce the number of unhappy people. Data hiding is one of the most effective means.

  • Answer # 3

    Typically, it is a situation where someone tries to rewrite a member variable of a class. For example, if you consider the following structure in C language, you can imagine accessing from the outside.

    struct Point2D
    {
    int x, y;
    }

    However, data concealment is even more desirable if it is not possible to easily assume that "the situation where another person tries to rewrite a member variable of a class". The purpose is to create a simple and secure exterior by not exposing data unnecessary to others.