Java programming is the most easy to forget the problem, please!

Source: Internet
Author: User
Tags getmessage stack trace volatile


1. Tangled with the same name

Phenomenon

Many classes are named the same (for example, common to exceptions, constants, logs, and so on), which sometimes pigtailed when import, sometimes in a subtle way. The IDE does not prompt for warn because the class features that are often the same name are similar.

Solve

When you have finished writing the code, scan the import section to see if there are any unfamiliar ones. After you have replaced the correct import, be aware that the comments are also modified accordingly.

Enlightenment

Name as far as possible to avoid duplicate names, especially to avoid the same name as the JDK class, otherwise easy to import the wrong, there are a large number of duplicate class, in the search, also need more time to identify.

2. Take the API for granted

Phenomenon

Sometimes when invoking the API, it is assumed that the name can be called directly and confidently, causing a surprising number of errors:

Example one: Flag is true?

Boolean flag = Boolean.getboolean ("true");

Probably always false.

Example two: Is this the present of the year (this is 2012, regardless of leap year)? The result is still 2012:

Calendar calendar = Gregoriancalendar.getinstance;calendar.roll (calendar.day_of_year,-365);

The following is last year:

Calendar.add (Calendar. Day_of_year,-365);

Solutions

Ask yourself a few questions, is this method familiar to me? Is there a similar API? What's the difference? In the case of example one, the following differences are required:

Boolean.valueof (b) VS Boolean.parseboolean (b) Vsboolean.getboolean (b);

Enlightenment

Name from a more detailed point, the note is more clear, do not know, test to take for granted some APIs, if the time is limited, with their most familiar with the API.

3. Sometimes overflow is not difficult

Phenomenon

Sometimes overflow is not difficult, although not often reproduced:

Example one:

Digital 1x Digital 2x Digital 3 ...

Example two:

In order to avoid overloading, select the parameter number, and the result of the following code is less than 0, also because the overflow causes:

Solve

Let the first operand be long, for example plus L or l (lowercase l is not recommended because it is too similar to the number 1);

When unsure, use the overload bar, which uses doublevalue, which does not solve the problem when the parameter is the BigDecimal parameter.

Enlightenment

Be sensitive to the use of digital: It involves the calculation of the number to consider overflow, involving division to consider dividend is 0; I can think of BigDecimal.

4. Where did the log go?

Phenomenon

Sometimes I think the log is playing, how can not find?

Example one: no stack trace!

} catch (Exception ex) {log.error (ex);}

Example two: log! not found

} catch (ConfigurationException e) {e.printstacktrace;}

Solve

1. Replace with Log.error (EX.GETMESSAGE,EX);

2. Change to a regular log4j instead of a System.out.

Enlightenment

1.API definition should avoid making mistakes, if you add an overloaded log.error (Exception) Naturally no errors occur

2. In the product code, the use of some of the methods to consider whether it is effective, using e.printstacktrace to see where the terminal (console).

5. Forgotten volatile

Phenomenon

In DCL mode, always forget to add a volatile.

Privatestatic Cacheimpl instance; Lose Volatilepublicstaticcacheimpl getinstance {if (instance = = null) {synchronized (Cacheimpl.class) {if (instance = = NULL) {instance = Newcacheimpl;}} } return instance; }

Solve

Undoubtedly, add one bar, synchronized lock is a piece of code (the entire method or a block of code), to ensure that the "block" code visibility and atomicity, but instance = = NULL for the first time judgment is no longer within the range. Therefore, it is possible to read out an expired null.

Enlightenment

We always feel that some low probability events are difficult to take place, such as the likelihood of a time concurrency, the likelihood of an exception being thrown, and so no control, but if you can, follow the previous "best practices" to write code. At least not too much explaining why.

6. Do not affect each other

Phenomenon

When releasing multiple IO resources, IOException is thrown, so it might be easier to write:

Publicstaticvoidinputtooutput (InputStream is, OutputStream os, Boolean isclose) throws IOException { Bufferedinputstream bis =new bufferedinputstream (is, 1024); Bufferedoutputstream BOS = newbufferedoutputstream (OS, 1024); .... if (isclose) {bos.close; bis.close;}}

Assuming that the BOS shutdown fails, can the BIS still be closed? Of course not!

Solutions

Although the same exception is thrown, it is better to capture each one individually. Otherwise the first one fails, and the latter face has no chance to release the resources.

