Writing high-quality code: 151 suggestions for improving Java programs (Chapter 1: enumeration and annotation ___ suggestion 83 ~ 87), java151

Source: Internet
Author: User

Writing high-quality code: 151 suggestions for improving Java programs (Chapter 1: enumeration and annotation ___ suggestion 83 ~ 87), java151

Enumeration and annotation are introduced in Java1.5. Although they are the starting points, their functions cannot be underestimated. Enumeration changes the declaration method of constants, and annotations are coupled with data and code.

Recommendation 83: enumeration is recommended to define constants.

Constant declaration is indispensable for every project. Before Java, we only have two methods to declare: Class constants and interface constants. If Java is used in a project, this is basically the definition. However, it has been improved after version 1.5, that is, a constant declaration method is added: declare Constants by enumeration. See the following code:

enum Season {        Spring, Summer, Autumn, Winter;    }

This is a simple enumeration constant name, clear and simple. By the way, JLS (Java Language Specification, Java Language Specification) advocates that all enumeration items are capitalized and separated by underscores (_). This is also a constant (of course, the naming method for similar class names is also friendly ).

So what are the advantages of enumerated constants compared with the class constants and static constants we often use? The advantages of enumeration are as follows:

1. Simple enumerated constants: simple and simple. Let's compare the definitions and usage of the two. First, write the Season enumeration as an interface constant. The Code is as follows:

1 interface Season {2     int SPRING = 0;3     int SUMMER = 1;4     int AUTUMN = 2;5     int WINTER = 3;6 }

The four seasons of spring, summer, autumn, and winter are defined here. The type is int, which is the same as the sorting value of the Season enumeration. First, compare the definitions of the two. The enumerated constants only need to define each enumeration item, and do not need to define enumeration values. The interface constants (or class constants) must define values; otherwise, compilation fails, it must be defined even if we do not need to pay attention to the value. Secondly, although the two are referenced in the same way (both are "class names. attribute ", such as Season. SPRING), but enumeration represents an enumeration item, literally meaning SPRING, and the interface constant is indeed an int type, although its literal meaning is SPRING, however, in the operation, we must pay attention to its int value.

2. Enumeration constants belong to the steady state type.

For example, we need to describe what it looks like in spring, summer, autumn, and winter, and use the interface constant to write it like this.

