我經常遇到這樣的情況:API定義了一個類,它只包含其與專用setter和getters相關的字段。只有「Setter」和「Getters」的類 - 優點
但是,他們有特定的角色。所以從現實生活(OOP)的角度來看他們實際上分別是有意義。我最後一次偶然發現這是schema in Olingo。它被用來設置一些屬性。
我的問題是,從技術的角度來看,「僅設置變量」還是有優勢嗎?或者這些類只用于堅持OOP(並且有乾淨的代碼等)?
編輯:請注意,我不是問爲什麼我們使用「Setters」和「Getters」。試着從另一個角度來看待它。假設您必須定義三個字符串以在您的代碼中進一步使用它們。您決定創建一個將這三個字符串存儲爲字段併爲其定義setter和getter的類,而不是將它們定義爲「即時」私有字符串。這樣做有沒有技術上的優勢?
的「模式」示例代碼:
public List<Schema> getSchemas() throws ODataException {
List<Schema> schemas = new ArrayList<Schema>();
Schema schema = new Schema();
schema.setNamespace(NAMESPACE);
List<EntityType> entityTypes = new ArrayList<EntityType>();
entityTypes.add(getEntityType(ENTITY_TYPE_1_1));
entityTypes.add(getEntityType(ENTITY_TYPE_1_2));
schema.setEntityTypes(entityTypes);
List<ComplexType> complexTypes = new ArrayList<ComplexType>();
complexTypes.add(getComplexType(COMPLEX_TYPE));
schema.setComplexTypes(complexTypes);
List<Association> associations = new ArrayList<Association>();
associations.add(getAssociation(ASSOCIATION_CAR_MANUFACTURER));
schema.setAssociations(associations);
List<EntityContainer> entityContainers = new ArrayList<EntityContainer>();
EntityContainer entityContainer = new EntityContainer();
entityContainer.setName(ENTITY_CONTAINER).setDefaultEntityContainer(true);
List<EntitySet> entitySets = new ArrayList<EntitySet>();
entitySets.add(getEntitySet(ENTITY_CONTAINER, ENTITY_SET_NAME_CARS));
entitySets.add(getEntitySet(ENTITY_CONTAINER, ENTITY_SET_NAME_MANUFACTURERS));
entityContainer.setEntitySets(entitySets);
List<AssociationSet> associationSets = new ArrayList<AssociationSet>();
associationSets.add(getAssociationSet(ENTITY_CONTAINER, ASSOCIATION_CAR_MANUFACTURER, ENTITY_SET_NAME_MANUFACTURERS, ROLE_1_2));
entityContainer.setAssociationSets(associationSets);
entityContainers.add(entityContainer);
schema.setEntityContainers(entityContainers);
schemas.add(schema);
return schemas;
}
添加了含有正好我質疑內容的例子。考慮將類「測試」作爲包含兩個字段「a」和「b」以及適用的「setters」和「getters」的類。 簡單的例子:
public class Main {
public static void main(String[] args) {
//Version 1: Common practice
test asdf = new test();
asdf.setA("asdf");
asdf.setB("asdf2");
//Doing something with "asdf" and "asdf2"
//Version 2: My request
String a = "asdf";
String b = "asdf2";
//Doing something with "asdf" and "asdf2"
}
}
那麼你不能有一個接口上的字段,只有方法,所以這是一個很大的優勢,再加上有整個Java Bean自動佈線的事情。但是我認爲這個整個概念被一些常見的網站博客帖子/論文所深入報道,我確信有人有一個頭腦:) –
是的,如果你真的改變setter方法做一些額外的工作,或檢查如果變量的新值在範圍內。想象你必須這樣做,並且你會將變量改爲private而不是public,並且設置setter方法來在設置或獲取變量之前或之後實現這些額外的任務。您需要更改直接分配變量的整個代碼。 – SomeJavaGuy
安裝人員非常適合調試。它會告訴你到底什麼時候變量改變了值。你不需要在代碼中設置斷點。 – cup