This essay reference many materials, and under validated before or transcriptions or extract or combination with their own experience.
References:
1,SornaQube
2,
-------------------------------------------------- ----------Dividing line----------------------------------- -------------------------
1, equals the string comparison, initiate a text string is determined, on the left, can be prevented NullPointerException
String successFlag = null; if("0".equals(successFlag )){ //TODO }
2, nested if, for, while and try not to sentence structure more than three layers, if more than consider the business logic optimization
IF (condition1) { // first layer -OK. 1 / * ... * / IF (condition2 The) { // layer -OK 2 / * ... * / for ( int I = 0; I <10; I ++ ) { // layer 3 -ok, does not exceed the defined / * ... * / IF (condition4) { // layer 4 - not ok, beyond the limited / * ... * / return ; } } } }
3, (for example: files, database connections, network connections, etc.) relates to the operation of external resources, generally external plate processing resources in the finally closed, after which JDK7 use try-with-resources simplify the code syntax
【未使用try-with-resources】 FileInputStream inputStream = null; try { inputStream = new FileInputStream(new File("test")); System.out.println(inputStream.read()); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } } } 【使用try-with-resources】 try (FileInputStream inputStream = new FileInputStream(new File("test"))) { System.out.println(inputStream.read()); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); }
4, connected to a case of: If you have closed external resources when not easy try-with-resources operations grammar, it is recommended to separate try-catch resources
InputStream inStream = null, fileInStream = null; ServletOutputStream outStream = null; int byteRead; try { fileInStream = new FileInputStream("filename"); inStream = new BufferedInputStream(fileInStream); response.reset(); response.setContentType("APPLICATION/OCTET-STREAM"); response.setHeader("Content-disposition", "attachment; filename=" + "filename"+ ".xls"); outStream = response.getOutputStream(); byte[] buffer = new byte[1024]; while ((byteRead = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, byteRead); } response.flushBuffer(); outStream.close(); inStream.close(); fileInStream.close(); } catch (Exception e) { LOGGER.error("e); }finally{ try { if(outStream!=null){ outStream.close(); } } catch (IOException e2) { LOGGER.error(e2); } try { if(inStream!=null){ inStream.close(); } } catch (IOException e2) { LOGGER.error(e2); } try { if(fileInStream!=null){ fileInStream.close(); } } catch (IOException e2) { LOGGER.error(e2); } }
5,
Reproduced in: https: //www.cnblogs.com/ruanian/p/11064539.html