抽象类中的空方法

时间:2022-02-01 11:37:57

I have just installed PMD to analyze my Java project. Really nice tool, highly recommended. Anyways, I got a few errors saying:

我刚刚安装了PMD来分析我的Java项目。非常好的工具,强烈推荐。无论如何,我有一些错误说:

"An empty method in an abstract class should be abstract instead"

“抽象类中的空方法应该是抽象的”

I checked out PMD documentation and the explanation says:

我检查了PMD文档,解释说:

as developer may rely on this empty implementation rather than code the appropriate one

因为开发人员可能依赖于这个空实现而不是编写适当的实现

So I think I understand the reason behind this code style error, but consider the following scenario: I have an abstract class called Entity. This class has a boolean method with default implementation. (controls whether to delete its related entities upon deletion). Only a few of the derived classes override this default behavior to true.

所以我认为我理解这种代码样式错误背后的原因,但请考虑以下场景:我有一个名为Entity的抽象类。该类具有默认实现的布尔方法。 (控制是否在删除时删除其相关实体)。只有少数派生类将此默认行为覆盖为true。

Should I remove the default implementation and force all deriving classes to declare their behavior? Do you really think this pattern is such a bad practice?

我应该删除默认实现并强制所有派生类声明其行为吗?你真的认为这种模式是一种不好的做法吗?

Clarification: PMD treats a method with single return statement as empty.

澄清:PMD将单个return语句的方法视为空。

2 个解决方案

#1


I think it's just a guideline. It tells you so that you might want to reconsider your design, but if your design already makes perfect sense, there's no reason to obey a software instead of your brain.

我认为这只是一个指导方针。它告诉你,你可能想重新考虑你的设计,但如果你的设计已经完全合理,那么没有理由服从软件而不是你的大脑。

#2


If you are on Java 1.8, you can make Entity an interface instead of an abstract class and write a default implementation for your method in it.

如果您使用的是Java 1.8,则可以将Entity设置为接口而不是抽象类,并为其中的方法编写默认实现。

public interface Entity {
    default boolean yourMethod() {
        //default implementation ...
    }
}

You can use this for reference : https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html

您可以将其用作参考:https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html

#1


I think it's just a guideline. It tells you so that you might want to reconsider your design, but if your design already makes perfect sense, there's no reason to obey a software instead of your brain.

我认为这只是一个指导方针。它告诉你,你可能想重新考虑你的设计,但如果你的设计已经完全合理,那么没有理由服从软件而不是你的大脑。

#2


If you are on Java 1.8, you can make Entity an interface instead of an abstract class and write a default implementation for your method in it.

如果您使用的是Java 1.8,则可以将Entity设置为接口而不是抽象类,并为其中的方法编写默认实现。

public interface Entity {
    default boolean yourMethod() {
        //default implementation ...
    }
}

You can use this for reference : https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html

您可以将其用作参考:https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html