简体   繁体   English

只有一个 String 字段的模型类

[英]Model class with only one String field

i have a class, which i would like refactor looks like this:我有一个类,我希望重构如下所示:

class PersonId {
    String personId
    //getter, setter
}

class Person{

   PersonId personId;
   //other fields...
}

It seems for me, that a class PersonId is unnecessary cause it contains only one string-field with a id-value.在我看来,PersonId 类是不必要的,因为它只包含一个带有 id 值的字符串字段。 Actually this string-field could be placed directly into class Person.实际上,这个字符串字段可以直接放入类 Person 中。 Is there a basic rule for class-design, that would allow a class 'PersonId'?是否有类设计的基本规则,允许类“PersonId”? Which disadvantage has a class 'PersionId' ?哪个缺点有一个类 'PersionId' ?

As far as I know, if your class PersonId ONLY contains this String, then you can place it directly inside your Person class.据我所知,如果你的类 PersonId包含这个字符串,那么你可以将它直接放在你的 Person 类中。 On the other hand, if your class contains more than that (method or more attributes) then it is usefull.另一方面,如果您的类包含更多(方法或更多属性),那么它很有用。

Then only advantage I could see is that you can give the same PersonId to multiple Person, and if you modifie one, then it modifies the others :那么我能看到的唯一优点是您可以将相同的 PersonId 提供给多个 Person,如果您修改一个,则它会修改其他人:

Person p1 = new Person();
Person p2 = new Person();
PersonId id = new PersonId();
id.id = "abc";
p1.id = id;
p2.id = id;
System.out.println(p1.id.id); // abc (for p1 & p2)
id.id = "foo";
System.out.println(p1.id.id); // foo (for p1 & p2)
id.id = "ba";
System.out.println(p2.id.id); // ba (for p1 & p2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM