寫出漂亮代碼的七種方法

來源:互聯網
上載者:User

編程是一種藝術,以下是從美學的角度出發的。以下為寫出漂亮代碼的七種方法:

1, 儘快結束 if語句

例如下面這個JavaScript語句,看起來就很恐怖:

1 function findShape(flags, point, attribute, list) {

2    if(!findShapePoints(flags, point, attribute)) {

3        if(!doFindShapePoints(flags, point, attribute)) {

4            if(!findInShape(flags, point, attribute)) {

5                if(!findFromGuide(flags,point) {

6                    if(list.count() > 0 && flags == 1) {

7                          doSomething();

8                    }

9                }

10            }

11       }

12    }  

13  }

但如果這麼寫就好看得多:

1 function findShape(flags, point, attribute, list) {

2    if(findShapePoints(flags, point, attribute)) {

3        return;

4    }

5

6    if(doFindShapePoints(flags, point, attribute)) {

7        return;

8    }

9

10    if(findInShape(flags, point, attribute)) {

11        return;

12    }

13

14    if(findFromGuide(flags,point) {

15        return;

16    }

17

18    if (!(list.count() > 0 && flags == 1)) {

19        return;

20    }

21

22    doSomething();

23

24 }

你可能會很不喜歡第二種的表述方式,但反映出了迅速返回if值的思想,也可以理解為:避免不必要的else陳述。

2, 如果只是簡單的布爾運算(邏輯運算),不要使用if語句

例如:

1 function isStringEmpty(str){

2    if(str === "") {

3        return true;

4    }

5    else {

6        return false;

7    }

8 }

可以寫為:

1 function isStringEmpty(str){

2    return (str === "");

3 }

3, 使用空白,這是免費的

例如:

1 function getSomeAngle() {

2    // Some code here then

3    radAngle1 = Math.atan(slope(center, point1));

4    radAngle2 = Math.atan(slope(center, point2));

5    firstAngle = getStartAngle(radAngle1, point1, center);

6    secondAngle = getStartAngle(radAngle2, point2, center);

7    radAngle1 = degreesToRadians(firstAngle);

8    radAngle2 = degreesToRadians(secondAngle);

9    baseRadius = distance(point, center);

10    radius = baseRadius + (lines * y);

11    p1["x"] = roundValue(radius * Math.cos(radAngle1) + center["x"]);

12    p1["y"] = roundValue(radius * Math.sin(radAngle1) + center["y"]);

13    pt2["x"] = roundValue(radius * Math.cos(radAngle2) + center["y"]);

14    pt2["y"] = roundValue(radius * Math.sin(radAngle2) + center["y");

15    // Now some more code

16 }

很多開發人員不願意使用空白,就好像這要收費一樣。我在此並非刻意地添加空白,粗魯地打斷代碼的連貫性。在實際編寫代碼的過程中,會很容易地發現在什麼地方加入空白,這不但美觀而且讓讀者易懂,如下:

1 function getSomeAngle() {

2    // Some code here then

3    radAngle1 = Math.atan(slope(center, point1));

4    radAngle2 = Math.atan(slope(center, point2));

5

6    firstAngle = getStartAngle(radAngle1, point1, center);

7    secondAngle = getStartAngle(radAngle2, point2, center);

8

9    radAngle1 = degreesToRadians(firstAngle);

10    radAngle2 = degreesToRadians(secondAngle);

11

12    baseRadius = distance(point, center);

13    radius = baseRadius + (lines * y);

14

15    p1["x"] = roundValue(radius * Math.cos(radAngle1) + center["x"]);

16    p1["y"] = roundValue(radius * Math.sin(radAngle1) + center["y"]);

17

18    pt2["x"] = roundValue(radius * Math.cos(radAngle2) + center["y"]);

19    pt2["y"] = roundValue(radius * Math.sin(radAngle2) + center["y");

20    // Now some more code

21 }

4, 不要使用無謂的注釋

無謂的注釋讓人費神,這實在很討厭。不要標出很明顯的注釋。在以下的例子中,每個人都知道代碼錶達的是“students id”,因而沒必要標出。

1 function existsStudent(id, list) {

2    for(i = 0; i < list.length; i++) {

3       student = list[i];

4

5       // Get the student's id

6       thisId = student.getId();

7

8       if(thisId === id) {

9           return true;

10       }

11    }

12    return false;  

13 }

5, 不要在源檔案中留下已經刪除的代碼,哪怕你標註了

如果你使用了版本控制,那麼你就可以輕鬆地找回前一個版本的代碼。如果別人大費周折地讀了你的代碼,卻發現是要刪除的代碼,這實在太恨人了。

//function thisReallyHandyFunction() {

//      someMagic();

//      someMoreMagic();

//      magicNumber = evenMoreMagic();

//      return magicNumber;

//}

6,不要有太長的代碼

看太長的代碼實在太費勁,尤其是代碼本身的功能又很小。如下:

1 public static EnumMap<Category, IntPair> getGroupCategoryDistribution(EnumMap<Category, Integer> sizes, int groups) {

2        EnumMap<Category, IntPair> categoryGroupCounts = new EnumMap<Category,IntPair>(Category.class);

3

4        for(Category cat : Category.values()) {

5            categoryGroupCounts.put(cat, getCategoryDistribution(sizes.get(cat), groups));

6        }

#

我並不是說非要堅持70個字元以內,但是一個比較理想的長度是控制在120個字元內。如果你把代碼發布在互連網上,使用者讀起來就很困難。

7,不要在一個功能(或者函數內)有太多程式碼

我的一個老同事曾經說Visual C++很臭,因為它不允許你在一個函數內擁有超過10,000行代碼。我記不清程式碼數的上限,不知道他說的是否正確,但我很不贊成他的觀點。如果一個函 數超過了50行,看起來有多費勁你知道麼,還有沒完沒了的if迴圈,而且你還的滾動滑鼠前後對照這段代碼。對我而言,超過35行的代碼理解起來就很困難 了。我的建議是超過這個數字就把一個函數代碼分割成兩個。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.