13th: Minimize the accessibility of classes and members

Source: Internet
Author: User
Tags modifier modifiers


Encapsulation (encapsulation) or "information hiding (information hiding)": The module Hides all implementation details, isolates its APIs from its implementation, communicates communication between modules only to their APIs, A module does not need to know the internal work of other modules.

Information hiding is important because it effectively relieves the coupling between the modules that make up the system and facilitates their independent development, testing, optimization, use, understanding, and modification. This can speed up system development because these modules can be developed in parallel. It also reduces the burden of maintenance , because programmers can understand these modules faster, and while debugging them without affecting other modules, although information hiding itself does not bring better performance both internally and externally, it can effectively adjust performance: Once a system is completed, and through the analysis to determine which modules affect the performance of the system, those modules can be further optimized without affecting the correctness of the other modules, that is, after the modules of the system are modular, you can perfect a module in the future to improve performance without having to involve other modules, This is one of the advantages of loose coupling. It also improves the reusability of modules because they are not tightly connected and are often useful in other environments besides developing the environments used by these modules. Finally, information hiding reduces the risk of building large systems , because even if the entire system is not available, these standalone modules may be available.

Access control in Java provides an important safeguard for information hiding, which determines the accessibility of classes, interfaces, and members (accessibility). The accessibility of an entity is determined by the location of the entity's reputation and by the access modifiers (private, protected, public, or default) that appear in the entity's reputation.

The basic rule is to make every class or member inaccessible to the outside world as much as possible. that is to minimize the level of access as much as possible.

for top-level (not nested) classes and interfaces, there are only two possible levels of access: package-level Private (package-private) and public. If you use the public modifier to fame the top-level class and interface, 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 package-level private, by making the class or interface into a package-level private so that it actually becomes part of the implementation of the package, rather than part of the API exported by the package, if you need to modify, replace, or delete it in the future, There is no need to worry about affecting the existing client, because the client only uses the exported API and is not closely associated with the specific implementation. However, if it is made public, it becomes part of the API, and the developer has a responsibility to support it forever to maintain their compatibility. If a package-level private top-level class or interface is used only within a class, consider making it the inner class of a particular class so that its accessibility can be narrowed from all classes in the package to the class that uses it. However, it is more important to reduce unnecessary class-only accessibility than to reduce the level of private top-level classes. Because the public class is part of the package's API and is part of the client's real use, the top-level class of the package-level private is already part of the implementation of the package, in short, "It's easier to deal with yourself than with others." ”

There are four possible access levels for members (including domains, methods, nested classes, and nested interfaces):

1, Private (private): This member can only be accessed within the top-level class that declares the member.

2. Package-level Private (package-private): any class within the package that declares the member can access this member. This is also known as the default access level, which is used if no access modifiers are specified for the member.

3, Protected (Protected): a subclass of the class that declares the member can access this member, and any class within the package that is known to the member can also access that member.

4. Public: the member can be accessed anywhere.

As you can see, the four access levels above are constrained by strong to weak, and when you carefully design the only API for a class, you may feel that you should make all 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 that you often need to do this, then you should re-examine the system design to see if there is another kind of decomposition scheme the class can make the coupling between other classes smaller.

Private members and package-level private members are part of the implementation of a class and generally do not affect its exported APIs, but if the class implements the Serializable interface, then these domains are likely to be leaked to the exported API. for members with only classes, accessibility is greatly enhanced when the access level becomes a protection level from package-level private. Protected members are part of the export API for a class, but this also brings trouble to consider the compatibility API in the future, and protected members of the derived class also represent the class's public commitment to an implementation detail. protected members should be used sparingly.

If the method overrides one of the methods in the superclass, the access level in the subclass is not allowed to be below the access level in the superclass, which ensures that any instance using the salts can also use instances of subclasses, and if this rule is violated, the compiler generates an error when attempting to compile the subclass. This rule has a special case: If a class implements an interface, then all the methods in the interface must be known as common in this class, because all the methods in the interface implicitly have the public access level. At the same time, it is not necessary to turn a class, interface, or member variable into a part of the export API of a package for testing purposes, and you can implement the test as part of the test package so that it has access to the package-level private element.

The instance domain is not public. If the domain is not final, or it points to a final reference to a Mutable object, this would mean abandoning the ability to limit the values stored in the domain, and also giving up the ability to force the domain to be immutable. When the layoffs were revised, the ability to take any action was also boosted. Therefore, classes that contain mutable domains are not thread-safe. Even if the domain is final and the immutable object referenced, when the domain becomes the only time, the flexibility to "switch to a new internal data representation" is discarded because you have exposed it to the client and become a part of the client's access. There are also problems with static domains, but if constants form part of the entire abstraction provided by the class, they can be exposed through the only static final domain. The names of such fields are made up of uppercase letters and the words are separated by an underscore. Here are the examples from Java.math

     * The {@code double} value that's closer than any other
     to * <I>E</I>, the base of the natural Lo Garithms.
    /public static final Double E = 2.7182818284590452354;

     * The {@code double} value
     , which is closer than the "other to * <I>PI</I>, the ratio of the CIRCUMFE Rence of a circle to its
     * diameter.
     * * Public
    static final double PI = 3.14159265358979323846;

It is important that these fields either contain values of the base type or contain references to immutable objects. If the 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 refers to can be modified.

An array of nonzero lengths is always variable, note the following code:

	Potential security hole!
	public static final thing[] VALUES = {...};
Note that many Ides produce an access method that returns a reference to a private array field, which creates this problem, and there are two ways to fix the problem generally. you can make only an array private, and add an only mutable list:

private static final thing[] Private_values = {...};
public static final list<thing> VALUES = 
			collections.unmodifiablelist (arrays.aslist (private_values));
The Help method collections.unmodifiablelist limits the list to immutable. Another approach is to make the array private, and add an only method that returns a backup of the private array.


	private static final thing[] Private_values = {...};
	public static final thing[] values () {return
		private_values.clone ();
All in all, you should always reduce accessibility as much as possible. After careful design of a minimal public API, you should prevent any scattered classes, interfaces, and members from becoming part of the API. Public classes should not contain public domains except for special cases where only static final domains are available. and to ensure that the objects referenced by the public static final domain are 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.