Effective Java Third edition--27. Eliminate non-check warnings

Source: Internet
Author: User

Tips
"Effective Java, third Edition" an English version has been published, the second edition of this book presumably many people have read, known as one of the four major Java books, but the second edition of 2009 published, to now nearly 8 years, but with Java 6, 7, 8, and even 9 of the release, the Java language has undergone profound changes.
In the first time here translated into Chinese version. For everyone to learn to share.

27. Eliminate non-inspection warnings

When you use generic programming, you see a number of compiler warnings: Unchecked cast warnings, unchecked method invocation warnings, unchecked parameterized variable length type warnings, and unchecked conversion warnings. The more experience you get with generics, the less warnings you get, but don't expect the newly written code to compile cleanly.

Many unchecked warnings are easy to eliminate. For example, suppose you accidentally wrote the following statement:

Set<Lark> exaltation = new HashSet();

The compiler will remind you what you did wrong:

Venery.java:4: warning: [unchecked] unchecked conversion        Set<Lark> exaltation = new HashSet();                               ^  required: Set<Lark>  found:    HashSet

You can then make an indication correction to let the warning disappear. Note that you do not actually need to specify a type parameter, just to show that it appears with the diamond operator ("<>") introduced in Java 7. The compiler then infers the correct actual type parameters (in this case, Lark):

Set<Lark> exaltation = new HashSet<>();

But some warnings are more difficult to eliminate. This chapter is filled with examples of such warnings. When you receive a warning that you need to think further, persevere! as much as possible, eliminate every unchecked warning . If you eliminate all warnings, you can rest assured that your code is type-safe, which is a very good thing. This means that at run time you will not get a classcastexception exception and add confidence that your program will act according to your intentions.

If you cannot dismiss the warning, but you can prove that the code that caused the warning is type-safe, then (and only then) use @SuppressWarnings(“unchecked”) annotations to suppress the warning . If you suppress the warning without first proving that the code is type safe, then you give yourself a false sense of security. The code may compile without warning, but it can still throw a classcastexception exception at run time. However, if you ignore the unchecked warnings that you think are safe (rather than suppressing them), you will not notice that this is a real problem when a new warning appears. The new warning will be drowned in all error warnings.

SuppressWarningsAnnotations can be used for any declaration, from a single local variable declaration to an entire class. Always use SuppressWarnings annotations within the smallest possible range . Usually this is a variable declaration or a very short method or constructor method. Never use annotations on the entire class SuppressWarnings . Doing so may obscure important warnings.

If you find yourself using annotations on methods or construction methods that have more than one line in length SuppressWarnings , you can move them to the local variable declaration. You may need to declare a new local variable, but it is worthwhile. For example, consider this toarray method from ArrayList:

public <T> T[] toArray(T[] a) {    if (a.length < size)       return (T[]) Arrays.copyOf(elements, size, a.getClass());    System.arraycopy(elements, 0, a, 0, size);    if (a.length > size)       a[size] = null;    return a;}如果编译ArrayList类,则该方法会生成此警告:ArrayList.java:305: warning: [unchecked] unchecked cast       return (T[]) Arrays.copyOf(elements, size, a.getClass());                                 ^  required: T[]  found:    Object[]

It is illegal to set an annotation in a return statement SuppressWarnings because it is not a declaration [jls,9.7]. You might try to put the comment on the whole method, but don't do it. Instead, declare a local variable to hold the return value and label its declaration as follows:

// Adding local variable to reduce scope of @SuppressWarningspublic <T> T[] toArray(T[] a) {    if (a.length < size) {        // This cast is correct because the array we're creating        // is of the same type as the one passed in, which is T[].        @SuppressWarnings("unchecked") T[] result =            (T[]) Arrays.copyOf(elements, size, a.getClass());        return result;    }    System.arraycopy(elements, 0, a, 0, size);    if (a.length > size)        a[size] = null;    return a;}

The resulting method compiles cleanly and minimizes the range of unchecked warnings that are suppressed.

whenever @SuppressWarnings(“unchecked”) you use annotations, add a comment explaining why it is safe . This will help others understand the code, and more importantly, it will reduce the likelihood of someone modifying the code, making the calculation unsafe. If you find it difficult to write such comments, keep thinking. After all, you may end up with an unchecked operation that is unsafe.

In short, unchecked warnings are important. Don't neglect them. Each unchecked warning represents the likelihood of a classcastexception exception at run time. Do whatever you can to eliminate these warnings. If you cannot eliminate an unchecked warning, and you can prove that the code that raised the warning is of a security type, you can use annotations to suppress the warning in the smallest possible scope @SuppressWarnings(“unchecked”) . Record the reasons you decide to suppress this warning in comments.

Effective Java version--27. Remove non-check warnings

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.