Valid Java Note 3

Source: Internet
Author: User

From: http://blog.csdn.net/ilibaba/archive/2009/02/06/3866657.aspx

No. 18 give priority to static member classes

Nested classes only serve its peripheral classes.

Nesting can be divided into four types: static member, non-static member, anonymous, and Department (the last three are called internal classes ), if you want an instance of a nested class to exist independently of its external class, the nested class should be set to a static member class, however, static member classes cannot access non-static peripheral class objects. A non-static internal class has a reference to a peripheral object, so it can access all the members of the peripheral class, including the declared private members.

Application scenarios of anonymous classes:

① Create a function object;

② Creation process objects, such as thread, runnable, and timetask

③ Internal use of static factory methods;

④ In a complex type security Enumeration type (which requires a separate subclass for each instance), it is used in the public static final domain initializer;

Summary: four different Nested classes have their own purposes. If a nested class needs to be visible outside of a single method, or it is too long, it is not suitable to be placed inside a method, so the Member class should be used. If each instance of the member class needs a reference pointing to its peripheral instance, the member class is made non-static; otherwise, it is made static. Assume that a nested class is inside a method. If you only need to create its instance in one place and a pre-existing type already exists, you can describe the features of this class, then it is made into an anonymous class; otherwise it is made into a local class.

 

Note: The following points (No. 19 ~ No. 22) It is an alternative solution to explain the C language structure. Because I am only engaged in Java Development, I skipped this chapter. To ensure the integrity of the notes, I Will repost the article no. 19 to other places ~ Note No. 22.

No. 19 Replace the structure with classes
At the beginning of Java, many c programmers thought that replacing the structure with classes is too complicated and costly. However, if a Java class degrades to contain only one data domain, the structure of such a class is roughly equivalent to that of C language.
For example, the following two program snippets:

  1. Class Point
  2. {
  3. Private float X;
  4. Private float y;
  5. }

In fact, this code is basically no different from the structure of the C language, but this code is probably not well understood by many OO design fans, because it does not reflect the encapsulation superiority, it does not reflect the advantages of object-oriented design. When a domain is modified, you cannot take any auxiliary measures, let's take a look at the OO design code segment that includes private domains and common access methods:

  1. Class Point
  2. {
  3. Private float X;
  4. Private float y;
  5. Public point (float X, float y)
  6. {
  7. This. x = X;
  8. This. Y = y;
  9. }
  10. Public float getx () {retrun X ;}
  11. Public float Gety () {return y ;}
  12. Public void setx (float X) {This. x = x ;}
  13. Public void sety (float y) {This. Y = y ;}
  14. }

On the surface, this code has a lot more lines and functions than the one above, but think about it carefully. Such an OO design seems to be more user-friendly, we can extract and modify the value range without directly having a relationship with the value range. Such code is not only easy to understand, but also safe, I also learned the flexibility of object-oriented programming. Just imagine if a common class exposes its value range, it would be impossible to modify it in future versions, because the customer code of the common classes is everywhere.
It should be noted that if a class is package-level private or a private nested class, it is not inappropriate to directly expose its value range.

 

No. 20 replace union with class hierarchy
When we use C language for development, we often use the concept of joint, such:

  1. Typedef struct {
  2. Double length;
  3. Double width;
  4. } Rectangledimensions_t;

So we don't have the concept of union in Java. What should we use? Yes! Inheritance is also one of the most attractive aspects of Java. It can use better mechanisms to define delayed data types, bruce Eckel's thinking in Java also mentioned a shape-related example multiple times. We can first define an abstract class in a general sense, that is, the superclass we usually refer, each operation defines an abstract method. Its behavior depends on the tag value. If other operations do not depend on the tag value, the operation is changed to the root class (inherited class).
The most important advantage of this is that the class layer provides type security. Secondly, the code is very clear, which is also the advantage of OO design. In addition, it is easy to expand, and can be equally competent even for multiple aspects of work. At last, it can reflect the essential hierarchies between these types, so as to allow more flexibility for Type checks during compilation.

 

No. 21 replaces the enum structure with a class
The Java programming language proposes a type-safe enumeration mode to replace the enum structure. Its basic idea is simple: Define a class to represent a single element of the enumeration type, no public constructor is provided. On the contrary, a public static final class is provided so that every constant in the enumeration type corresponds to a field. For example:

Public class suit {

Private final string name;

PrivateSuit (string name) {This. Name = Name ;}

Public String tostring () {return name ;}

Public static final suit clubs = new suit ("clubs ");

Public static final suit diamonds = new suit ("Diamonds ");

}

