Java performance Optimization (12): minimizing class and member accessibility __java

Source: Internet
Author: User
Tags modifier modifiers

Classes and interfaces are the core of the Java programming language, and they are also the basic abstraction units of the Java language. The Java language provides a number of powerful basic elements for program apes to design classes and interfaces.

The most important factor to distinguish between a well-designed module and a poorly designed module is whether the module hides internal data and other implementation details for other external modules. A well-designed module hides all implementation details, separating its APIs from the implementation. Then, the modules communicate with each other only through their APIs, and a module does not need to know the work inside other modules, which is called encapsulation.

There are many reasons why encapsulation is important, most of which stems from the fact that it effectively removes the coupling between modules in a system, enabling them to be independently developed, tested, optimized, used, understood, and modified. This can speed up system development because these modules can be developed in parallel. It also reduces the burden of maintenance because programmers can quickly understand these modules and can debug them without harming other modules. Although the encapsulation itself, both internal and external, will not bring better performance, but it makes effective performance tuning possible. Once a system has been completed and analyzed to see which modules affect the performance of the system, these modules can be further optimized without affecting the correctness of the other modules. Encapsulation can improve software reusability because individual modules do not rely on other modules, and they are often useful in other environments, in addition to the environments in which these modules are developed. Finally, encapsulation also reduces the risk of building large systems, which can be successful even if the entire system is not successful.

The Java programming language provides many facilities to help you sit down to information hiding. One of these facilities is the access control mechanism, which determines the accessibility of classes, interfaces, and members.

The accessibility of an entity is determined by the location of the entity declaration, and by the access modifier Fu Gong that appears in the entity declaration. Using these modifiers correctly is critical to implementing encapsulation.

experience shows that you should try to make every class or member inaccessible to the outside world. in other words, you should use the access level that is the lowest possible and consistent with the correct functionality of the software.

For top-level classes and interfaces, they have only two possible levels of access: package-level private and public. If you declare a top-level class or interface with a public modifier, it is publicly owned, otherwise it will be package-level private. If a class or interface can be made into a packet-level private, it should be made into a packet-level private. By making a class or interface into a package-level private, it's actually part of the implementation of the package, not part of the package's export API, and in future releases you can modify, replace, or remove it without having to worry about hurting existing customers. If you make it public, you have an obligation to support it forever to maintain compatibility.

If a package-level private top-level class or interface is used only within a class, you should consider making it a private nested class of the latter. This can further reduce its accessibility, however, it is not as important as "making an unnecessarily common class A private class" because a package-class private class is already part of the implementation of this package, not part of its API.

For members, there are four possible levels of access, listed below in an ascending order of accessibility:

Private-access to this member only within the top-level class that declares the member

Package-level private--any class within the package that declares the member can access the member. Technically, it is called the "Default access level", and it has such access levels if no access modifiers are specified for the member.

Protected-This member declares that the subclass of the class that contains the member can access the members, and that the member is accessible to any class within the package that contains the member declaration.

Public-access to that member anywhere.
Once you have carefully designed the public API for a class, you should then make all the other members private. Only when another class in the same package really needs to access a member should you remove the private modifier and make the member a package-level private. If you find yourself often doing things like this, then you should re-examine your system design to see if the classes obtained by another decomposition scheme have better separation properties and are less coupling to each other. It can be said that private members and package-level private members are part of a class implementation and do not affect the APIs to which they are exported. However, if these domains are in a class that implements the serializable interface, these domains may be "compromised" in their exported APIs.

For members of the public class, a significant increase in accessibility occurs when the access level becomes a protection level from package-level private. Protected members are part of a class export API and must always be supported. Further, each protected member of an exported class represents the class's public commitment to an implementation detail. Protected members should be used sparingly.

There is a rule that makes it impossible for you to reduce the accessibility of a method. If a method overwrites a method in the superclass, the access level of the method in the subclass is lower than the access level in the superclass. This ensures that the subclass instance can be used in any instance where the superclass can be used. If you violate this rule, the compiler generates an error message when you attempt to compile the subclass. A special case of this rule is that if a class implements an interface, then all the methods in the interface must be declared public in the class. This is because all the methods in the interface implicitly have the public access level.

The public class should contain as many public domains as possible. If a domain is not final, or a final reference to a Mutable object, once you make it public, you discard the ability to limit the values stored in the domain; When the domain is modified, you also lose the ability to take any action. A simple consequence is that classes that contain public mutable domains are not thread safe. Even if a domain is final and does not point to any of the mutable objects, once you make the domain public, you give up the flexibility to "switch to a new internal data representation."

There is also an exception to the rule that "public classes should not contain public domain", and it is permissible to expose the constants of a class through the public static final domain. By convention, the names of such fields are made up of uppercase letters, and the words are separated by an underscore. It is important that these fields either contain a value of the primitive type or contain a reference to a Mutable object. If a final field contains a reference to a Mutable object, it has all the disadvantages of a non-final domain. Although the reference itself cannot be modified, the object it references can be modified-which can lead to catastrophic consequences.

Note that a non-0-length array is always variable, so it is almost always wrong to have a public static final array field . If a class contains such a domain, the customer will be able to modify the contents of the array. This is a common source of security vulnerabilities:

public static final type[] VALUES = {...};
private static final type[] Private_values ={...};
public static final List VALUES =
collections.unmodifiablelist (arrays.aslist (private_values));

Alternatively, if you require the type of compile-time security and are willing to lose a bit of performance, you can replace the public array with a public method that returns a copy of the private array:

private static final Type [] private_values = {...};
public static final Type [] values () {return
(type[]) private_values.clone ();
}

In short, you should always be able to reduce accessibility, and after carefully designing a minimal public API, you should prevent any stray classes, interfaces, and members from becoming part of the API. The public class should not contain public domain except for the special case of the public static final domain. And make sure that the object referenced by the public static final field is immutable.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.