What are the advantages of using private methods in a class other than hidden calculations?

  • one
    Well, at least assign at least, and then the following and reputation is not enough - Yuri
  • 2
    I will offer the shortest explanation of private (and not only) methods - "Protection against a fool" - KoVadim
  • 2
    @KoVadim: If the project is big enough, the class developer himself may suddenly be a fool. - VladD
  • four
    right, you also need to defend yourself. Better to let the compiler curse than later users / customers - KoVadim
  • I will try shortly: private means - the one that is available only inside this class for this particular class. For others, not available (not inherited, not directly transmitted). - nick_n_a

11 answers 11

When writing a sufficiently large piece of code (whether it is a class, a function, or something else), an important technique is decomposition . You divide the functionality into logical parts, and in the main function you add up from them, like from bricks, a common logic.

At the same time, the bricks themselves may not be adapted for access from outside. For example, an open method can check input parameters, and auxiliary brick methods are no longer necessary, since they are called only from the inside. If these methods were open, they would need to implement parameter checking, and when implementing them it would be impossible to expect that they would be called at the moment you control.

In addition, internal methods have the right to spoil the state of the class, if you know that the code calling them will fix this problem later. If you make these methods open, users of this class will be able to spoil the internal state of the class without repair.

Then, internal methods may have nothing to do with what the class should provide, with its external interface . For example, if a class represents a car, then an open method in it that converts inches to centimeters would look ridiculous. But inside such a translation may well be needed.

Well, in the end, the public method is a promise for users. Every change (deletion, change of signature, and sometimes addition) of an open method - breaking change for clients, they should review the code that your class uses. Thus, you should not just like that, without the special need to change the public methods of the class. But changes in closed methods usually occur when refactoring in a mass order: methods are simplified, combined, decomposed into several, transferred up and down the hierarchy, their semantics change, and all this does not affect the users of your class.

  • five
    The rabbit well will be very fat :) - user207618
  • @Other: I hope someone will write better :-P - VladD
  • 2
    @vp_arth: This is a quote. From me :-) - VladD
  • one
    I did not see your answers to ruSO better. Is that Nicholas, but he rather articles. - user207618
  • one
    @Other: ( flushed, closes his cheeks ) - VladD

To add something, a private method can ALWAYS be changed safely, because you know exactly what is called only from its own class, no external classes can call the private method (they don’t even see it).

Thus, having a private method is always good, because you know that there are no problems with changing it, even you can safely add additional parameters to the method.

As for public methods, anyone can call this method, so if you add / remove a parameter, you will also need to change ALL the calls to this method.

Here are some advantages of creating private variables or methods in Java:

  1. private methods are well encapsulated in the class, and the developer knows that they are not used anywhere else in the code, which gives them the confidence to change, change, or improve the private method without any side effect.

  2. If you look at the private method, you probably know that no one uses it, which helps a lot when debugging a java program.

  3. IDEs, such as Netbeans, IDEA and Eclipse, use this information and automatically check whether private methods are used within a class or not, and can display a warning to improve code quality or remove unused statements, variables or methods.

  4. Private methods use static binding in Java, and they are linked at compile time, which is quickly compared to the dynamic binding that occurs at run time, and also gives the JVM a chance to either embed the method or optimize it.

  5. Assigning variables to private in java and giving them getter and setter makes your class compatible with the naming of Java beans and other reflection-based structures such as displaytag.

Good (in my opinion) article on this topic.

  • 4th point is interesting :) But 2nd did not understand at all. How does the privacy of the method affect debugging? - Qwertiy
  • On point 3. I don’t know how other IDEs are, and IDEA notes any methods that are not used in the project, and not just private ones or inside the class. - pavlofff

Having made a method closed, it is not necessary to save it when you go to
another implementation. This method is more difficult to implement, and it may be
generally unnecessary if the presentation of the data changes, which is generally not essential. Another thing is more important: as long as the method is private, the developers of the class can be sure that it will never be used in operations outside the class, and therefore they can simply delete it. If the method is open (public), it cannot simply be omitted,
because other code may depend on it.

Source - Horstmann K., Cornell G.-Java 2. Basics. Volume 1-Williams (2014) (p. 158)

In general - everything is unreal simple. Much easier than many here have written :)

