2014-02-24 43 views
0

也許我在網站的選擇上犯了一個錯誤。'setters'(set-methods)有什麼用?

對不起,我的英語

直到最近,我認爲有在哪些字段設置一次一類寫settersgetters沒有任何意義。而不是setters\getters我使用public constant字段(或在Java中爲final)並通過構造函數設置字段。

但是我最近遇到了這種情況,當這種方法證明是非常不舒服的。類有很多領域(5-7個領域)。

我首先意識到0​​的好處。

而不是做這個的:

class Human { 
    public final int id; 
    public final String firstName; 
    public final String lastName; 
    public final int age; 
    public final double money; 
    public final Gender gender; 
    public final List<Human> children; 

    Human(int id, String firstName, String lastName, int age, double money, Gender gender, List<Human> children) { 
    // set fields here 
    } 
} 


class HumanReader { 
    Human read(Input input) { 
     int id = readId(input); 
     String firstName = readFirstName(input); 
     // ... 
     List<Human> children = readChildren(input); 
     return new Human(id, firstName, lastName, age, money, gender, children); 
    } 
} 

我開始使用下一個解決方案:

interface Human { 
    int getId(); 
    String firstName; 
    // ... 
    List<Human> getChildren(); 
} 

class HumanImpl implements Human { 
    public int id; 
    public String firstName; 
    // ... 
    public List<Human> children; 

    public int getId() { 
     return id; 
    } 

    public String getFirstName() { 
     return firstName; 
    } 

    // ... 

    public List<Human> getChildren() { 
     return children; 
    } 
} 


class HumanReader { 

    Human read(Input input) { 
     HumanImpl human = new HumanImpl(); 
     human.id = readId(input); 
     human.firstName = readFirstName(input); 
     // ... 
     human.children = readChildren(input); 
     return human; 
    } 
} 

我認爲第二種解決方案是更好的。它沒有混淆參數順序的複雜構造函數。

但是setters有什麼用?我仍然無法理解。或者他們需要統一?

回答

0

使用getter和setter方法的要點是封裝訪問這些值。因此,如果 您的基礎數據結構發生變化,您將不必更改其餘的代碼。想象一下,例如,你的人類突然依賴於一個數據庫...

雖然getters和setters提供了一個小的保護以防止改變,但它們仍然反映了非常多的數據結構,所以你仍然可能進入麻煩。最好的解決方案是儘量避免獲取者和設置者,而是提供該類客戶實際需要的服務。 (即在人類的情況下,考慮使人能夠將自己呈現給接口)

0

在這裏很簡單的解釋,想想你需要改變別的東西(可能是UI或數據),每次你改變(設置)一個屬性的情況。然後,最簡單的實現方法就是在setter中完成它。

而這裏的的原因,您可能希望使用它一個很好的列表,

Why use getters and setters?