【问题标题】:Clean Coding Use Attributes from Subclasses in Superclass清洁编码使用超类中子类的属性
【发布时间】:2021-09-01 12:45:21
【问题描述】:

我想在编码和编写干净的代码方面做得更好。 我有一个超类 Document 和子类,例如DocA、DocB、DocC等 每个子类 Document 都有这个单独的属性 egg。路径、编号等 我想在像 printPath() 这样的超类中编写一个方法。我想出了两种方法。

  1. 覆盖超类(DocA)的属性
  2. 将元素传递给方法 (DocB)
class Document {
    String path;

    public String getPathA() {
        return path;
    }

    public String getPathB(String path) {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }
}

class DocumentA extends Document{
    String path = "pathA";

    DocumentA () {
        setPath(this.path);
    }
}

class DocumentB extends Document{
    String path = "pathB";

    public String getPathB(){
        return super.getPathB(path);
    }
}

有更好/更清洁的方法吗?或者更确切地说,其中一种方式可以吗?

【问题讨论】:

  • 从这段代码中并不清楚为什么继承是有用的。或者你想要做什么。老实说,我发现很难理解这一切的目的。
  • 如果路径变量是DocumentA和DocumentB中的一个常量,你可以把Document变成一个抽象类并创建一个抽象方法'getPath',然后DocA和DocB只提供实现来返回它们的常量. printPath 方法只会调用 getPath
  • 如果超类知道只有子类知道的概念,我不会认为它是一个干净的设计或干净的代码。如果它们只在子类中有意义,请将它们保留在那里。如果它们对所有人都有意义,请将它们拉起并可能覆盖特定行为的方法。
  • 为什么需要子类?根据您到目前为止告诉我们的内容,这些子类似乎没有必要。相反,Document 类可以有一个带有 getter/setter 的 path,然后 a/b/c 可以是 Document 类的实例。例如。 Document docA = new Document("path/to/a");

标签: java subclass superclass


【解决方案1】:
  1. Document.getPathA()Document.getPathB() 一开始就不应该存在,因为 Document 不应该知道 DocumentADocumentB

  2. 如果 Document 已经有 path,那么如果 DocumentA 和 DocumentB 也有一个变量 path,那么它看起来很像糟糕的设计,大概具有相同的功能。

如何改进:

如果所有文档都有路径,请始终使用该路径并通过myDocument.getPatch() 检索它。如果 DocumentA 有一些特殊的附加功能,您可以像这样覆盖该方法:

class DocumentA extends Document { 
    @Override public String getPath() {
         return someSpecialPath;
    } 
}

如果不是所有文档都有路径,但只有一些,

  1. 为所有需要路径的文档创建第二个中间类,例如 class DocumentWithPath extends Document 作为父类
  2. 或者干脆留给基类在需要时实现

另一种情况:

  • 如果 MOST 文档有路径
  • 他们都必须提供专门的实现
  • 并且该 Document 需要知道路径,

你可以写一个抽象方法:

abstract class Document { // 'abstract shows that this class itself cannot be instantiated, but its fully implemented children can
    abstract public String getPath();
    String toString() { 
        return "My Path is: " + getPath(); // this calls the abstract method, implemented by any instantiable subclass
    }
}

class DocumentA extends Document { 
    @Override public String getPath() {
         return someSpecialPath;
    } 
}

这会强制所有子类(可以实例化)以自己的方式实现getPath()

编辑: 如果您将父级中的path 定义为protected

class Document {
    protected File path;
}

然后您可以从所有子类访问path,就好像它是它们自己的成员变量一样。

【讨论】:

    猜你喜欢
    • 2021-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-09
    • 1970-01-01
    • 1970-01-01
    • 2017-04-18
    相关资源
    最近更新 更多