"Effective Java" chapter 4th Class and interface

Source: Internet
Author: User

13th: Minimizing the accessibility of classes and members

The first rule is simple: make every class or member non-accessible to the outside world as much as possible. Other words. You should use the lowest possible level of access consistent with the corresponding functionality of the software you are writing.

For top-level (non-nested) classes and interfaces, there are only two possible levels of access: package-level Private (package-private) and public. If you declare a top-level class or interface with the public modifier, it is publicly owned. Otherwise, it will be a 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 is actually part of the implementation of the package, not part of the API exported by the package, which can be modified, replaced, or deleted in a later release, without worrying about affecting existing client programs. If you make it public, it is your responsibility to always support it to maintain their compatibility.

If a package-level private top-level class (or interface) is used only within a class, consider making it a private nested class of the only class that uses it (see 22nd). This reduces the scope of its accessibility from all classes in the package to the class that uses it. However, it is much more important to reduce the accessibility of unnecessary public classes than to reduce the top-level classes that are private to the package class: Because the public class is part of the package's API, and the package-level private top class is already part of the implementation of the package.

There are four possible levels of access for members (domains, methods, nested classes, and nested interfaces), listed below in ascending order of accessibility:

    1. Private--This member can only be accessed within the top-level class that declares the member.
    2. Package-level Private (package-private)-the member can be accessed by any class within the package that declares the member. Technically, it is referred to as the "default" access level, which is used if no access modifier is specified for the member.
    3. protected (protected)-the subclass of the class that declares the member can access this member (but there are some restrictions [JLS, 6.5.2]), and any class within the package that declares the member can also access this member.
    4. Public-the member can be accessed everywhere.

Classes that contain mutable fields are not thread-safe.

If the final field contains a reference to a Mutable object, it has all the drawbacks of a non-final domain. Although the reference itself cannot be modified, the object it refers to can be modified-which results in catastrophic consequences.

Note that arrays of nonzero lengths are always mutable, so it is almost always wrong for a class to have a public static final array field, or to return a method of access to such a city.

It is important to note that many Ides have access methods that return references to private array fields, which creates this problem. There are two ways to fix this problem. You can make a public array private, and a well adds a public immutable list:

Another way is to make the array private, and the well adds a public method that returns a backup of the private array:

In addition to the special case of a public static final domain, public classes should not contain public domains. And make sure that the objects referenced by the public static final domain are immutable.

16th: Compound takes precedence over inheritance

Unlike the method invocation, inheritance breaks the encapsulation. The implementation of the superclass may change depending on the release version, and if it does, the subclass may be compromised, even if its code does not change at all.

One of the related reasons for the fragility of subclasses is that their superclass can acquire new methods in subsequent releases.
If the superclass gets a new method in subsequent releases, well and unfortunately, you give the subclass a method that has the same signature but a different return type, then such subclasses will not compile.

Fortunately, there is one way to avoid all the problems mentioned earlier. Instead of extending an existing class, add a private domain to the new class that is an instance of an existing class. This design is called "composition" because the existing class becomes a component of the new class. Each instance method in the new class can invoke the corresponding method in an existing class instance that is contained and return its results. This is called forwarding (forwarding), and the method in the new class is called the Forwarding method (forwarding). The resulting class will be very stable, and it does not depend on the implementation details of the existing class.

Inheritance is only appropriate when subclasses are really sub-types (subtype) of the superclass. In other words, for two classes A and B, Class B should be extended only if there is a real "is-a" relationship between the two. If the answer is no, normally, B should contain a private instance of a, and exposing a smaller, simpler api:a is inherently not part of B, but it's implementation details.

Implementation details are unnecessarily exposed if inheritance is used where it is appropriate to use compositing.

17th: Either design for inheritance, provide documentation, or prohibit inheritance

The design for inheritance involves not only the design of the document for personal use. In order for programmers to write more efficient subclasses without suffering unnecessary pain, the class must provide the appropriate hooks in some form to be able to enter into its internal workflow, which can be a carefully chosen protected (protected) method, or a protected domain, or , the latter is relatively rare.

For classes designed for inheritance, the only way to get started is to write to the class.

To allow inheritance, classes must also adhere to some other constraints. The constructor must never invoke a method that can be overwritten, whether it is a direct call or an indirect call. If this rule is violated, it is likely to cause the program to fail. The constructor of the superclass runs before the constructor of the subclass, so the method that overrides the version in the subclass will be called before the child class's constructor is run.

The best solution to this problem is to prohibit subclasses for classes that are not designed and written for the sake of safe sub-class. There are two ways to prohibit subclasses. The easier way is to declare this class final. Another way is to make all the constructors private, or package-level private, and add some public static factories to replace the constructors.

