Code elegance 1: clear error handling

Source: Internet
Author: User

RecentlyCodeI have read a few books and found that it is not easy to write code that is simple, beautiful, and readable. So I started to study how to write some common code structures more elegantly. Today I will share my first article.

 

When writing a piece of logic or writing a function (method), we usually need to add some fault tolerance Processing to ensure code robustness. Fault Tolerance processing is an important part. If you have not carefully considered it, it is easy to generate bugs. This is especially important when writing background code, because background services always run for a long time, and a small bug may cause service crash. However, if we add Fault Tolerance processing to a piece of logic, we often find that the code is messy, and fault tolerance code is everywhere. The real core logic does not know where to go. It is often seen that multi-layer if nesting makes it difficult to understand the code logic. The following is a simple example:
Java code:

     Public   Static String format1 ( Int Age, string name, Double  Salary ){  If (Age> 18 ){ If (Name! = Null & Name. Trim ()! = "" ){  If (Salary> 0 ){  //  Core Logic String personinfo = string. Format ("Name: % s, age: % d, salary: % lf" , Name, age, salary );  Return  Personinfo ;}  Else  {System. Err. println ( "Salary must be larger than zero! " );}}  Else  {System. Err. println ( "Name cannot be empty! " );}}  Else  {System. Err. println ( "Age must be larger than 18 ." );}  Return "" ;} 

The above Code seems okay because the logic is not very complex, but it is hard to read. If it is nested with three layers, the core logic is too indented and reading is very difficult. In real projects, this situation may be even more prominent. In extreme cases of nested if, there may be seven or eight layers. At that time, people who read the code will be crazy.

Of course, we can simply put the error handling code at the beginning, and return if there is a mistake. However, this encoding method is not applicable in some scenarios, or may produce a lot of repetitive code. For example, when the logic is used to read and write several files, the files must be closed after the code ends. If an error is returned at the beginning, the file may not be closed. Of course, you can try to close all files in each error handling section, but this will produce a lot of repeated code. Of course, you can close the file to package functions, but there is an additional function that is not necessary.

I thought for a long time and thought about a clear encoding method. We can encapsulate a logical variable for each type of error and assign values to these variables using an error judgment expression. It is best to use an if statement to process all logic. The core logic when the first if processing is correct, and other if branches handle various errors. The following code is used:
Java code:

 Public   Static String format2 ( Int Age, string name, Double  Salary ){  //  1. Definition and calculation of logical jump Variables          Boolean Agelegal = age> 18;  Boolean Namelegal = False  ;  Boolean Salarylegal = salary> 0 ;  //  2. If the calculation of some logical variables is complex, it can be defined only in code block 1. Namelegal = Name! = Null & Name. Trim ()! = "" ;  //  3. If jump Structure          If (Agelegal & namelegal &&Salarylegal ){  //  Core Logic String personinfo = string. Format ("Name: % s, age: % d, salary: % lf" , Name, age, salary );  Return  Personinfo ;}  Else   If (! Agelegal ){ //  Error Handling 1 System. Err. println ("age must be larger than 18 ." );}  Else   If (! Namelegal ){ //  Error Handling 2 System. Err. println ("name cannot be empty! " );}  Else   If (! Salarylegal ){ //  Error handling 3 System. Err. println ("salary must be larger than zero! " );}  Return "" ;} 

 

Come here today and continue with other ideas.

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.