用程式碼說人話

ZiziChou

程式碼臭不臭?

  • 滑鼠滾滾滾
  • 尋找蛛絲馬跡
  • 方法跳跳跳
  • 跟看小說一樣
  • 不斷使用求救卡

人家不睡覺當小偷

我們不睡覺當柯南

寫者無心,看者有意

  • 命名
     
  • 註解
     
  • 結構
     
  • 架構

命名

  • Class:班級(Grade)
     
  • 需求:獲取學生數量

說中文彷彿在說法文

  • getStudentsCount();
     
  • countStudents();
     
  • students.size();
     
  • size();
     
  • studentsCount();

說中文彷彿在說法文

事實往往不如想像中的美好

 

  • grade.getStudentsCount();
    • get 有些多餘?
  • grade.countStudents();
    • 行為,需要時間?
  • grade.students.size();
    • students 公開?
  • grade.size();
    • 班級房間大小?
  • grade.studentsCount();

摻在一起做撒尿牛丸?

 

  • 重新檢索 = research
     
  • 限制 = limit?
     
  • 加速 = fasten?

結果連是牛是豬都搞不懂

 

  • 重新檢索 != research = 研究
    • searchAgain
       
  • 限制 != limit = 極限
    • restriction
       
  • 加速 != fasten = 固定
    • accelerate

眼睛自備分段系統?

public class Keyboard {
    private String theInputtedKeycharacterOfHardKeyboard;
}

眼睛自備分段系統?

public class Keyboard {
    private String theInputtedKeycharacterOfHardKeyboard;
}
public class HardKeyboard extends Keyboard {
    private String input;
}

女人的天性 = 口是心非

 

  • 更新顯示
  • 寫入檔案
public void update(String[] data) {
    showData(data);
    writeToFile(data);
}

隱藏性錯誤

說不要不見得是真的不要?

if ((hardKeyboardHidden == 0) == false)

說不要不見得是真的不要?

if ((hardKeyboardHidden == 0) == false)
if (hardKeyboard.isConnected())

註解

每個工程師心中都有一座 101

/** 向左上角移動 */
600+

/** 向左下角移動 */
600+

/** 向右上角移動 */
600+

/** 向右下角移動 */
600+

根本之道:縮短 method

別人寫的都是聖經?

// 打開檔案
File file = new File("xxxx");

try {
    //讀取檔案
    while (true) {
        String row = file.readLine();
        // 略
    }
} catch (Exception e) {
    //略
} finally {
    try {
        //關閉檔案
        file.close();
    } catch (Exception e) {
        //略
    }
}

難以閱讀

培養副業:占卜師

public void calculateTax() {
    tax = (salary - nonTaxBase) * percentage - tail;
}
File file = new File("xxxx");

try {
    while (true) {
        String row = file.readLine();
    }
} catch (Exception e) {
    
}

結構

switch-case 吃到飽

public boolean onKeyDown(int keyCode, keyEvent event) {
    switch(keyCode) {
        case KeyEvent.KEYCODE_ENTER:
            break;
        case KeyEvent.KEYCODE_SPACE:
            break;
        case KeyEvent.KEYCODE_LEFT:
            break;
        case KeyEvent.KEYCODE_RIGHT:
            break;
        case KeyEvent.KEYCODE_UP:
            break;
        case KeyEvent.KEYCODE_DOWN:
            break;
        case KeyEvent.KEYCODE_BUTTON1:
            break;
        case KeyEvent.KEYCODE_BUTTON2:
            break;
        case KeyEvent.KEYCODE_BUTTON3:
            break;
        ...
    }
        return false;
}

老饕才懂得如何吃得久

public boolean onKeyDown(int keyCode, keyEvent event) {
    if (event.isPrintingKey()) {
        return appendInput(keyCode);
    } else if (event.isArrowKey(keyCode)) {
        return moveCursor(keyCode);
    } else if (event.isChannelKey(keyCode)) {
        return appendInput(convertChannelToNumber(keyCode));
    } else if (event.isFunctionalKey(keyCode)) {
        return processFunctionalKey(keyCode);
    } 
        return false;
}

國王的 default?

public enum State {
    CREATED, UPDATED, DELETED
}

public void process(State state) {
    switch (state) {
        case State.CREATED:
                ...
            break;
        case State.UPDATED:
                ...
            break;
        case State.DELETED:
                ...
            break;
        default:
            return 0 ?
            return null?

            // 怎麼死得都不知道
    }
}

話要好好說

public enum State {
    CREATED {
        public void process() {
            ...
        }
    },

    UPDATED {
        public void process() {
            ...
        }
    },
    
    DELETED {
        public void process() {
            ...
        }
    };
}

public void process(State state) {
    state.process();
}

架構

一家親?

public class keyboard {
    private Sound sound;
    public void pressUpKey(int level) {
        sound.up(level);
    }
}

一家親?

public class keyboard {
    private Sound sound;
    public void pressUpKey(int level) {
        sound.up(level);
    }
}
public class ComputerAction {
    public Keyboard keyboard;
    public Sound sound;
}

不是每個人都可以十項全能

public class Keyboard {
    private boolean onKeyDown(int keyCode, KeyEvent event) {
        // 輸入
    }

    private void display() {
        // 顯示
    }

    private List<String> convert(String input) {
        // 轉換
    }

}

Bug小孩往往是不小心生出來的

動作一定要是方法?

