Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the top 10 low-level mistakes easy to make by Java programmers?

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "what are the top 10 low-level mistakes that Java programmers are easy to make". In daily operation, I believe many people have doubts about the 10 low-level mistakes that Java programmers are easy to make. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "what are the top 10 low-level mistakes easy to make by Java programmers?" Next, please follow the editor to study!

1 you cannot use "=" to compare the equality of two strings.

Unscramble

When comparing whether the contents of two strings are equal, if you use "= =", when two strings do not point to the same address in memory, then even if the contents of the two strings are the same, the result compared with "= =" is false. So be sure to use the "equals" method when comparing whether the contents of two strings are equal.

Example

Here is an example of string comparison:

Publicclass Test {publicstaticvoid main (String [] args) {String a = new String ("a"); String a2 = "a"; if (a = = a2) {System.out.println ("a = = a2return true.");} else {System.out.println ("a = = a2 returnfalse.")} if (a.equals (a2)) {System.out.println ("a.equals (a2) return true.") } else {System.out.println ("a.equals (a2) return false.");}

The result of the final output is:

A = = a2 return false. A.equals (a2) return true.2 cannot modify list structure in foreach loop

Unscramble

In foreach loop writing above the jdk1.5 version, the structure of the list being looped cannot be modified in the loop code, that is, add, remove and other operations are performed on the list. If you do these operations, you must exit the loop immediately, otherwise an exception will be thrown.

Example

Publicclass Test {publicstaticvoid main (String [] args) {List list = new ArrayList (); Person p1 = new Person ("Zhang San", 23); Person p2 = new Person ("Li Si", 26); Person p3 = new Person ("Wang Wu", 34); Person p4 = new Person ("Liu er", 15); Person p5 = new Person ("Zhu Liu", 40); list.add (p1); list.add (p2); list.add (p3); list.add (p4) List.add (p5); for (Person p: list) {if (Wang Wu .equals (p.getName () {list.remove (p); / cannot delete an object at this time. } elseif ("Li Si" .equals (p.getName () {list.remove (p); / / cannot delete an object at this time. } System.out.println (list.size ());} class Person {private String name; privateintage; public Person (String name, intage) {this.name = name; this.age = age;} public String getName () {returnname;} publicvoid setName (String name) {this.name = name;} publicint getAge () {returnage;} publicvoid setAge (intage) {this.age = age;}}

To solve the problem in the red part of the code above, you can take out the object through a loop, and then delete it at the end of the loop.

List list = new ArrayList (); Person p1 = new Person (new String ("Zhang San"), 23); Person p2 = new Person (new String ("Li Si"), 26); Person p3 = new Person (new String (Wang Wu), 34); Person p4 = new Person (new String ("Liu er"), 15); Person p5 = new Person (new String ("Zhu Liu"), 40); list.add (p1); list.add (p2); list.add (p3) List.add (p4); list.add (p5); Person wangwu = null; Person lisi = null; for (Person p: list) {if ("Wang Wu" .equals (p.getName () {wangwu = p;} elseif ("Li Si" .equals (p.getName () {lisi = p;}} list.remove (wangwu); list.remove (lisi); 3 Log standardization

Unscramble

The log is the most important basis for locating the problem. The lack of necessary logs in the business process will bring a lot of trouble to the positioning problem, and may even cause the problem to be completely impossible to locate.

After an exception occurs, the exception stack must be recorded in the log at the level of ERROR or above, otherwise the exception stack will be lost and the location of the exception cannot be confirmed. It is not necessary to record the exception log every time an exception is caught, which may cause the exception to be recorded repeatedly and affect the location of the problem. However, the exception stack must be recorded at least once after the exception occurs.

Like comments, the more logs, the better. Useless redundant logs not only cannot help locate the problem, but also interfere with the location of the problem. And the wrong log will mislead the problem and must be put an end to.

Example

Although the following example prints a lot of logs, they are basically useless logs and are difficult to help locate the problem. There are even wrong logs that interfere with the positioning of the problem:

Public voidsaveProduct1 (ProductServiceStruct product) {log.debug ("enter method: addProduct ()"); log.debug ("check product status"); if (product.getProduct (). GetProductStatus ()! = ProductFieldEnum.ProductStatus.RELEASE) {thrownewPMSException (PMSErrorCode.Product.ADD_ERROR);} log.debug ("check tariff"); BooleanResult result = checkTariff (product.getTariffs ()); if (! result.getResult ()) {thrownewPMSException (PMSErrorCode.Product.ADD_ERROR) } log.debug ("before add product"); ProductService prodSrv = (ProductService) ServiceLocator.findService (ProductService.class); try {prodSrv.addProduct (product);} catch (BMEException e) {/ / No exception stack is recorded, unable to locate the source of the problem} log.debug ("after add product"); log.debug ("exit method: updateProduct ()"); / / incorrect log}

The following example log is not printed much, but it is all key information, which can help to locate the problem:

Public voidsaveProduct2 (ProductServiceStruct product) {if (product.getProduct (). GetProductStatus ()! = ProductFieldEnum.ProductStatus.RELEASE) {log.error ("productstatus" + product.getProduct (). GetProductStatus () + "error, expect" + ProductFieldEnum.ProductStatus.RELEASE); thrownewPMSException (PMSErrorCode.Product.ADD_ERROR);} BooleanResult result = checkTariff (product.getTariffs ()) If (! result.getResult ()) {log.error ("checkproduct tariff error" + result.getResultCode (): "+ result.getResultDesc ()); thrownewPMSException (PMSErrorCode.Product.ADD_ERROR);} ProductService prodSrv = (ProductService) ServiceLocator.findService (ProductService.class); try {prodSrv.addProduct (product);} catch (BMEException e) {log.error (" add product error ", e); thrownewPMSException (PMSErrorCode.Product.ADD_ERROR,e) }} 4 devil numbers

Unscramble

Using devil numbers (numbers with no specific meaning, strings, etc.) in your code will make the code difficult to understand and should be defined as a constant with a meaningful name.

The ultimate goal of defining a number as a constant is to make the code easier to understand, so it's not just defining a number as a constant is not a devil's number. If the name of a constant is meaningless and does not help you understand the code, it is also a devil's number.

In individual special cases, defining a number as a constant makes the code more difficult to understand, and it should not be forced to define a number as a constant.

Example

Public void addProduct (ProductServiceStruct product) {/ / devil number, unable to understand what status 3 represents specifically for the product if (product.getProduct (). GetProductStatus ()! = 3) {thrownewPMSException (PMSErrorCode.Product.ADD_ERROR);} BooleanResult result = checkTariff (product.getTariffs ()); if (! result.getResult ()) {thrownewPMSException (PMSErrorCode.Product.ADD_ERROR);}} / * * Product inactive status * / privatestaticfinalintUNACTIVATED = 0 / * * Product activated status * / privatestaticfinalintACTIVATED = 1; public voidaddProduct2 (ProductServiceStruct product) {if (product.getProduct (). GetProductStatus ()! = ACTIVATED) {thrownewPMSException (PMSErrorCode.Product.ADD_ERROR);} BooleanResult result = checkTariff (product.getTariffs ()); if (! result.getResult ()) {thrownewPMSException (PMSErrorCode.Product.ADD_ERROR);}} 5 null pointer exception

Unscramble

Null pointer exception is the most common exception in the coding process. When using an object, if the object may be empty, and the use of secondary object may cause null pointer exception, then you need to determine whether the object is empty or not, and then use this object.

When judging the equality of constants and variables, it is recommended that constants be defined as Java object encapsulation types (for example, constants of int type are defined as Integer types), so that the constants can be placed on the left when comparing, and the equals method can be called to compare, thus eliminating unnecessary null judgment.

Example

Public classNullPointer {staticfinal Integer RESULT_CODE_OK = 0; staticfinal Result RESULT_OK = newResult (); publicvoid printResult (Integer resultCode) {Result result = getResult (resultCode); / / result may be null, resulting in a null pointer exception if (result.isValid ()) {print (result) }} publicResult getResult (Integer resultCode) {/ / even if resultCode is null, it can still be executed correctly, reducing the extra null statement if (RESULT_CODE_OK.equals (resultCode)) {returnRESULT_OK;} returnnull;} publicvoid print (Result result) {...}} 6 subscript out of bounds

Unscramble

When accessing elements in an array, List and other containers, you must first check whether the subscript is out of bounds to prevent the occurrence of subscript out-of-bounds exceptions.

Example

Publicclass ArrayOver {publicvoid checkArray (String name) {/ / gets an array object String [] cIds = ContentService.queryByName (name); if (null! = cIds) {/ / only considers that cids may be null, but cids may be a 0-length array, so it is possible that cIds [0] array subscript crosses String cid=cIds [0]; cid.toCharArray ();}} 7 string to number

Unscramble

When you call the Java method to convert a string to a number, a run-time exception NumberFormatException is thrown if the string is in an illegal format.

Example

Examples of errors:

Public Integer getInteger1 (String number) {/ / if the number format is illegal, NumberFormatException returnInteger.valueOf (number) will be thrown;}

The correct treatment is as follows:

Public Integer getInteger2 (String number) {try {returnInteger.valueOf (number);} catch (NumberFormatException e) {... / / record log exception information returnnull;}}

Note: be sure to log after catching an exception.

8. Resource release

Unscramble

When using resources that are not automatically released, such as files, IO streams, database connections, and so on, you should turn them off as soon as you finish using them. The code that closes the resource should be executed within the finally of the try...catch...finally, otherwise the resource may not be released.

Example

Examples of errors are as follows:

Public voidwriteProduct1 (ProductServiceStruct product) {try {FileWriter fileWriter = new FileWriter ("); fileWriter.append (product.toString ()); / / if append () throws an exception, the close () method will not execute, resulting in the IO stream not releasing fileWriter.close () for a long time;} catch (IOException e) {...}} the correct way to close the IO stream is as follows: public voidwriteProduct2 (ProductServiceStruct product) {FileWriter fileWriter = null Try {fileWriter = new FileWriter ("); fileWriter.append (product.toString ());} catch (IOException e) {. / / logging} finally {/ / regardless of whether there is an exception or not, the code in finally must execute if (fileWriter! = null) {try {fileWriter.close ();} catch (logging) {. / / logging}}

Note: be sure to log after catching an exception.

9 cycle body performance

Unscramble

The loop body is the most likely to cause performance problems in the software, so the performance problem must be considered when coding the loop body.

Resources that are reused and will not change in the loop body (such as variables, file objects, database connections, etc.) should be constructed and initialized before the loop body starts, so as to avoid the waste of CPU resources caused by repetition and structural initialization in the loop body.

Avoid constructing try...catch blocks in the loop body unless required by the business scenario, because each entry and exit of the try...catch block consumes certain CPU resources, and putting the try...catch block outside the loop body can save a lot of execution time.

Example

Public voidaddProducts (List prodList) {for (ProductServiceStruct product: prodList) {/ / prodSrv is retrieved at each cycle, resulting in unnecessary resource consumption ProductService prodSrv = (ProductService) ServiceLocator.findService (ProductService.class); / / avoid try...catch in the body of the loop, which can save execution time try {prodSrv.addProduct (product) } catch (BMEException e) {... / / logging}

If you encounter string addition in the body of the loop, be sure to use the class StringBuffer.

10 data class overloaded toString () method

Unscramble

If the data class does not overload the toString () method, it will not be able to record the property values of the data object when logging, which makes it difficult to locate.

Example

Public classMdspProductExt {privateString key; privateString value; publicString getKey () {returnkey;} publicvoid setKey (String key) {this.key = key;} publicString getValue () {returnvalue;} publicvoid setValue (String value) {this.value = value;}} class BusinessProcess {privateDebugLog log = LogFactory.getDebugLog (BusinessProcess.class) Publicvoid doBusiness (MdspProductExtprodExt) {try {...} catch (PMSException e) {/ / MdspProductExt does not overload the toString () method, the log cannot record the value of attributes in the object, only the object address log.error ("error while process prodExt" + prodExt);} at this point, the study on "what are the top 10 low-level mistakes easy to make by Java programmers" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report