About communication between client and server

What is Data Transfer Object(DTO) ?

  今天要來探討所謂的Data Transfer Object(DTO),大家可能會問這是什麼? 有在寫程式的朋友應該對於參數等等的傳遞不陌生,通常我們在寫小程式的時候,傳遞參數或其他需要的資料可能會直接傳遞就好,但是當程式在2個程序(process)間傳遞參數或程式架構橫跨使用者端(Client)與伺服器端(Server)時,傳輸資料卻變得很重要的一個課題,假設我們需要傳輸的參數有5個,就要傳遞五次,每傳遞一次變數就是要將參數從一端(client或server)傳到另外一端,走完一整趟的路程(round-trip),每多一個參數就會多一趟的成本,如果參數的數量一多,執行效能與傳輸的效益就會大大降低,而Data Transfer Object 就可以解決這個問題,將要傳遞的參數或資料放到一個物件一起傳輸,這樣一來就能一次取得所需的大量資料。

  再來,我們在寫一般寫程式的時候也會常用到Data Transfer Object,為什麼會用它呢?  原因是我們如果要傳遞的參數一多,要呼叫某個method或function等等時,會讓程式碼看起來相當雜亂,進而使得我們不好閱讀,因此降低程式的可讀性(Readable),而如果在此用Data Transfer Object的話,可以讓程式更好理解,增加可讀性,通常我們會將我們需要的資料欄位的意義寫下來再對應其他API的欄位(如果有使用的話),通常我們會在Object-oriented(OOP /物件導向)的程式語言用class來將需要用的資料做定義,並設getter跟setter來讀取該物件裡面的資料或參數。

  以下是一段java程式碼定義的Data Transfer Object(DTO)
//這是一段由java 定義的DTO,是定義檔案資訊傳遞相關的Object,其中包括檔名、檔案內容、網址、檔案類型
public class Document {
    private String fileName;
    private String content;
    private String url;
    private String type;

    public static Document valueOf(JSONObject jsonObject) throws JSONException {
        Document doc = new Document();
        doc.fileName = jsonObject.getString("Name");
        doc.content = jsonObject.getString("odata.id");
        doc.timeLastModified = jsonObject.getString("TimeLastModified");
        doc.url = jsonObject.getString("Url");
        doc.type = jsonObject.getString("odata.type");
        return doc;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getFileName() {
        return title;
    }

    public void setFileName(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

**P.S. / Reference:  Data Transfer Object wiki entry
           有關Design Pattern中提到的DTO

results matching ""

    No results matching ""