抽象类是一个好的实践吗?

发布于 2024-08-21 13:23:30 字数 231 浏览 5 评论 0原文

我有这样的场景:

这两个类具有以下属性:

  • 表 [Id,Name,Parent_Id]
  • 字段 [Id,Name,Creation_Time,Creation_Date]

制作一个抽象类来实现 ID 和 NAME 的属性和属性是一个好习惯吗?这样我就可以节省一些编写代码的时间;或者重写每个类的每个属性和属性是否更好?或者也许使用接口?

谢谢。

I have this scenario:

This two clases with this attributes:

  • Table [Id, Name, Parent_Id]
  • Field [Id, Name, Creation_Time, Creation_Date]

Is it a good practice to make an Abstract Class to implemet the attributes and properties for ID and NAME so that I save some time writting code; or is it better to rewrite each attribute and property on each class? Or maybe use an Interface?

Thanks.

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

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

发布评论

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

评论(3

在你怀里撒娇 2024-08-28 13:23:30

我认为这两种选择都没有意义。如果您使用抽象类,当有人查看从您的抽象类继承的类时,他们可能会费尽心思去发现该信息的位置。这可能是继承中最糟糕的部分:将类中的重要细节隐藏在继承链的某个位置。

接口是类必须遵守的一种契约,以便通常可以被其他机制使用。一个很好的例子是迭代器,这样的类通常需要一个“next”方法。如果类的实例订阅了需要它具有“next”方法的接口,则可以保证该类的实例可以被迭代。这样,想要迭代您的实例的机制就可以知道它会起作用。如果这对您想做的事情没有意义,也许不要使用它。

I don't think either choice make sense. If you use an abstract class, when someone looks at a class that inherits from your abstract class they may be at pains to discover just where that information is. It's probably the worst part about inheritance: hiding important details in a class up in the inheritance chain somewhere.

An interface is kind of a contract that a class has to adhere to so that, usually, it can be used by some other mechanism. A great example is an iterator, such a class usually needs a "next" method. You guarantee that an instance of a class can be iterated if it subscribes to an interface which requires it to have a "next" method. That way a mechanism that wants to iterate through your instance can know it will work. If that's not making sense for what you want to do, maybe don't use this.

一身仙ぐ女味 2024-08-28 13:23:30

子类与其父类应该有“is a”关系。表和字段看起来是如此不同的实体,因此应该避免继承。但另一方面,它们可以有一个共享基类,如 DatabaseObject(或类似的东西),它实现了公共属性。但如果这看起来太人为,我会避免在这些简单的情况下继承。

Subclasses should have an "is a" relationship with their parent class. Table and field seem so different entities that inheritance should be avoided. But on the other hand, they could have a shared base class like DatabaseObject (or something like that) which implements the common attributes. But if this seems too artificial, I would avoid inheritance in these simple cases.

蓦然回首 2024-08-28 13:23:30

如果你想解决代码重复的问题,你可以使用它。

但如果你能使用它,从逻辑方面来看,你必须明白所有扩展这个抽象类的类都必须有共同点。

If you want to solve a problem of code repitition of couse you can use it.

But if you can use it, from the logic side, you must undestand that all classes extends this abstarct class must have smth common.

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