18th: interface is better than abstract class
    • Existing classes can easily be updated to implement the new interface.
    • An interface is an ideal choice for defining mixin(mixed types.
    • Interfaces allow us to construct a type framework that is not hierarchically structured.

Although interfaces do not allow implementations of methods, using interfaces to define types does not prevent you from providing implementation assistance to programmers. By providing an abstract skeleton implementation (skeletal implementation) class for each important interface you export, combine the advantages of interfaces and abstract classes. The function of the interface is still the definition type, but the skeleton implementation class takes over all the work related to the implementation of the interface.

The class that implements this gate can forward the invocation of the interface method to an instance of an internal private class, which extends the skeleton implementation class. This approach is called analog multiple inheritance (simulated multiple inheritance). Refer to "Reference" 1 "for multiple inheritance.

19th: interfaces are only used to define types

Changdong interface mode is a bad use of the interface.

If you want to export constants, there are several reasonable alternatives. If these constants are closely related to an existing class or interface, they should be added to the class or interface. If these constants are best considered to be members of an enumeration type, they should be exported using the enumeration type (enum type) (see article 30th). Otherwise, you should use a non-instantiated tool Class (utility Class) (see 4th) to export these constants.

20th: Class hierarchy is better than label class

Tag class: Consider the following class, which can represent a circle or a rectangle:

This label class (tagged Class) has many drawbacks. They are filled with boilerplate code, including enumeration declarations, label fields, and conditional statements. The readability is undermined by multiple implementations scrambling seven or eight of slots in a single class. The memory footprint is also increased because the instance assumes an unrelated domain that belongs to other styles.

Label classes are too verbose, error-prone, and inefficient. The Label class is a simple imitation of the class hierarchy.

To turn a label class into a class hierarchy, you first define an abstract class that contains abstract methods for each method in the Label class, and the behavior of each method depends on the tag value. Next, define the specific subclasses of the root class for each of the original authentication classes.

21st: Using a Function object to represent a policy

Java does not provide a function pointer, but the same functionality can be implemented with object references. The method on the calling object is typically an operation on the object that is executed on the objects. However, we may also define an object whose methods perform operations on other objects (other objects), which are passed explicitly to these methods. If a class simply exports such a method, its instance is actually equivalent to a pointer to the method. Such an instance is called a function object. For example, consider the following class:

A reference to a Stringlengthcamparator object can be treated as a pointer to the comparer "function pointer", which can be called on any pair of strings. In other words, the Stringlengthcamparator instance is a specific strategy for string comparison operations (concrete strategy).

As a typical concrete policy class, the Stringlengthcamparator class is stateless (stateless): It has no domain, so. All instances of this class are functionally equivalent to each other. Therefore, it is very appropriate as a singleton to save unnecessary object creation overhead (see articles 3rd and 5th):

In short, the primary purpose of a function pointer is to implement the policy (strategy) pattern. To implement this pattern in Java, declare an interface to represent the policy, and declare a class that implements the interface for each specific policy. When a specific policy is used only once, an anonymous class is typically used to declare and instantiate the specific policy class. When a specific strategy is designed to be used repeatedly. Its class is typically implemented as a private static member class, and is exported through a public static final domain, and its type is the policy interface.

22nd: Prioritize static member classes

Each instance of a non-static member class is implicitly associated with a peripheral instance of the perimeter class (enclosing instance).

A common use for static member classes is to define a adapter[gamma95, p.139], which allows an instance of an external class to be treated as an instance of another unrelated class. For example, implementations of map interfaces often use non-static member classes to implement their collection views (collection View), which are returned by the map's keyset, EntrySet, and values methods. Similarly, implementations such as set and list are often implemented using non-static member classes to implement their iterators (iterator):

A common use of private static member classes is to represent the components of the objects represented by the perimeter class. For example, consider a map instance, which associates the key (key) with the value. Many map implementations have an entry object in the interior that corresponds to each key-value pair in the map. Although each entry is associated with a map, the methods on entry (Getkey,getvalue and SetValue) do not require access to the map. Therefore, it is wasteful to use non-static members to represent entry: The private static member class is the best choice. If you accidentally omit the static modifier from the entry declaration, the map still works, but each entry will contain a reference to the map, wasting space and time.

Because anonymous classes appear in expressions, they must be kept short-about 10 rows or less-otherwise it can affect the readability of the program.
A common use of anonymous classes is to dynamically create functions like (Functivn object, see section 21t)
Another common use of anonymous classes is to create process objects, such as runnable, thread, or timertask instances.
The third common use is within the static factory method.

Resources

"1" Java Improvement Chapter (ix)-Implement multiple inheritance http://www.cnblogs.com/chenssy/p/3389027.html

"Effective Java" chapter 4th Class and interface

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.