The 7th chapter of the effective Java method

Source: Internet
Author: User
Tags variadic

38th: Check the validity of the parameters

For public methods, the Javadoc @throws tag (tag) is used to describe the exception that is thrown when a violation of a parameter value restriction is in the document. Such exceptions are usually illegalargumentexception, indexoutofboundsexception, or NullPointerException.

Non-public methods should generally use assertions (assertion) to examine their parameters, as follows:

39th: A protective copy if necessary

Without the help of an object, while another class cannot modify the internal state of an object, it is easy for an object to provide this help unconsciously. For example, consider the following class, which claims to represent a period of time that is immutable:

At first glance, this class seems immutable and imposes constraints: the start time of the cycle (start) cannot be after the end time (end). However, because the date class itself is mutable, it is easy to violate this constraint:

In order to protect the internal information of the period instance from this attack, it is necessary to have a protective bake shell (defensive copy) for each variable parameter of the constructor, and use the Backup object as the component of the period instance instead of the original object:

Note that a protective copy is performed before checking the validity of the parameter, and the validity check is the object after the needle is copied, not the original time image of the needle. Although this may seem a bit unnatural, it is necessary.

41st: Careful use of heavy-duty

A counter example:

You may expect this program to print "Set", followed by "List", and "Unknown Collection", but it is not. It is printed "Unknown Collection" three times.

The classify method is overloaded (overloaded), and which overload (overloading) method to invoke is determined at compile time. For all three iterations in the For loop, the compile-time type of the parameter is the same:collections<>. The run-time types of each iteration are different, but this does not affect the selection of overloaded methods. Because the compile-time type of the parameter is Collection<>.

The behavior of this program is counterintuitive, because the choice of overloaded methods (overloaded method) is static, and the choice of overridden methods (overridden method) is dynamic. Selecting the correct version of the overridden method is done at run time, based on the run-time type of the object to which the method is called.

The name method is declared in the class wine, but is overridden in classes Sparklingwine and champagne. As you might expect, this program prints out "wine, sparkling wine and champagne", although in each iteration of the loop, the compilation-time type of the instance is wine. When the overridden method is called, the compile-time type of the object does not affect which method will be executed; The most specific (most specific) version of the overlay will always be executed.

The best remedy for the classify method is to replace the three overloaded classify methods with a single method, and to do an explicit instanceof test in this method:

Because the overlay mechanism is the norm, and the overloading mechanism is the exception, the override mechanism satisfies people's expectations of the method invocation behavior. As the Collectionclassifier example shows, overloading mechanisms can easily frustrate these expectations.

What exactly is the use of overloaded mechanisms? The question remains controversial. A safe and conservative strategy is to never export two overloaded methods with the same number of parameters. If the method uses a mutable parameter (varargs), the conservative policy is not to overload it at all.

You can always give a different name to a method without using an overloaded mechanism.

For constructors, you do not have the opportunity to use different names, and multiple constructors for a class are always overloaded. In many cases, you can choose to export a static factory instead of a constructor.

JDK a counter example
Before the release of Java 1.5, all the base types were fundamentally different from all reference types. But when auto-boxing occurs, it's no longer the case, it can cause real trouble. Consider the following procedure:

If it's like most people. You want the program to go from the collection and list unless the integer values (0, 1, and 2) and print out [-3,-2,-1] [-3,-2,-1]. In fact, print out [-3,-2,-1] [-2, 0,-2].

What actually happens is: Set.remove (i) calls the Select overloaded method, remove (e), where E is the element type of the collection (Integer), and I automatically boxed i from int to Integer. This is the behavior you expect, so the program does not remove positive values from the collection. On the other hand, List.remove (i) invokes the Select overloaded method, remove (int i), which removes the element from the specified position in the list.

42nd: Use variable parameters with caution

A variadic method accepts 0 or more parameters of a specified type. The variadic mechanism creates an array by first, the size of the array is the number of arguments passed at the call location, then passes the parameter values to the array, and finally the array is passed to the method.

Both printf and reflection mechanisms greatly benefit from variable parameters.

43rd: Returns an array or set of 0 lengths, not NULL

For a method that returns null instead of a 0-length array or collection, this tortuous process is required almost every time the method is used. This is prone to error because programmers writing client programs may forget to write this specialized code to handle null return values.

Sometimes people think that a null return value is better than a zero-length array because it avoids the overhead required to allocate an array. This argument is untenable, for two pips first, it is unwise to worry about performance at this level unless the analysis shows that this approach is the real source of performance problems (see 55th). Second, it is possible to return the same 0-length array each time for calls that do not return any elements, since 0-length arrays are immutable, and immutable objects may be freely shared (see article 15th).

For example, you can do this:

Similarly, the method of collection values can be made to return the same immutable empty collection whenever an empty collection needs to be returned. The Collections.emptyset, Emptylist, and Emptymap methods provide exactly what you need, as follows:

In short, the return type is an array or a collection of methods and there is no reason to return NULL, instead of returning a 0-length arrays or collections.

44th: Write a document comment for all exported API elements

In order to properly write the API documentation, you must add a document comment before each exported class, interface, constructor, method, and domain declaration.

Use characters before multiple lines of code sample

{@code, then add} after the code

Do not forget that special actions must be taken to produce documents that contain HTML metacharacters, such as less than (<), greater than (>), and "and" (&). The best way to make these characters appear in the document is to enclose them with the {@literal} tag, which restricts the processing of HTML tags and nested Javadoc tags.

The three features added in the Java 1.5 release require special care in document annotations: Generics, enumerations, and annotations. When writing a document for generics or methods, be sure to describe all the type parameters in the document.

When writing a document for an enumeration type, be sure to describe the Changdong, as well as the type, in the document, and any public methods. Note that if the document comment is short, you can put the entire comment on one line:

When writing a document for an annotation type, make sure that all members are described in the document, as well as the type itself.


Starting with the Java 1.5 release, package-level private document annotations should be placed in a file called Package-info.java, rather than in package.html. In addition to package-level private document annotations, Package-info.java can (but is not required) include package declarations and package annotations.

Javadoc the ability to have "inherited" method annotations. If the API element does not have a document comment, Javadoc will search for the most applicable document comment, and the document comment of the interface takes precedence over the document comment for the superclass.

You can also inherit portions of a document's comments from a superclass using the {@inheritDoc} tag. This means that, without saying anything else, the class can reuse the documentation annotations of the interfaces it implements without needing to copy them.

The 7th chapter of the effective Java method

Related Article

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.