public class Warrior {
    public void fight(性別) {
        if (男) {
            // 處理 A 攻擊
        } else if (女) {
            // 處理 B 攻擊
        } else if (不男不女) {
            // 處理 C 攻擊
        }

        ...
    }
}
public class Warrior {
    public void fight() {
        FistFactory.create(條件).attack();
}

public interface Attackable {
    public void attack();
}
public class LightFist implements Attackable {
    public void attack() {
        ...
    }
}

public class SuperFist implements Attackable {
    public void attack() {
        ...
    }
}
public class FistFactory {
    public static Attackable create(性別) {
        if (女) {
            return new LightFist();
        } else if (男生) {
            return new SuperFist();
        }
        return null;
    }
}

各種出拳方式

多一種 = 多一個實作

儘管呼叫 attack 就好

public void setupButton() {
    LoginButton loginButton = new LoginButton();
    loginButton.addActionListener(
        new ActionListener() {
            public void actionPerformed(Event e) {
                showAlert();
            }
        });

    LogoutButton logoutButton = new LogoutButton();
    logoutButton.addActionListener(
        new ActionListener() {
            public void actionPerformed(Event e) {
                showAlert();
            }
        });
}

心臟只有一顆,樓不能跳兩次

厲害的人往往一次到位

public class LoginPage implements ActionListener {
    public void setupButton()  {
        LoginButton loginButton = new LoginButton();
        loginButton.addActionListener(this);
    
        LogoutButton logoutButton = new LogoutButton();
        logoutButton.addActionListener(this);
    }

    public void actionPerformed(Event e) {
        showAlert();
    }
}

請學習克服跳針

public class Browse extends Activity {
    public void showToast()  {
        Toast.makeText(this, "Browse", Toast.LENGTH_LONG).show();   
    }
}
public class Inbox extends Activity {
    public void showToast()  {
        Toast.makeText(this, "Inbox", Toast.LENGTH_LONG).show();   
    }
}
public class Checkout extends Activity {
    public void showToast()  {
        Toast.makeText(this, "Checkout", Toast.LENGTH_LONG).show();   
    }
}

每天都充滿驚喜

{
  "result": [
    {
      "uid": "pollynull",
      "created": 1398838793,
      "country": {
        "code": "TW",
        "name": "台灣"
      },
      "review": {
        "rating": 0,
        "total": 0
      },
      "item_fav": [
        "11YYvIsT",
        "1jaGFTBy"
      ],
      "seller": false,
      "store_fav": [
        "suebidowa"
      ],
      "nick": "pollynull",
      "intro": "",
      "avatar_rev": 0,
      "reward": {
        "points": 3815
      },
      "friend": {
        "requested": [],
        "friend": [
          "pollychou"
        ],
        "requesting": []
      }
    }
  ]
}

for 打得手好酸?

for (int i = 0; i < students.size(); i++) {
    ...
}

for 打得手好酸?

for (int i = 0; i < students.size(); i++) {
    ...
}
for (Student student : students)

英文不潮,但很重要

 

  • 順序:prev / curr / next
    • nextPage
       
  • 回應某個行為:on~
    • onConfigurationChanged()
       
  • 判定:is~ / has~ / need~ / is~able
    • isNullOrEmpty()
    • hasErrors()
    • needSpread()
    • isWritable

英文不潮,但很重要

 

  • 監聽者:~Listener
    • onClickListener
       
  • 獲取 / 設置:get~ / set~
    • getName
    • setName
       
  • 轉換:to~
    • toString

其實可以更簡單

public boolean hasMore() {
    if(list.size() > 0) {
        return true;
    }
    return false;
}

其實可以更簡單

public boolean hasMore() {
    if(list.size() > 0) {
        return true;
    }
    return false;
}
public boolean hasMore() {
    return list.size() > 0;
}

其實可以更簡單

if (user.isLogin()) {
        return "你好棒";
    }
    return "你是誰";
}

其實可以更簡單

if (user.isLogin()) {
        return "你好棒";
    }
    return "你是誰";
}
return (user.isLogin())? "你好棒" : "你是誰";

其實可以更明白

public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
}

public class Calculator {
    public int sub(int a, int b) {
        return a - b;
    }
}

其實可以更明白

public Calculator {
    public class Parameter {
        public int a;
        public int b;
}

public class Calculator {
    public int add(Calculator.Parameter param) {
        return param.a + param.b;
    }
}

public class Calculator {
    public int add(Calculator.Parameter param) {
        return param.a + param.b;
    }
}

其實可以更平坦

if (list != null) {
    for (int i = 0; i < list.size(); i++) {
        ...
    }
}

其實可以更平坦

if (list != null) {
    for (int i = 0; i < list.size(); i++) {
        ...
    }
}
if (list == null) return;

for (int i = 0; i < list.size(); i++) {
    ...
}

我的螢幕真的沒這麼寬

dialogBuilder.setTitle("title").setIcon(icon.jpg).setText("text").setPositiveButton("ok").setNegativeButton("cancel").build();

我的螢幕真的沒這麼寬

dialogBuilder.setTitle("title").setIcon(icon.jpg).setText("text").setPositiveButton("ok").setNegativeButton("cancel").build();
dialogBuilder
    .setTitle("title")
    .setIcon(icon.jpg)
    .setText("text")
    .setPositiveButton("ok")
    .setNegativeButton("cancel")
    .build();

希望大家以後都不用再吃翻譯米糕

程式碼 = 人話

By ChouPeiWen

程式碼 = 人話

tech sharing

  • 962