java类只有“setter”和“getter”的优点
我经常遇到这样的情况,一个API定义了一个类,该类只由它的字段和适当的setter和getter组成
然而,他们扮演着特殊的角色。所以从现实生活(OOP)的角度来看,它们实际上是有意义的。我最后一次在这个问题上绊倒是schema in Olingo。它用于设置一些属性
我的问题是,从技术角度来看,与“只设置变量”相比,这些类有什么优势吗?还是这些类只用于坚持OOP(并且有干净的代码等等)
编辑:请注意,我不是在问为什么我们要使用“setter”和“getter”。试着从另一个角度看问题。假设您必须定义三个字符串,以便在代码中进一步使用它们。您决定创建一个类,将这三个字符串存储为字段,并为它们定义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;
}
添加了一个例子,其中正好包含我所质疑的内容。将类“test”视为包含两个字段“a”和“b”的类,以及指定的“SETTER”和“GETTER”。 简单的例子:
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"
}
}
共 (0) 个答案