The constructor is private and the customer cannot create or extend the class. Therefore, except for suit objects exported through these public static final domains, no other objects exist. Even if this class is not declared as final, there is no way to expand it, because the constructor of the subclass must call the constructor of the superclass.
One disadvantage of the type security Enumeration type is that it takes a certain amount of time and space to load the enumeration class and construct constant objects, this issue will not be considered in reality unless it is on devices with limited resources, such as cell phones and toaster machines.
In short, the type-safe Enumeration type is obviously better than the int type, unless an enumeration type is mainly used as a collection element, or is mainly used in an environment with very limited resources, otherwise, the type security Enumeration type is not a problem. In order to use an enumeration type environment, we should first consider the type security Enumeration type mode.

 

No. 22 replace function pointers with classes and interfaces
As we all know, the biggest difference between the Java language and C is that the former removes pointers, and the first time that Xiaosheng came into contact with Java, he felt very uncomfortable because he suddenly lost the pointer, the essence of C language lies in the use of its pointer, while Java has cut it down, which makes people very depressing, but over time, I gradually realized that applications using classes and interfaces can also provide the same function. We can directly define a class whose method is to execute operations on other methods, if a class only exports such a method, it is actually a pointer to the method. For example:

  1. Class stringlengthcomprator {
  2. Public int compare (string S1, string S2)
  3. {
  4. Return s1.length ()-s2.length ();
  5. }
  6. }

This class exports a method with two strings, which is a specific policy for string comparison. It is stateless and has no domain. Therefore, all instances of this class are functionally equivalent and can save unnecessary object creation costs. However, it is difficult to pass this class directly to users because users cannot pass any other comparison policies. Instead, we can define an interface, that is, when designing a specific policy class, we also need to define a policy interface:

  1. Public interface comparator {
  2. Public int compare (Object O1, object O2 );
  3. }

The specific policy class usually uses Anonymous class declaration.
In Java, in order to implement the pointer mode, we declare an interface to represent this policy, and declare a class that implements this interface for each specific policy, if a specific policy is used only once, an anonymous class is usually used to declare and instantiate this specific policy class,If a policy class is used repeatedly, its class is usually a private static member class.

No. 23 Check the parameter Validity

For non-public methods, we should use the assertion method to check its parameters, instead of using the check statements that are common to everyone. If the development platform we use is jdk1.4 or a more advanced platform, we can use the assert structure; otherwise, we should use a temporary asserted mechanism.

Some parameters are saved before being called during use, so you must check the parameters, otherwise, the program may throw some exceptions that make you confused (such as common NULL pointer exceptions), and you cannot immediately locate the problem. constructor is a reflection of this type, therefore, we usually check the constructor parameter validity very carefully.

In short, when writing a method or constructor, you should consider the restrictions corresponding to its parameters, and write these restrictions into the document, at the beginning of the method body, these restrictions are implemented through the displayed check.

 

Use protective copy when needed

Assume that the class user will do everything possible to break the constraints of the class. Under such circumstances, you must design the program in a protective manner. Class that can still be robust in the face of the customer's bad behavior.
For an immutable class, you can consider using protective copies for the variable parameters of its constructor, such

  1. Public period (date start, date end ){
  2. This. Start = new date (start. gettime ());
  3. This. End = new date (start. gettime ());
  4. // Perform other logics (the protective copy should be performed before other logics, And the validity check is for the Copied object, not the original object)
  5. }

The get method for obtaining parameters should also be returned in clone mode, such:

  1. Public date getstart (){
  2. Return (date) Start. Clone ();
  3. }

Protective copy is performed before the parameter validity check. It checks the Copied object to prevent another thread from changing the original parameter object.

Remember that arrays with a non-zero length are always variable. Try to use an immutable object as an internal component so that you do not have to worry about the protective copy issue.

 

No. 25 prototype of careful design method

1. Carefully select the method name

① It is easy to understand and consistent with other name styles in the same package;

② Select the same name as that recognized by the public;

2. Do not pursue convenient methods too much. Too many methods increase the learning and usage costs of classes. A quick method is considered only when an operation is frequently used.

3. Avoid too long parameter lists. Too long parameters are not easy for users, especially when the parameter types are the same, it is easy to produce the problem of parameter passing errors. Methods To avoid such errors:

① A method can be divided into multiple methods;

② You can create a helper class ). Organizes parameters into a class as parameters for input;

4. For type parameters,The interface is preferred, not the class.If the parameter is map, this method can receive parameters of the hashtable, hashmap, and treemap types.

5. Exercise caution when using function objects

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.