Robert Martin once said that “the frequency of swearing in code reading is the only measure of code quality”. At the same time, the code should be written in such a way as to minimize the time it takes for others to understand it, which means that we write code for people, not machines. So how do you write elegant code? You can optimize your code both at the ideological level, which means following object-oriented design principles, and at the specific level of techniques covered in this installment.

##1. Is code always as short as possible?

assert((! (bucket = findBucket(key))) || ! bucket.isOccupied());Copy the code

The above line of code is short, but difficult to read. For better reading, we make the following modifications:

bucket = findBucket(key);
if(bucket ! = null){ assert(! bucket.isOccupied()); }Copy the code

Reducing the number of lines of code is a good goal, but minimizing the number of events that read the code is a better goal.

2. Add comments to important statements

// Fast version of "hash = (65599*hash) + c"
hash = (hash< < 6) + (hash< < 16) -hash + c
Copy the code

The above line of code would have no idea what it meant without the comment, but with the comment, we know that the shift operation improves performance.

TMP is something we use a lot, like two variable substitutions, and it’s become a convention.

tmp = right;
right = left;
left = tmp;
Copy the code
String tmp = user.getName();
tmp += "" + user.getPhoneNumber();
tmp += "" + user.getEmail();
template.set("user_info",tmp);
Copy the code

4.I, j, K, iter, it: Only used for indexing or loop iteration

It is standard practice for I, j, k, iter, it to be used for indexing or iterating (I is short for index), for example:

for(int i=0; i<100; i++){for(int j=0; j<100; j++){ ...... } } Iterator<String> iter = list.iterator();while(iter.hasNext()){
  ......
}
Copy the code

If we use I, j, k elsewhere, it will increase the reader’s time.

5. Attach important attributes

We use naming as a way of commenting and letting it carry more information!

6. How long should a name be?

  • Use short names in small scopes
  • Long names can be used in large scopes
if(debug){
  Map<String,Integer> m = new HashMap<>();
  lookUpNamesNumbers(m);
  print(m);
}
Copy the code

7. Don’t use misleading names

results = Database.all_objects.filter("year<=2011")
Copy the code

What information does the above line of code result now contain? Filter is to filter out the data whose year is less than or equal to 2011. Or keep it?

8. It is recommended to use min and Max to express limits

MAX_ITEMS_IN_CART = 10;

if (shoppingCart.numOfItems()> MAX_ITEMS_IN_CART){
    error("Too many items in cart");
}
Copy the code

9. Begin and end are recommended for inclusion/exclusion


String s = "Hello world"; S.s ubstring (2, 5); ->"llo"

Copy the code

10. Match user expectations

In general, getters are methods that get the value of a field. Users expect lightweight methods. If you do too much computation in them, you should consider changing the name.


public double getMeanPrice(){// iterate over all items to calculate the total price, then calculate the average price} public doublecomputeMeanPrice(){// iterate over all items to calculate the total price, then calculate the average price}Copy the code

11. Don’t comment for facts that can be quickly inferred from the code itself


public  class Account {  

    // Constructor

   public  Account(){

   }

   // Set the profit member to a new value    

   void setProfit (double Profit) {... . } // Return the profit from this Account doublegetProfit() {... .}};Copy the code

12. Don’t comment bad names — change them well

// Releases the handle for this key.This doesn't modify the actual registry.
void deleteRegistry(RegistryKey key)
Copy the code

At first glance we might mistake this for a function that deletes the registry, but the comments clarify that it does not change the real registry. Therefore, we can use a more self-explanatory name, such as:

void releaseRegistryHandle(registryKey key);
Copy the code

13. Write comments for flaws in your code

TODO(dustin): handles image formats other than JPEG

14. Write comments for constants

// users thought 0.72 gave the best size/quality tradeoff
image_quality = 0.72;

// as long as it's >= 2*num_processors,that's good enough
NUM_THREADS = 8;

// impose a reasonable limit - no human can read that much anywhere
const int MAX_RSS_SUBSCRIPTIONS = 1000;
Copy the code

15. Put yourself in the reader’s shoes

struct Recoder {
    vector<float> data; . voidclearClear (){// Everyone reads this and asks why we don't call data.clear() vector<float>().swap(data); }}Copy the code

If there is a good comment that answers the reader’s question, modify the above as follows: Force the Vector to actually return memory to the memory allocator. See STL Swap Trick for details.

16. Announce possible pitfalls

void sendMail(String to,String subject,String body);
Copy the code

This function can be time-consuming because of the need to call an external server to send mail, potentially causing the consumer’s thread to hang. You need to put this description in a comment.

17. Order of arguments in conditional statements

Put the more stable variable on the right
In the case of non-” size “comparisons, the above principle does not seem to work
if ( request.getParameterValue("name")).equals("Brandon"))

18. Order of if/else statement blocks

If /else writing specification: Handle positive logic first rather than negative logic, such as if(OK) rather than if(! “Ok”); The second is to get rid of simple cases, which makes it easier for the if and else processing code to be visible on the same screen.

19. Reduce nesting by returning early

Using the early return mechanism, you can make the nesting level of functions shallow. For example, instead of using pre-returned code:

static bool checkUserAuthority()
        {
            bool a, b, c, d, e;

            if (a)
            {
                if (b)
                {
                    if (c)
                    {
                        if (d)
                        {
                            if (e)
                            {
                                return true;
                            }
                        }
                    }
                }
            }

            return false;
        }
Copy the code

Pre-returned code is used:

static bool checkUserAuthority()
        {
            bool a, b, c, d, e;

            if(! a)return false;

            if(! b)return false;

            if(! c)return false;

            if(! d)return false;

            if(! e)return false;

            return true;
       
        }
Copy the code

##20. Improve readability by “summarizing variables”

if(request.user.id == document.owner_id){
    // user can edit this document ...
}

if(request.user.id ! = document.owner_id){ // document isread-only...
}
Copy the code

Final Boolean user_OWNS_document =(request.user.id == document.owner_id), then the code can be changed to:

if(user_owns_document){
 // user can edit this document ...
}
if(! user_owns_document){ // document isread-only...
}

Copy the code

Reduce control flow variables

In loops such as while and for, we usually use a custom bool variable to control the flow.

boolean done = false;
while(/* condition */ && !done){
    ...
    if(...). {done = true;
        continue; }}Copy the code

In our experience, “control flow variables” can be eliminated by optimizing program structure and logic.

while(/* condition */){
    ...
    if(...). {break; }}Copy the code

22. Reduce the scope of variables

void foo(){
    int i = 7;

    if(someCondition){
        // i is used only within this block
    }

}

void foo() {if(someCondition){
        int i = 7;
        // i is used only within this block
    }
}
Copy the code

23. Do not set variables to class fields for sharing purposes

public class LargeClass{
    String s;
    void method1(){
        s = ...
        method2();
    }
    void method2(){
        //使用s
    }
}
Copy the code

Data sharing is realized through parameter passing

public class LargeClass{
    void method1(){
        String s = ...
        method2(s);
    }
    void method2(String s){
        //使用s
    }
}
Copy the code

24. Don’t define all variables at the beginning

Defining all variables at the beginning is the style of THE C language, object-oriented languages tend to define variables away from where they start to be used.

public void foo(){
  boolean debug = false; String[] pvs; String pn; String pv; . }Copy the code

In addition to the above suggestions, we can also refer to The Ali Java specification, follow the wechat account: “Mukeda”, send “Ali Java specification” to get relevant information.


Welcome to follow wechat public account: Mukeda, all articles will be synchronized on the public account.