Practical Java, some worth noting

Source: Internet
Author: User
Reading Notes <practical Java> 68 important topics for code improvement

-------------------------------------------------------------------------

I. general technology

Practice 1: parameters are always transmitted by value instead of by reference.

When a method parameter is an object (accurately referred to as an object reference), it is actually a method of passing values, the real parameter first assigns the reference to the form parameter (in this case, the form parameter and the real parameter point to the same object), and then the part in the function changes the object value through the reference operation of the form parameter.

Practice 2: Use final for unchanged date and object references

The keyword final can only prevent variable values from changing.If the variable declared as final is an object
The reference cannot be changed and must always point to the same object. However
The specified object can be changed at will.. (Note the meaning of Shenma)

Practice 3: By default, all non-static functions can be overwritten.

When designing classes, you can use final as a tool to improve performance. In the statement
Before a class is final, consider the implied meaning and limitations of this pair of classes. You must also carefully consider the potential impact of the final function or non-final function on performance.

Practice 4: carefully select between arrays (array) and Vectors

Arrays can contain both primitive types (basic type) and object references. Each element is assigned a default value based on its own type. If the array element is object references, java does not call the default constructor, but sets its initial value to null.

When more elements are added to a vector to exceed its capacity, the volume of the element increases dynamically, which is significantly different from array. The vector is actually implemented in array. The vector can only accommodate object references and cannot contain basic types (primitive types ).

Practice 5: polymorphism is superior to instanceof

Do not use instanceof as the judgment condition to implement an if else function. polymorphism should be used. For example, do not implement only one computing function (instanceof is used in the calculation to determine whether the object is a manager or an ordinary employee, and then determine different calculation methods ), multiple computing methods should be implemented to achieve polymorphism with different parameter types.

Practice 6: Use instanceof only when necessary

Problems encountered during the downward Transformation: For types that are not in the same class architecture, the forced transformation will prompt errors during the compilation period, however, a forced type conversion between classes in the same class architecture throws an exception during running. In a collection like a vector, the element types retrieved from the element are all object types. The downward transformation will not prompt errors in the compiler, No matter why the type is converted, so you need to use instanceof to check its actual type, and then in the transformation, this is often better than catch to catch exceptions.

Practice 7: Set object references to null

Memory consumption

--------------------------------------------------------------------------

2. Equality between objects

Practice 8: differentiate between a reference type and a primitive type

All Java objects are accessed through object references (references,The collection stores object references, not the object itself..

Practice 9: differentiate = and equas ()

Operator = only test equality in [Shallow. Check whether the left side of the operator is the same as the right side.
Example: If the two references do not point to the same object, even if the object value is equal, = is not equal because it is only a test in the shallow layer.

Use = to test whether the two basic types are identical (identical), or test whether the two object references point to the same object. Use equals () to compare whether the two objects are consistent (Same) -- the benchmark is its attribute (attributes. Note: this refers to the object's real value content, that is, the data value range, field ).

Practice 10: do not rely on the default Implementation of equals ()

1) To compare whether objects are equal, its class has the responsibility to provide a correct equals ().
2) before [Taking equals ()] for granted, check and ensure that the class you are using is true.
Implements equals ().
3) if the class you are using does not implement equals (), check the default value of Java. Lang. object.
Whether the function is competent.
4) if not competent, it should be written in a Wrapper class or subclass.
Write your own equals ().

Practice 11: Be careful when implementing equals ()

Which classes objects do you want to compare with your class objects? Are you only planning to compare objects of the same class? Or do you allow the derived class object to be compared with its base class object? In general, equals () is implemented to ensure that objects with the same value are equal in different memory spaces. However, according to the definition of equals (), you can even make the objects of different class types equal, although this makes no sense.

Practice 12: getclass () is preferred when equals () is implemented ()

The best way to implement equals () is to use getclass (). The latter ensures that only
Objects generated by the same class have the opportunity to be considered equal.

Practice 13: Call super. Equals () to arouse the behavior of base class

When you write equals () for a derived class, you must check all base classes other than Java. Lang. Object To see if they all implement equals (). If so, you must call Super. Equals (). Then, compare the newly added attributes.