Enlightenment

There may be dependencies between the code/modules, to fully identify the dependencies on each other.

7. Replace the parameter check with an assertion

Phenomenon

Title, as a common way of defensive programming: assertions, written in the product code to do parameter verification. For example:

Privatevoidsend (List eventlist) {assert eventlist! = null;}

Solve

Change to a normal uniform parameter checking method. Because the assertion is turned off by default, it does not work entirely in the configuration, and if the default configuration has gone through the eventlist! = NULL result has not worked, in vain.

Enlightenment

Sometimes, the code does not work, not only in use cases, but also in configuration, such as whether the assertion is enabled, log level, etc., to combine the real environment to do useful coding.

8. The user's cognitive burden is sometimes heavy.

Phenomenon

Let's compare three sets of examples to see if those look smoother.

Example one:

Publicvoidcaller (int A, string B, float C, string d) {MethodOne (d, z, b); Methodtwo (b, C, d);} Publicvoidmethodone (string d, float z, string b) Publicvoidmethodtwo (string B, float C, string d)

Example two:

Publicbooleanremove (string key, long timeout) {futurefuture = Memcachedclient.delete (key); Publicbooleandelete (string Key, Long

Example three:

Publicstaticstring getdigest (String filePath, Digestalgorithm algorithm) publicstaticstring getdigest (String FilePath , Digestalgorithm Digestalgorithm)

Solve

Maintain the order of parameter passing;

Remove becomes a delete, appears abrupt point, unified expression is better;

Keep the expression, fewer abbreviations will also appear smooth points.

Enlightenment

In the coding process, regardless of the order of the parameters or the name are as uniform as possible, so that the user's cognitive burden will be very small, do not want users prone to mistakes or confusion. For example, use an enumeration instead of a string to confuse the user with what string to pass, and so forth.

9. Ignore logging timing, level

Phenomenon

The following two examples exist:

Example one: Should the log not be logged?

catch (SocketException e) {log.error ("Server Error", e); Thrownewconnectionexception (E.getmessage, e);}

Example two: What level logs do you remember?

In the user logon system, each failed logon:

Log.warn ("Failed to login by" +username+ ");

Solve

1. Remove logging: If you encounter an exception that needs to be re-throw, if everyone is processed in the same way as the first record and throw, then too many logs are logged for an error, so this is not recommended But if the re-throw out of exception does not have a complete trace (i.e. cause), it is best to record it.

2. If the malicious login, there will be too many warn inside the system, so that the administrator mistakenly thought to be a code error. You can feed back the user with errors, but do not log user error behavior unless you want to achieve the purpose of control.

Enlightenment

Log changes do not change the record? What level do you remember? How to remember? These are questions that must be considered according to the specific circumstances:

1. Is user behavior error or code error?

2. Recorded logs, can give others without causing excessive interference in the premise of providing useful information to quickly locate the problem.

10. Forget to set the initial capacity

Phenomenon

In Java, we use the map in collection as the cache, but we often forget to set the initial capacity.

Cache=new Lrulinkedhashmap

Solve

How much does the initial capacity affect? Take Linkedhashmap, the initial capacity if not set by default is 16, more than 16xload_factor, will resize (2 * table.length), expand twice times: using Entry newtable = new entry[ Newcapacity]; Transfer (newtable), that is, the entire array copy, then for a larger capacity cache, from 16 to a large number of times, it is conceivable that the group should be duplicated. If the initial capacity is set to a large size, it will naturally reduce resize, although it may be feared that no cache content will still occupy a large volume when the initial capacity setting is large. In fact, you can refer to the following table for a simple calculation, initially there is no cache content, each object is only a 4-byte reference.

Memory for reference fields (4 bytes each);

Memory for primitive fields

Enlightenment

Not only map, there are stringbuffer and so on, there are capacity resize process, if the data is large, you can not ignore the initial capacity may be considered set, otherwise not only frequent resize also easy to waste capacity.

In Java programming, in addition to some of the above enumerated issues that are easily overlooked, there are still many in the daily practice. Believe in the continuous practice of self can be found and corrected.

Summarize:

Whether it is development, testing, operation, each technician in the heart more or less have a technical Daniel Dream, after all, "dream always have to have, in case the realization of it"! It is the pursuit of technical dreams, prompting us to constantly strive and improve ourselves.

Java programming is the most easy to forget the problem, please!

Related Article

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.