Effective the methods section in Java

Source: Internet
Author: User

1. Check the validity of the parameters

Non-public methods should use assertions (assertion) to check their parameters, and the public method needs to indicate in Javadoc what exception will be thrown if the parameter violates the limit.

But it is not that any restriction on parameters is a good thing, it should be guided by the principles of the general principle.

2. Protective copies must be made when necessary

This section touches me very much, because I never noticed that when I was writing code.

Take a look at the following code:

 Public Final classPeriod {Private FinalDate start; Private FinalDate end;  PublicPeriod (date start, date end) {if(Start.compareto (end) > 9)            Throw Newillegalargumentexception (Start+ "after" +end);  This. Start =start;  This. end =end; }     PublicDate Start () {returnstart; }     PublicDate End () {returnend; }}

At first glance it seems as if the period is immutable, in fact, just start and end cannot point to the new reference, but can be passed:

NewNew New  Period (start, end); End.setyear (78);

This changes the start and end in P, and if the interface in period is open to the client, it is possible to modify the starting and ending times at will, which is obviously not what we want, so we can use a protective copy to solve the problem:

 Public Final classPeriod {Private FinalDate start; Private FinalDate end;  PublicPeriod (date start, date end) { This. Start =NewDate (Start.gettime ());  This. end =NewDate (End.gettime ()); if(Start.compareto (end) > 9)            Throw Newillegalargumentexception (Start+ "after" +end); }}

Find a different place, if the client modifies the returned internal components, modifies only one copy of the component, cannot modify the real start and end, but still period provides access to the start and end of the public interface, so all can use a protective copy

Solve:

     Public Date Start () {        returnnew  Date (Start.gettime ());    }      Public Date End () {        returnnew  Date (End.gettime ());    }

As for why not using the Clone () method, the book is also written in detail, date is not the final class, that is, it can be inherited and modified, if someone maliciously inherits the date, the reference record into a private static list, this seed class is not credible, if as

In the construction of parameters passed into period, if the copy is made using the Clone () method, the Nobuko class is copied, or the period becomes vulnerable, and the Java.util.Date class is used to avoid this situation.

For internal components such as arrays, non-zero-length arrays must be mutable, and a protective copy should be returned to the client before returning it to an immutable view.

3. Carefully design method signatures with variable parameters and overloading

The principle is: The parameters can not too much, the method should not be too much, the method name should be clear, the parameter type takes precedence over the interface instead of the class.

Use the overloaded and mutable arguments with caution, because this blurs the method, and the result that the client gets after invoking the method is often unexpected. For example:

System.out.println (Arrays.aslist (MyArray));

The parameter of the Aslist () method is a variable parameter, which allows myarray to be passed in as the first element of the parameter array when the array is passed, and when it is wrapped in list<int[]>, it is meaningless to print:

[[[Email protected]]

4. Returns a zero-length array or collection instead of NULL

This I used to remind me when using sonarlint, mainly to avoid the client when the use of tortuous processing, such as must first determine whether it is null

Effective the methods section in Java

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.