The appearance of the private modifier is due to one of the main principles of OOP - encapsulation. The main idea of ​​encapsulation is to make private a maximum of methods / properties that can be passed privately. As a consequence, we have:

  1. A simpler code structure: the separation of internally important implementations (privates) and controls (publics).
  2. More convenient hints (when you put an end and you are offered to choose a method / parameter) - the IDE does not show anything "superfluous" (only public) when using the class.
  3. Security Code (foolproof)
    • It is impossible foolishly to call a method from another class that does NOT need to call from it. (here you have a microwave - you have access to Run () and ChangeTime (), but you don’t have access to ChangeFrequency of Waves () [this is an internal implementation that you don’t need to be given access to "mortals" so as not to confuse and harm to your class instance by mindlessly changing parameters with the hands of mortals] )
    • It is impossible to change from the outside a property that does not need to be changed from the outside. (Wave Frequency) [same]
    • The ability to change the whole class interior (all privates) from the beginning without the “external code”, which works exclusively with the public of this class, will remain working as before. You can change the whole internal implementation of the microwave at the root - replace all parts, insert other boards, but all public methods and parameters will remain in place. Visually, the microwave will not even change - the user will not even guess that something has changed, since it has become subjectively or objectively better to work.
  4. As Barmaley noted, this is also a tool for planning future releases. We can close access to some features / methods / parameters that are still raw so that users of the class would not use them until a particular release.

TOTAL: In consequence of the use of the principle of encapsulation, the programmer decreases the possibility of making a mistake in stupidity and increases the productivity on medium-small, medium and large projects since the code becomes simpler and safer when changing the class itself.

