devil figures

Devil's Numbers in Code

 

Definition of devil numbers: numbers and strings that have no specific meaning in the code.

 

The devil's number mainly affects code readability, and the reader sees the number that cannot understand its meaning, making it difficult to understand the intention of the program. When there are too many devil numbers in the program, the maintainability of the code will drop sharply, the code will become difficult to modify, and it is easy to introduce bugs.

 

E.g:

 

After modification:

 

E.g:

int itemCount=10;                  // This can be considered not a devil's number , but there should be a comment

       int itemSize=5;                    //   this can be considered not a devil number , but there should be a comment

       // After a series of processing logic

       if ((storageManager.getCapacity() - itemCount*itemSize) < 1024){   //1024 is the devil's number

           storageManager.expandCapacityBy(512);     //512 is the devil's number

     }

 

solution:

1.   Define devil numbers as constants

For example, will:

storageManager.expandCapacityBy(512);

Change it to:

public static final int CAPACITY_INCREASE_STEP=512;

storageManager.expandCapacityBy(CAPACITY_INCREASE_STEP);

 

2.   Encapsulate the logic of using devil numbers as methods and add comments

For example, will:

if ((storageManager.getCapacity() - itemCount*itemSize) < 1024){

Change it to:

if ( storageManager.needIncreaseCapacity(itemCount,itemSize)){

 

boolean storageManager.needIncreaseCapacity(int itemCount,int itemSize){

    return (storageManager.getCapacity() - itemCount*itemSize) < 1024;// When the remaining capacity is less than 1024 bytes, expansion space is required.

}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326488135&siteId=291194637