Practice 14: exercise caution when using instanceof in the equals () function

To achieve equality between the derived class and the base class object.

Practice 15: certain rules must be followed when equals () is implemented.

Whether you choose to use getclass () or instanceof to implement equals (), the following rules apply
All equals () functions:
1) if the two objects of a class occupy different memory space, they can be considered
", You must provide an equals () for this class ().
2) check whether it is equal to this (see practice 12 ).
3) Compare the related attributes (value range, fields) in this class to determine whether the two objects are equal
(See practice 12 ).
4) if any base class other than Java. Lang. Object implements equals (),
Super. Equals () should be called (see practice 13 ).

When you choose between getclass () and instanceof in the equals () function, consider
Problem:
1) if only the objects generated by the same class are considered equal
Getclass () (see practice 12 ).
2) only when you have to "compare the derived classes object with the base classes object"
(See practice 14), and you should understand that
Possible problems and complexity.
3) If you use instanseof and both the derived class and base class implement equals (),
You must know that this comparison does not show the so-called symmetric equality
Integrity ).

--------------------------------------------------------------------------

Iii. Exception Handling

Practice 16: Understand the exception Control Flow Mechanism

Practice 17: Never ignore an exception (never ignore an exception)

What can you do when a Java program has an exception?
1. Capture and process it to prevent it from further propagation (propagate ).
2. Capture and throw it again, so that it will be propagated to the caller.
3. capture it and then throw a new exception to the caller.
4. If this exception is not caught, let it be transmitted to the caller.

Practice 18: never hide exceptions (never hide an exception)

Try, catch, and finally segments can be nested with each other (nested ). In addition, although multiple exceptions are thrown from them, only one exception can be propagated to the outside world. Remember, the last thrown exception is the only one accepted by the caller. Other exceptions are hidden and lost. If the caller needs to know the initial cause of failure, no exceptions can be concealed in the program. You can create a vector storage exception, save all generated exceptions, and return them to the terminal.

PRACTICE 19: Check the shortcomings of the throws clause

When a throws exception is added to a method, unless it is handled by itself in the method body, each method that calls it will add catch to catch exceptions, which has a great impact on the system, do not add exception handling at the end of the development cycle. Please design your error handling policy at the beginning. When you still encounter this situation after careful planning, you will understand that the throws clause is a useful language feature, but if you are not careful enough, it can be a headache.

Practice 20: carefully and comprehensively understand the throws clause

1) The intention of the throws clause is to notify the function caller of possible exceptions.

2) When the exception types A, B, and C in the method body are inherited, the compiler will pass even if you only throws the top-level exceptions, but this is generally not recommended!

When you provide the throws clause, the fields are complete. Although the compiler does not require this, listing all the exceptions that a function may throw is a good programming habit. This is advantageous for capturing and handling exceptions by calling its methods.

3) The exception thrown by the overwriting function, or the corresponding function of superclass has the same type, or the specializations of these types ).
This means that if your overwriting object (A superclass function) does not throw any exception, but you
Because code is added to the overwrite function, you must capture exceptions in the new function and process them locally. You cannot spread exceptions caused by new functions to the outside world !!!!!

Practice 21: Use finally to avoid resource leaks)

Disable socket and file stream

Practice 22: Do not return data from the try Partition

When the code in the try segment leaves the try segment, it will enter the finally segment, which may cause the code to leave the try segment:
1) throw an exception
2) The try section ends normally.
3) The return, break, or continue statement is executed in the try section, causing execution

Note that the return statement cannot prevent finally execution. To avoid troubles, try not to use return in try. This return value is often not returned to the method, but is blocked by finally.

Practice 23: place the try/catch section outside the loop

Efficiency-based considerations

Practice 24: Do not use exceptions for Process Control

Exception control is only used for exception handling. Do not use exceptions to control the execution process of programs. The meaning is vague and difficult to maintain.

Practice 25: Do not use exceptions whenever an error occurs.

Use traditional error handling and exceptions together to build efficient code

Practice 26: throw an exception in Constructors

The constructor has no return value. If an exception occurs in the constructor, the Internal Failure Cause of the constructor can be obtained.