(On very small projects in a couple of small classes, the programmer's performance may fall due to "unnecessary actions", but in fact, it's still worth it)

    off-topic

    If there is a private method, this is already an invitation to the hacking, namely, calling a private method through the Java Reflection API is easy to google, I will not even give examples of how this is done.

    In this context, fun to read:

    private methods and variables are visible only inside the class. They are not seen by any other classes. Even their children. This is done to prevent unwanted data changes from the outside.

    Now to the essence of the issue of the vehicle

    Private methods are sometimes done in order to make them public someday. I personally observed this using the SMS / MMS API in Android, when in early versions of Android, the methods for working with SMS were mostly hidden / private , and then somewhere in the KitKat area they began to open (declare public ) and loudly announced new api :)

    So besides encapsulation, I see plus the use of private methods as a means of planning future releases.

    • one
      I would also add that private ones increase the programmer’s productivity, if only because making up a name for them sometimes takes much less time -). - avp
    1. As an official answer: a private-модификатор is part of the data encapsulation .

    Encapsulation protects object data from unwanted access, allowing an object to control access to its data itself.

    1. Your answer: there is such a thing as an API ( application programming interface ). From the point of view of a java-класса , its public-методы are its API , since through these methods you can interact with this java-классом in your code. In turn, private-методы always hidden from the outside. Accordingly, the modification of private-методов will not affect the public-методов signatures. That is, all external interactions with this java-классом , after modifying its private-методов , most likely will not require any improvements. And this is the advantage of private methods!

      There is such a concept - encapsulation.

      Ie users of your class should not be aware of the internal structure of your class.

      The user must interact with the fields through special methods that do not allow, for example, misappropriation.

        I will summarize the answers

        The private modifier is part of the data encapsulation .

        Encapsulation protects object data from unwanted access, allowing an object to control access to its data itself.

        For a private member of a class, you cannot set a value directly in the code outside the class. But at the same time, you can completely control how and when data is used in an object. Consequently, a correctly implemented class forms a kind of “black box” that can be used, but the internal mechanism “of its action is closed for outside intervention.

        Java

        The java programming language has many features to hide information. One of them is the access control mechanism, which sets the level of accessibility for interfaces, classes, and class members. The availability of any entity is determined by where it was declared and which access modifiers, if any, are present in its declaration (private, protected or public).

        As a consequence, we have:

        1 A simpler code structure (you can see exactly where the implementation is internally important, and where it is important for external objects)

        1.1 When writing a sufficiently large piece of code (whether it is a class, a function, or something else), an important technique is decomposition. You divide the functionality into logical parts, and in the main function you add up from them, like from bricks, a common logic.

        At the same time, the bricks themselves may not be adapted for access from outside. For example, an open method can check input parameters, and auxiliary brick methods are no longer necessary, since they are called only from the inside. If these methods were open, they would need to implement parameter checking, and when implementing them it would be impossible to expect that they would be called at the moment you control.

        2 In addition, internal methods have the right to spoil the state of the class, if you know that the code that calls them will fix this problem later. If these methods are made public, users of this class will be able to spoil the internal state of the class without repair.

        3 Secure Code

        3.1 It is impossible to call a method from another class that does not need to be called from it.

        3.2 It is impossible to change from the outside a property that does not need to be changed from the outside.

        4 The ability to change the implementation of the internal structure of a class (all that relates to privates) is not the “external code”, which is tied exclusively to the public.

        4.1. In joint projects, programmers have less opportunity to make a mistake due to ignorance of the features of the source code.

        4.2 Increased productivity on medium-small, medium and large projects because the code gets easier and safer. (On very small projects in a couple of small classes, the programmer's performance may fall due to "unnecessary actions", but in fact, it's still worth it)

        4.3 Well, in the end, the public method is a promise for users. Every change (deletion, change of signature, and sometimes addition) of an open method - breaking change for clients, they should review the code that your class uses. Thus, you should not just like that, without the special need to change the public methods of the class. But changes in closed methods usually occur when refactoring in a mass order: methods are simplified, combined, decomposed into several, transferred up and down the hierarchy, their semantics change, and all this does not affect the users of your class.

        5 Private methods use static binding in Java, and they are linked at compile time, which is quickly compared to the dynamic binding that occurs at run time, and also gives the JVM a chance to either embed the method or optimize it.

        6 Assigning variables to private in java and giving them getter and setter makes your class compatible with the naming of Java beans and other reflection-based structures such as displaytag.

        7 If you look at the private method, you probably know that no one uses it, which helps a lot when debugging a java program.

        8 More convenient hints (when you put an end and you are offered to choose a method / parameter) - the IDE does not show anything "superfluous" (only public) when using the class.

        IDEs, such as Netbeans, IDEA and Eclipse, use this information and automatically check whether private methods are used within a class or not, and can display a warning to improve code quality or remove unused statements, variables or methods.

          The only extremely important factor that distinguishes a well-designed module from an unsuccessful one is the degree of hiding its internal data and other implementation details from other modules. A well-designed module hides all implementation details, clearly separating its API and implementation. Modules interact with each other only through their API, and none of them knows what processing takes place inside another module. This concept, called information hiding or encapsulatiori, is one of the fundamental principles of software development.

          Information hiding is important for many reasons, most of which are related to the fact that this mechanism effectively isolates the modules that make up the system from each other, making it possible to develop, test, optimize, use, investigate and update them separately. This accelerates the development of the system, since different modules can be created in parallel. In addition, the maintenance costs of the application are reduced, since each module can be quickly studied and debugged, at the minimum risk of harming the other modules. Information hiding alone cannot provide good performance, but it creates the conditions for effective performance management. When the development of the system is completed and the procedure for its profiling has shown which modules work causes a drop in performance, you can optimize them without disrupting the functioning of the other modules. Information hiding increases the possibility of program reuse, since each individual module is independent of the other modules and is often useful in other contexts than the one for which it was designed. Finally, information hiding reduces the risks in building large systems: individual modules can be successful, even if the system as a whole does not enjoy success.

          The java programming language has many features to hide information. One of them is the access control mechanism, which sets the level of accessibility for interfaces, classes, and class members. The availability of any entity is determined by where it was declared and which access modifiers, if any, are present in its declaration ( private , protected or public ). Proper use of these modifiers is essential for hiding information.

          The main rule is that you must make each class or member as unavailable as possible. In other words, you should use the lowest possible level of access that still allows for the correct functioning of the program being created.

          For classes and top-level interfaces (non-nested), there are only two possible access levels: available only within a package ( package-private ) and open ( public ). If you declare a top-level class or interface with the public modifier, it will be open, otherwise it will be available only within the package. If a top-level class or interface can only be made available in a package, you need to do so. In this case, the class or interface becomes part of the implementation of this package, and not part of its external API. You can modify it, replace it, or exclude it from the package without fear of harming customers. If you make a class or interface open, it is your responsibility to always support it in order to maintain compatibility. If a class or top-level interface, available only within a package, is used in only one class, you should consider turning it into a private class (or interface) that will be nested in the class where it is used. Thereby, you will further reduce its availability. However, this is no longer as important as making an unreasonably open class available only within a package, since a class that is available only in a package is already part of the implementation of this package, and not its external API.

          For class members (fields, methods, nested classes, and nested interfaces), there are four possible access levels that are listed here in order of increasing accessibility:

          • Private ( private ) - this member is available only within the top-level class where it was declared.

          • Available only within a package (package-private) - a member is accessible from any class within the package where it was declared. Formally, this level is called default access, and it is this level of access that you get if access modifiers have not been specified.

          • A protected member is available for subclasses of the class in which this member was declared (with some restrictions); member access can be obtained from any class in the package where this member was declared.

          • Open ( public ) - member accessible from anywhere.

          After an open API has been carefully designed for your class, you should make all other members of the class private. And only if another class really needs access to a member from the same package, can you remove the private modifier and make that member accessible within the entire package. If you find that there are too many of these members, double check your model of the system and try to find another option to divide classes into which they would be better isolated from each other. As mentioned, both the private member and the member, available only within the package, are part of the class implementation and usually do not affect its external API. However, they can "leak" into the external API if the class implements the Serializable interface.

          If the access level for an open class member changes from the available in the package to the protected one, the availability level of this member increases dramatically. For this class, the protected member is part of the external API, and therefore it must always be supported. Moreover, the presence of a protected member in a class that is transferred outside the package is an open transfer of implementation details. The need to use protected members should occur relatively rarely. There is one rule that limits your ability to reduce the availability of methods. If a method overrides a super class method, then the method in the subclass is not allowed to have a lower level of access than the method in the superclass. This is necessary to ensure that an instance of the subclass can be used wherever an instance of the superclass can be used. If you break this rule, then when you try to compile this subclass, the compiler will generate an error message. A special case of the rule: if a class implements a certain interface, then all the methods of the class represented in this interface must be declared as public . This is explained by the fact that in the interface all methods are implicitly implied by the open ones.

          Open fields (as opposed to open methods) in open classes should be a rare occurrence (if they have to APPEAR at all). If the field does not have a final modifier or has a modifier and refers to the object being modified, then by making it open, you miss the possibility of imposing restrictions on the values ​​that can be written in this field. You also lose the opportunity to take any action in response to a change in this field. Hence a simple conclusion: classes with open variable fields are unsafe in a system with several threads (not thread-safe). Even if the field has a final modifier and does not refer to the object being changed, declaring it open, you refuse the possibility of a flexible transition to a new view of the internal data in which this field is missing.

          There is one exception to the rule prohibiting open classes from having open fields. Using the public static final fields, classes can expose constants to the outside. According to the agreement, the names of such fields are composed of capital letters, the words in the title are separated by an underscore. It is extremely important that these fields contain either simple values ​​or references to immutable objects. A field with a final modifier that contains a link to a variable object has all the drawbacks of a field without a final modifier: although the link itself cannot be changed, the object to which it points can be changed - with fatal consequences.

          Note that a non-zero length array is always mutable. Therefore, you can almost never declare an array field as public static final . If the class has such a field, customers will be able to change the contents of this array. Often this is the cause of holes in the security system.

           // Потенциальная дыра в системе безопасности public static final Туре[] VALUES = { ... } ; 

          The open array should be replaced with a closed array and an open immutable list:

           private static final Туре[] PRIVATE_VALUES = { ... }; public static final List VALUES = Collections.unmodifiableList(Arrays.asList(PRIVATE_VALUES)); 

          Another way: if at the compilation stage you need type checking and you are ready to sacrifice performance, you can replace the open field of the array with an open method that returns a copy of the private array.

           private static final Туре[] PRIVATE_VALUES = { .. . } ; private static final Туре[] values() { return ( Туре[] ) PRIVATE_VALUES.clone(); } 

          Let's sum up. You should always reduce access levels as much as possible. By carefully designing the smallest open API, you should not allow any random classes, interfaces, and members to become part of this API. With the exception of public static final fields, there should be no other open fields in the open class. Make sure that the objects referenced in public static final fields are not modifiable.

          Source: "Java. Effective programming." Joshua Bloch.

          • It is strange that no one else has led this author (: - Tachkin
          • five
            so tempts to write "niasilil, mnogabukf" - rjhdby
          • one
            Who is gosling ?? =) - vp_arth
          • one
            @vp_arth, holy, holy, holy, how can you say that? As a penance, rebuild all the projects on the home machine, and write FizzBuzz kata 10 times. - Tachkin
          • 2
            Brevity is the soul of wit? - user207618

          The first principle of OOP is encapsulation. In essence, it means the ability to hide irrelevant implementation details from the object user by means of the language. Object users welcome encapsulation, since this principle of OOP allows to simplify programming tasks. Нет необходимости беспокоиться о многочисленных строках программного кода, который выполняет работу класса "за кулисами". Bсe, что требуется от вас, – это создание экземпляра и отправка подходящих сообщений.

          Одним из аспектов инкапсуляции является защита данных. В идеале данные состояния объекта должны определяться, как приватные. В этом случае "внешний мир" будет вынужден "смиренно просить" право на изменение или чтение соответствующих значений. (c) Троелсен

            Для тех, кому нужен быстрый ответ , без надобности углубляться сильно в инкапсуляцию.

            private методы и переменные видны только внутри класса. Их не видят никакие посторонние классы. Даже их дети. Это делают для предотвращения нежелательного изменения данных извне.

            Например, ты создаешь Аккаунт в банке, это будет наш объект. Ты не хочешь чтобы у кого-нибудь извне была возможность сменить пароль или посмотреть, какой баланс у тебя на счету, кроме тебя. Таким образом методы changePassword() и viewBalance() будут private . А метод типа viewProfile() для просмотра твоего профиля будет открыт для всех, т.е. public .