151 recommendations for improving Java programs-enumerations and annotations

Source: Internet
Author: User

83. In project development, it is recommended to use enumerations to define constants instead of interface constants or class constants

Eg:enum{spring,summer,autumn,winter;}

Enumeration defines the advantages of constants relative to the constant classes used frequently and static constants:

1) enumeration constants are simpler: enumeration constants do not need to define an enumeration value,int spring=1; An enumeration represents an enumerated item, and the literal meaning is different, and the other constant must be a type;

2) enumeration constants belong to steady-state

3) enumerations have built-in methods, such as values: Get a collection of all values that can be used for traversal , ordinal: getting sorted values,compareTo comparison methods, etc.;

4) enumeration can be custom method: Enumeration constants can not only define static methods, but also can define non-static methods, but also can fundamentally eliminate the constant class is instantiated

Disadvantage: Enum types cannot have inheritance, and after the enumeration constants are defined, they cannot be extended unless refactoring is modified.

Enumeration types of traversal:

For (Season s:season.values ()) {System.out.println (s);}

84. Using constructors to help describe enumeration items

Enum season{//can add descriptions and other definitions for enumeration items by constructing the method spring ("Spring", "springtime"), Summer ("Summer", "Sun High"), Autumn ("Autumn", "crisp"), Winter ("Winter", "Snow"); Private string desc;//describes the private string other;//other//Add the above description and definition must add the constructor method shown below season (String desc,string other) {this.desc= Desc;this.other=other;} Gets the description public String GetDesc () {return desc;} Get additional public String Getother () {return to other;}}

It is recommended to define a description for each enumeration item in the enumeration definition, which is more friendly and concise than adding annotations in interface constants or class constants

85. Beware of NULL exceptions caused by switch

public static void Testswitch (Season s) {switch (s) {case Spring:System.out.println ("Spring"); Break;case Summer: System.out.println ("Summer"); Break;default:throw new Assertionerror ();}}

The above code, if done test: Testswitch (NULL); will find in switch (s) throws a null pointer exception, because Java can judge. Switch type is Short , byte , int , Char type, then why does the enumeration type compile through, because the compiler is judged by the sort value of the enumeration type: Switch (s.ordinal ()) {Case Season.Spring.ordinal ()},if theNULLvalue, then noordinalmethod, the null pointer exception is definitely thrown, so the workaround is to include in the method whether theNULLJudging

86. Add assertionerror error in switch 's default code block

Default:throw new Assertionerror ();

87. must be verified before using valueOf

The valueOf method is provided in the enumeration class to find an enumerated item with a string value equal to the parameter, returning data of an enumerated type

Test the valueof method because season does not exist springtime will throw//illegalargumentexception exception information public static void Testvalueof () {list< String> list=arrays.aslist ("Spring", "springtime"); for (String s:list) {Season season=season.valueof (s); if (Season !=null) {System.out.println (s);} Else{system.out.println ("The enum type does not exist");}}}

Solution:

1. Add try....catch method to capture in season.valueof method

2.add a method to determine the existence of the enumeration class, for example : Contains method , if The string information exists, then The ValueOf is converted to the appropriate enumeration type, does not exist, and does not convert

88. It is easier to implement the factory method mode with enumeration

89. The number of enumerated items is limited to within five

The enumeration collection provided by Java, because the number of instances of enumerated types is fixed and limited, is relatively more efficient than other set and Map :

Enumset: Its element must be an enumerated item of an enumeration

Enummap:key value must be an enumeration item of an enumeration

Enumset when storing enumeration type data, Create an regularenumset Instance object that is greater than 64 when the enumeration quantity is less than or equal to creates a junmboenumset Instance Object when the

public static void Testenumset () {enumset<season> Set1=enumset.allof (Season.class); Enumset<season> Set2=enumset.allof (Season.class);//The enumeration type Season is less than or equal to 64 elements, the result is: class Java.util.RegularEnumSetSystem.out.println (Set1.getclass ());//More than 64 elements in the enumeration type season, the result is: class Java.util.JumboEnumSetSystem.out.println (Set2.getclass ());}

Because the implementation classes provided by Enumset are basic numeric type operations, their performance is certainly much better than other Set types, especially When the number is less than .

90. Careful annotation inheritance

Meta Annotations:@Inherited, indicating whether an annotation can be automatically inherited

91. Enumeration and annotations combined with greater power

Define role level, user, admin, Super Admin enum Roleidentify{user,admin,superadmin;} Define access Rights note class @retention (retentionpolicy.runtime)//meta annotations, which represent the retention level @target (elementtype.type)//meta annotations of the annotation, Indicates where the note can be labeled @inherited//a meta-annotation, indicating that the annotation is automatically inherited @interface access{//defined access level, which defaults to admin roleidentify levels () default Roleidentify.admin;} Use your own defined annotations @access (Level=roleidentify.user) class Testannatation{}public class Annatationtest {public static void main (string[] args) {//Test testannatation test=new testannatation (); Access Access=test.getclass (). Getannotation (Access.class); System.out.println (Access.level ());//Print out user}}

92, the main @Override Different versions of the difference

The following code:

Interface myinterface{public void DoSomething ();} Class Myimpl implements myinterface{@Overridepublic void DoSomething () {}public void Dotest (list<string> strlist) {}}

The above code compiles on the jdk1.6 version without any problems, but compiling the above code on the jdk1.5 version will make an error:themethod dosomething of type Myimpl Override a superclass ...

jdk1.5 @Override is strict adherence to the definition of overwrite: The subclass method must have the same method name, input parameter, output parameter as the parent class method. ( allow subclasses to shrink " , access rights ( allow subclasses to expand " , the parent class must be a class and cannot be an interface, otherwise it cannot be a overwrite.

Therefore, if the jdk1.6 version of the project is ported to the jdk1.5 version, you need to remove the @Override annotations that implement the interface method .

151 recommendations for improving Java programs-enumerations and annotations

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.