Effective Java Reading notes--Methods

Source: Internet
Author: User

38: Check the validity of the parameters

Whenever you write a method or constructor, you should consider the limitations of its parameters, check the parameters at the beginning of the method, and write these restrictions to the document.

Attention:

    1. For public methods, you should use the @throws tag to indicate in your document the exception that would be thrown when a parameter value restriction is violated
    2. For non-public methods, it is common to use assertions to check their arguments: If the assertion fails, the Assertionerror is thrown, and if it does not work, there is no cost overhead.
      Private void sort (long  a[]) {    null;}

    3. For the constructor, or the parameters will be saved, and will be used later, in particular, should pay attention to check the validity

39: Protective Copy if necessary

If a class has mutable components that are either obtained from the client or returned to the client, the class must copy the components in a protective form. Unless the copy cost is limited and the class trusts that his client does not inappropriately modify the component, it is possible to indicate in the document that the client has to modify the component appropriately to replace the protected copy.

Attention:

    1. mutable components obtained from the client should also be protected copies, especially when they are passed to the constructor, which is not normally noticed. Furthermore, a protective copy is performed before checking the validity of the parameter, and the validity check is for the object after the copy, not the original object, which avoids checking that the data is changed by other threads during the actual copy. This is also a good embodiment of: safety is greater than efficiency
    2. For mutable components obtained from the client, if they can be quilt-like, then the clone function cannot be copied, because it is possible to pass in a sub-class object, and the clone function can be overridden by subclasses, which raises security issues. You can use clone out of the way, because inside the class you can determine that it is non-subclass
    3. It's really important to note that immutable objects should be used as internal components whenever possible to avoid protective copies. For example, a long object using Date.gettime () is used as the internal time component, not as date, because date is variable and long is immutable

40: Careful design method signature

Key points for designing a signature method:

    1. Choose a reasonable method name: Follow the standard habit and meaning clearly
    2. Avoid too much of a convenient way to lead to too many methods, especially for interfaces. Unless you are frequently used to consider providing a convenient method
    3. Avoid too long parameter lists
      1. Splitting method, but should pay attention to the orthogonality of the method to reduce the number of methods, that is, the method A, B split into A,b,c three methods, A and C implementation B and C
      2. Create an auxiliary class to hold the grouping of parameters, typically a static member class. Especially when certain parameters often appear together
      3. Use Builder mode: Call setter to set parameters multiple times, then execute method

Attention:

    1. For parameter types, use interfaces rather than classes, if possible, to avoid expensive copy operations
    2. For Boolean arguments, the enumeration type of two elements takes precedence, making the code easier to read and write, with better extensibility

41: Use heavy loads with caution

Overloads are static, and compile-time determines which version of the overloaded function is used, depending on the parameters called, and the overwrite is dynamic, and the runtime determines which version to use based on the actual type of the instance.

To be more precise, the overloads that should be avoided are: the same number of parameters, and the different versions can be applied between different version parameters through type conversion, which makes it not easy for programmers to determine which version to invoke, which could lead to errors.

If overloading is required, it is best to:

    1. Make different versions have different number of parameters
    2. If you have the same number of formal parameters, then the different versions of the parameters are "fundamentally different types", giving people a look at what they call, such as int and list<int>, instead of int and integer, because they automatically unboxing
    3. If not, you should try to ensure that different versions of overloaded functions have the same behavior for the same parameters.
    4. It is also a good strategy to consider not using overloads, but using different naming methods, such as ObjectOutputStream Writeboolean, Writelong, and Writeint.

42: Use variable parameters with caution

A mutable parameter can accept 0 or more parameters of a specified type. The variadic mechanism creates an array by first, the size of the array is the number of arguments passed at the call location, then passes the parameter values to the array, and finally the array is passed to the method. mutable parameters are a convenient way to define a variable number of parameters, but should not be misused to avoid confusion. The cause of the confusion may be mostly due to:

    1. 0 parameters can be passed, that is, the parameter is not passed
    2. When the parameter type is defined as T. For example, if the parameter is defined as T ... args, the call is passed in int[], but since int is a primitive type and cannot be considered directly as an object T, then int[] as a whole is treated as an argument, not as an int parameter

In addition, when it comes to performance, the array allocation and initialization of each invocation of a mutable parameter may be difficult to meet performance requirements, consider the following: If a call to a method 95% has three or fewer arguments, it declares 5 overloads of the method:

1  Public voidFun () {}2  Public voidFunintA1) {}3  Public voidFunintA1,intA2) {}4  Public voidFunintA1,intA2,intA3) {}5  Public voidFunintA1,intA2,intA3,int... rest) {}

43: Returns a 0-length array or collection, NOT null

This is for methods that return types are arrays or collections.

Benefit: Returns an array or collection of 0 lengths without requiring the client to have additional code to handle null return values.

For a rebuttal that returns null may be more than a zero-length array or a collection's performance advantage:

    1. This level of performance worry is unwise unless you determine that a performance issue has been caused
    2. Because 0-length arrays or collections are immutable, immutable objects can be freely shared, that is, multiple invocations will only produce an array or collection of 0-length

44: Write document comments for all exported API elements

    1. Annotate with Javadoc, including all exported classes, interfaces, constructors, methods, or fields
    2. For the method, it succinctly describes the contract between it and the client, explaining what this method does, not how it is complete, all previous prerequisites, post conditions, side effects, and thread safety

Effective Java Reading notes--Methods

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.