Practice 27: Restore the object to a valid state before throwing an exception

-------------------------------------------------------------------------

Iv. Efficiency and Optimization Technology

Practice 28: Focus on design, data structures, and Algorithms

Practice 29; do not rely on compile-time optimization technology

Practice 30: Understand the runtime code optimization technology

Practice 31: to join strings, stringbuffer is better than string

Because the string class is immutable, when string is used for string combination, it is actually converted to stringbuffer and finally converted to string.

Using stringbuffer can reduce the number of object creation times and improve efficiency.

Practice 32: Minimize the object creation cost (creation cost)

1. allocate memory from heap to store all instance variables and the object together with its superclasses
Session data (implementation-specific data ). [Implement exclusive data] refer to "class and Method Data"
Needle.
2. The instance variable of the object is initialized to its default value.
3. Call the constructor of the most derived class (deepest derived class ). The first thing the constructor does is to call
Superclass constructor. This program continues until the java.1ang. object constructor is called. Remember that java.1ang. object is the base class of all Java objects.
4. Before executing the constructor ontology, initializers and initialization blocks of all instance variables are executed first before executing the constructor ontology. Therefore, the base class constructor is first executed, and the most derived class constructor is finally executed. This allows any class constructor to use any of its superclasses instance variables with confidence.

Since creating an object involves so many things, creating a lightweight object is much faster than creating a heavyweight Object. Lightweight objects do not have long inheritance chain or contain many other objects. The opposite is true for heavy objects. If an object contains multiple lightweight objects, it can also be considered as a heavy object.

Practice 33: guard against unused objects (unused objects)

Create an object in the appropriate place. Related to coding skills

Practice 34: Minimize Synchronization

In general, the synchronized version of vector is about 5 ~ slower than its non-synchronized version ~ Six times.

Practice 35: Use stack variables whenever possible

Practice 36: use static, final, and private functions to facilitate inlining

Inlined functions can improve performance only when they are called multiple times. This is because when a function is inline, the extra overhead of function calling is no longer required. Therefore, the more calls a function, the more savings it will save.

Practice 37: Initialize the instance variable once.

Practice 38: use the basic type (primitive types) to make the code faster and smaller

Practice 39: Do not use enumeration or ite Rato R to traverse the Vector

The fastest cycle is used.

Practice 40: Use System. arraycopy () to copy Arrays

It is faster than self-writing loop copy. It is a local function.

Practice 41: Prioritize array before vector and arraylist

After learning about the performance of vector and arraylist, consider using array when you are faced with performance-critical program tasks. If you need the vector function but do not need its synchronization feature (synchronization), use arraylist. Vector is used only when you need both the vector function and the inherent synchronization feature.

Do not use vector or arraylist without any choice just because there is a certain amount of data on hand that needs to be stored. If you cannot determine the number of elements to be saved, you can create an array that is sufficient to save the largest amount of data. This may waste a lot of memory, but the performance gains may exceed the memory cost. With detailed performance evaluation and detailed analysis of the system, you can make the right choice.

Practice 42: Reuse objects as much as possible

Programming Skills

Practice 43: Use a slow evaluation (latency evaluation, lazy evaluation)

It has nothing to do with language. In terms of strategy, it delays the execution of jobs that may not be used, and it is necessary to do so.

Practice 44: manually optimize code

Practice 45: compile as local code

Practice 46: In the face of Instance functions, synchronized locks objects rather than functions.
(Methods) or code)

The key word synchronized can be used as a modifier or a statement in a function. Due to its double usage, some people cannot find out its true intention. It is often described as mutex or criticalsection ). This makes many programmers mistakenly think that because the code is protected by the keyword synchronized, only one thread can access it at a time.

For the instance function, the keyword synchronized does not actually lock the function or code. What it locks is
Object (for the impact of synchronized on Statics, see practice 47 ). Remember, each object has only one lock associated with it.

When synchronized is treated as a function modifier, the lock obtained by synchronized is handed over to the function caller.
(An object ). If synchronized is used for object reference, the acquired lock will be handed over to the object referred to by this reference.

There are also some multithreading related topics later ~

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.