1 public void describe (int s) {2 // s variable cannot go beyond the boundary. Check Condition 3 if (s> = 0 & s <4) {4 switch (s) {5 case Season. SPRING: 6 System. out. println ("this is spring"); 7 break; 8 case Season. SUMMER: 9 System. out. println ("this is summer"); 10 break; 11 ...... 12} 13} 14}

It is very simple. First, use the switch statement to determine which is a constant and then output it. However, the problem is that we have to check the input value to determine whether the input is out of bounds. If the constant is very large, it is very troublesome to verify the input, but this is an unavoidable process, especially if our verification conditions are not strict, although the compilation can still pass, the runtime will have unpredictable consequences.

Let's take a look at whether enumerative constants can avoid verification issues. The Code is as follows:

 1 public void describe(Season s){ 2         switch(s){ 3         case Spring: 4             System.out.println("this is "+Season.Spring); 5             break; 6         case Summer: 7             System.out.println("this is summer"+Season.Summer); 8             break; 9                   ......10         }11     }12     

No verification is required. It is already limited to Season enumeration. Therefore, it can only be four instances of the Season class, that is, four enumeration items in spring, summer, and autumn. Do you want to enter one int type or another type? No door! This is the most important part of enumeration: specifying types during compilation does not allow cross-border operations.

3. enumeration has built-in Methods

There is a simple question: how can we implement it if we want to list all seasonal constants? Interface constants or class constants can be implemented through reflection. This is true, but although it can be implemented, it will be very complicated. You can write a reflection class to implement this function by yourself (of course, print the output constants one by one ). The Code is as follows:

1 public void query() {2         for (Season s : Season.values()) {3             System.out.println(s);4         }5     }

Use the values method to obtain all enumeration items and print them out. This is simple, thanks to the built-in enumeration method, every enumeration is java. lang. A subclass of Enum. This base class provides ordinal methods for obtaining sorting values and compareTo comparison methods, which greatly simplifies constant access.

4. Enumeration customizable Methods

This does not seem to be an advantage of enumeration. Class constants can also have their own methods, but the key is that enumeration constants can not only define static methods, but also non-static methods, in addition, it can fundamentally prevent constant classes from being instantiated. For example, to obtain the most comfortable season in constant definition, the code for using constant enumeration is as follows:

1 enum Season {2         Spring, Summer, Autumn, Winter;3         public static Season getComfortableSeason(){4             return Spring;5         }6     }

We know that each enumeration item is an instance of this enumeration. For our example, Spring is actually an instance of Season, and Summer is also an instance, the static method defined in enumeration can be referenced in the class (that is, enumeration Season), or in the instance (that is, enumeration items Spring, Summer, Autumn, Winter) see the following code:

public static void main(String[] args) {        System.out.println("The most comfortable season is "+Season.getComfortableSeason());    }

So how can we implement it using class constants? The Code is as follows:

1 class Season {2     public final static int SPRING = 0;3     public final static int SUMMER = 1;4     public final static int AUTUMN = 2;5     public final static int WINTER = 3;6     public static  int getComfortableSeason(){7         return SPRING;8     }9 }

How can we print out The sentence "The most comfortable season is Spring? There is no other way except to use the switch and if statements.

Although enumeration is easier to use than interface constants and class constants in many aspects, it is inferior to interface constants and class constants, that is, inheritance. enumeration types cannot be inherited, that is to say, after an enumerated constant is defined, it cannot be extended unless it is modified and reconstructed, and the interface constants and class constants can be extended through inheritance. However, constants are usually defined when a project is built, and there are few scenarios where business logic can be implemented only through expansion.

Note: In the project, we recommend that you use enumeration constants instead of interface constants or class constants.

Recommendation 84: Use constructors to help describe enumeration items

Generally, the enumerated items that we often use have only one attribute, that is, the order number. The default value is from 0, 1, 2 ......, we are familiar with this, but in addition to the order number, enumeration also has one or more attributes: enumeration description. Its meaning is through enumeration constructor, declares the attributes and behaviors required for each enumeration item (that is, the enumeration instance). This is a description or supplement to the enumeration item to make the description more clear and accurate. For example, there is a piece of code:

1 public enum Season {2 Spring ("Spring"), Summer ("Summer"), Autumn ("Autumn"), Winter ("Winter"); 3 private String desc; 4 5 Season (String _ desc) {6 desc = _ desc; 7} 8 // obtain enumeration description 9 public String getDesc () {10 return desc; 11} 12}

The enumeration option is in English and the description is Chinese. This design makes the meaning of the expression more accurate, so that multiple authors can reference the constant together. If you do not consider the use of the description (that is, access the getDesc method), it is similar to the description defined in the following interface:

Interface Season {// SPRING int SPRING = 0; // SUMMER int SUMMER = 1 ;//......}

Comparing the two sections of code, it is easy to see that using enumeration descriptions is a good solution, which is very simple and clear. Because it is a Description, we can give more meaning during development. For example, we can declare the business value, define the options, and add attributes by enumerative constructors, see the following code:

1 enum Role {2 Admin ("Administrator", new LifeTime (), new Scope (), User ("common User", new LifeTime (), new Scope ()); 3 private String name; 4 private LifeTime lifeTime; 5 private Scope scope Scope; 6/* setter and getter Methods */7 8 Role (String _ name, LifeTime _ lifeTime, scope _ scope) {9 name = _ name; 10 lifeTime = _ lifeTime; 11 scope = _ scope; 12} 13 14} 15 16 class LifeTime {17} 18 class Scope {19}

This is a role definition class that describes two roles: Administrator and common users. It also describes these two roles through constructors:

  • Name: indicates the Chinese name of the role.
  • LifeTime: indicates the role's lifecycle, that is, how long the role expires.
  • Scope: indicates the permission range of the role.

As you can see, such a description allows developers to have a three-dimensional multi-dimensional awareness of the Admin and User constants, including names, periods, and ranges, in addition, you can easily obtain such attributes in the program. Therefore, we recommend that you define descriptions for each enumeration item in the enumeration definition, especially in large-scale project development, A large number of constant definitions use enumeration item descriptions, which are much more friendly and concise than adding annotations to interface constants or class constants.

Recommendation 85: Be careful with the NULL pointer exception caused by switch.

When constants are defined using enumeration. A large number of switch statements are used to explain the behavior of each enumeration item. For example, the following method is used:

1 public static void doSports (Season season) {2 switch (season) {3 case Spring: 4 System. out. println ("Spring kite"); 5 break; 6 case Summer: 7 System. out. println ("Summer swimming"); 8 break; 9 case Autumn: 10 System. out. println ("Autumn is the harvest season"); 11 break; 12 case Winter: 13 System. out. println ("Winter skating"); 14 break; 15 default: 16 System. out. println ("output error"); 17 break; 18} 19}

The above code passes in a Season Type enumeration, and then uses the switch for matching, the purpose is to output the activities of each Season, the problem is that this code is correct:

Let's first take a look at how it is called, because the Season type is passed in, that is, an instance object. Of course, it is allowed to be empty, let's pass a null value to see if the code is correct, as shown below:

public static void main(String[] args) {        doSports(null);    }

It seems that "output error" will be printed, because the switch does not match the specified value, so the defaut code block will be printed, right? No. The running result is as follows:

Exception in thread "main" java.lang.NullPointerException    at com.book.study85.Client85.doSports(Client85.java:8)    at com.book.study85.Client85.main(Client85.java:28)

It turns out that there is a null pointer exception, that is, the switch line. How can there be a null pointer? This is related to enumeration and switch features, which often occurs during development. We know that currently, switch statements in Java can only judge the byte, short, char, and int types (the String type is allowed in JDK 7), which is a limitation of the Java compiler. The question is, why can the enumeration type follow the switch?

During compilation, the compiler determines that the parameter followed by the switch statement is of the enumeration type, and then continues Matching Based on the enumerated sorting value, that is, or the above Code is the same as the following code:

1 public static void doSports (Season season) {2 switch (season. ordinal () {3 case season. spring. ordinal (): 4 System. out. println ("Spring kite"); 5 break; 6 case season. summer. ordinal (): 7 System. out. println ("Summer swimming"); 8 break; 9 //...... 10} 11}

The switch statement calculates the sort value of the season variable first, and then compares it with each sort value of the enumerated constant. In our example, season is null, the ordinal () method cannot be executed, so a null pointer exception is reported. The problem is clear and the solution is simple. In the doSports method, you can determine whether the input parameter is null.

86: add the AssertionError error to the default code block of the switch.

Switch is followed by Enumeration type, and case is followed by listing all enumeration items. This is a mainstream way to use enumeration, so the default statement does not seem to have any effect, and the program has already listed all possible options, the defaut statement is definitely not executed. It seems redundant! Wrong. This default is still very useful. The log level we define indicates that this is a typical enumerated constant, as shown below:

enum LogLevel{        DEBUG,INFO,WARN,ERROR    }

Generally, a switch statement is used to determine the log level set by the user, and different levels of Log Code are output. The Code is as follows:

 1 switch(LogLevel) 2  3     { 4     case:DEBUG: 5         //..... 6     case:INFO: 7         //...... 8     case:WARN: 9         //......10     case:ERROR:11         //......12     }

Because all the enumerated items are listed and there is no other value, the default code is not needed, however, the problem is that there is no forced constraint between the switch code and enumeration. That is to say, the two are connected in semantics and there is no forced constraint. For example, the enumeration item of LogLevel has changed, an enumeration item FATAL is added. If we do not modify the switch statement at this time, the compilation will not fail, but an unexpected error will occur during the runtime: the FATAL type logs are not output.

To avoid such errors, we recommend that you directly throw an AssertionError after default, which means "don't come here, there will be problems as soon as you get here ", this ensures that when an enumeration item is added, if other code is not modified, an error will immediately occur during the runtime, which makes it easy to locate the error and facilitate immediate elimination.

Of course, there are other ways to solve this problem, such as modifying the IDE tool. Take Eclipse as an example, you can set "Enum type constant not covered on 'switch'" in Java --> Compiler ---> Errors/Warnings to the Error level. If you do not judge all enumeration items, the compilation fails.

87: verification is required before valueOf is used.

We know that each enumeration item is java. lang. the subclass of Enum can access the methods provided by the Enum class, such as hashCode, name, and valueOf. the valueOf method converts a String type name to an enumeration item, that is, find the enumerated items with the same nominal value as the parameter in the enumerated items. Although this method is simple, JDK does not provide a simple solution for developers. Let's look at the Code:

1 public static void main (String [] args) {2 // note that the summer is a lowercase 3 List <String> params = Arrays. asList ("Spring", "summer"); 4 for (String name: params) {5 // search for enumeration items with the same nominal value and name, in this example, Season is used to enumerate Season 6 Season s = Season. valueOf (name); 7 if (null! = S) {8 // when an enumeration item exists 9 System. out. println (s); 10} else {11 // This enumeration item does not exist 12 System. out. println ("No enumerated items"); 13} 14} 15}

It seems that there is nothing wrong with this program. Considering that conversion from String to Enumeration type may fail, for example, if no matching value is found, the returned value of ValueOf should be null, so it follows if... else determines the output. Let's take a look at the running results

SpringException in thread "main" java.lang.IllegalArgumentException: No enum constant com.book.study01.Season.summer    at java.lang.Enum.valueOf(Unknown Source)    at com.book.study01.Season.valueOf(Season.java:1)    at com.book.study85.Client85.main(Client85.java:14)

An invalid parameter exception is reported, which means that our summer (note that s is in lower case) cannot be converted to the Season enumeration. If the conversion fails, do not throw the IllegalArgumentException exception, once this exception is thrown, subsequent code will not be executed, which is inconsistent with our habits. For example, if we look for an element from the List, no error will be reported even if it does not exist, at most, the indexOf method returns-1. The source code of the valueOf method is as follows:

1 public static <T extends Enum <T> T valueOf (Class <T> enumType, String name) {2 // reflection, search for 3 T result = enumType from the constant list. enumConstantDirectory (). get (name); 4 if (result! = Null) 5 return result; 6 if (name = null) 7 throw new NullPointerException ("Name is null "); 8 // finally, an invalid parameter exception is thrown. 9 throw new IllegalArgumentException ("No enum constant" + enumType. getCanonicalName () + ". "+ name); 10}

The valueOf method is first searched from the constant declaration of enumeration class through reflection. If it is found, it is returned directly. If it cannot be found, an invalid parameter exception is thrown. ValueOf is designed to protect the enumeration security in the encoding so that it does not generate an empty enumeration object, which simplifies the enumeration operation, but introduces an unavoidable IllegalArgumentException exception.

Do you think the source code of the valueOf method here is incorrect? We need to enter two parameters here, while our Season. valueOf only transmits one String type parameter. Is that true? Yes, because the valueOf (String name) method is invisible and is a built-in JVM method. We only need to read the public valueOf method to understand its running principle.

The problem is clear. There are two ways to solve this problem:

(1) Use try... catch to catch exceptions.

Here is the most direct and simplest way. If IllegalArgumentException is generated, it can be confirmed that there is no enumeration item with the same name. The Code is as follows:

Try {Season s = Season. valueOf (name); // if this enumeration item exists, System. out. println (s);} catch (Exception e) {e. printStackTrace (); System. out. println ("No enumerated items ");}

(2) extended enumeration class: because the methods defined by the Enum class are basically of the final type, we can learn String and List, add a contains method to determine whether the specified enumerated items are included, and then continue the conversion. The Code is as follows.

1 enum Season {2 Spring, Summer, Autumn, Winter; 3 // whether it contains the specified enumeration Item 4 public static boolean contains (String name) {5 // All enumerated values 6 Season [] season = values (); 7 for (Season s: season) {8 if (s. name (). equals (name) {9 return true; 10} 11} 12 return false; 13} 14}

After the static method contains is available for the Season enumeration, you can determine whether the specified enumeration name is included before valueOf. If it contains, you can convert it to enumeration through valueOf, if not included, the conversion is not performed.

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.