类命名,我应该命名一个类并创建一个属性还是将该属性放入类名称中

发布于 2024-11-28 15:13:44 字数 216 浏览 3 评论 0原文

我试图了解人们命名类时的考虑因素。您在以下选项之间做出决定的方式是什么。

student = Student.new(:smart)

与简单地使用

student = SmartStudent.new

编辑相比: 我想确实没有正确或错误的答案,这只是我需要决定我要建模的内容的方式。

I'm trying to understand the considerations people use to name classes. What are the ways in which you decide between the following.

student = Student.new(:smart)

vs simply using

student = SmartStudent.new

Edit:
I guess there is really no right or wrong answer its just the way I need to decide what I am modeling.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

疯狂的代价 2024-12-05 15:13:44

一般来说,我喜欢用它们所代表的名词的最通用形式来命名类。因此,在您的示例中,名词是“学生”。 聪明是描述该名词的形容词。这个形容词代表学生的智力。所以我的属性就是智力

这样我就可以:

比尔 = 新学生
Bill.intelligence = 聪明

鲍勃 = 新学生
鲍勃.智力 = 愚蠢

In general I like to name classes at the most general form of the noun that they represent. So in your example the noun is Student. smart is an adjective describing that noun. the adjective represents a Student's intelligence. so my attrribute would be intelligence.

That way I could have:

Bill = new Student
Bill.intelligence = smart

Bob = new Student
Bob.intelligence = stupid

鱼窥荷 2024-12-05 15:13:44

你应该问自己:学生的特质是否真的使一个学生与其他学生不同?

如果没有并且可能的话,我建议您使用您提出的第一个解决方案。一般来说,部署学生类型的层次结构更简单(请参阅组合与继承),因为如果您的学生类型增长,那么您的学生班级可能会激增,从而难以正确处理所有学生。

另一方面,如果一个 Smart 学生类具有真正的自定义行为,并且您想要使用方法重写和类似的东西来对该类执行操作,而不是每次检查该特定类的学生类型,那么继承可以是一个选项。我会远离那个。

您应该向我们提供更多详细信息以获得正确答案。不能对你的问题说简单的是或否,因为这取决于你的设计。

编辑:
还要考虑这一点:学生能拥有的不仅仅是一个属性吗?如果是这种情况,您应该明确使用第一种方法,其他方法可能无法(或至少很棘手)对具有多个属性(例如:聪明和肥胖)的学生类型进行建模。

You should ask your self: does the student's attributes make a student really different from another?

If not and if it is possible, I'd suggest you to use the first solution you proposed. Generally is simpler that deploying a hierarchy of student types (see composition vs inheritance), because if your student types grow, then your student classes may proliferate making difficult to proper handle all of them.

On the other hand, if a Smart student class has a really custom behavior, and you want to use method overriding and stuff like that to perform operations on that classes instead of checking each time the student type of that particular class, then inheritance could be an option. I would stay away from that.

You should give us more details for a correct answer. Can't say simple yes or no to your question, because it depends on your design.

EDIT:
consider also this point: can a student have more than an attribute? If that's the case you should definitively used the first approach, other could be impossible (or at least tricky) modeling a student type that has more than one attribute (example: smart and fat).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文