恒定界面反模式澄清 [英] Constant Interface Anti-Pattern Clarification

查看:169
本文介绍了恒定界面反模式澄清的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚读到某个地方有一个带有常见项目常量的界面是不好的做法,也被称为常数界面反模式。如果我理解正确,提供的原因是,一旦实现,该类将公开这些常量。

I just read somewhere that having an interface with common project constants is bad practice and also known as the Constant Interface Anti-Pattern. If I understood this correctly, the reason provided was that once implemented, the class would expose these constants to the public.

嗯,我不明白需要'首先实施'。是不是可以直接使用这些静态常量?那么为什么我必须经历 import static 的麻烦,当我可以做类似的事情时:

Well, I don't understand the need for 'implementing' in the first place. Isn't it possible to just use these static constants directly? So why do I have to go through the trouble of import static when I can do something like:

interface Constants {
    public static final int FOO_1 = 1;
    public static final int FOO_2 = 2;
}

public class Test {
    public static void main(String[] args) {
        System.out.println(Constants.FOO_2);
    }
}

我很感激任何指导,以帮助我理解这一点更多。

I would appreciate any guidance to help me understand this a bit more.

推荐答案

我意识到...如果需要,接口可以由个人实现,为上面提到的问题(即命名空间污染,非常规使用,通过公共API暴露)。因此,最好完全阻止实现界面的能力。因此,使用私有构造函数的 final 类更合适,因此无法实例化/扩展它。

I realised... the fact that the interface CAN be implemented by an individual if desired, leaves room for the issues pointed out above (i.e. namespace pollution, non-conventional use, exposure through public API ). So it's best to prevent the ability to implement the interface altogether. Hence, it's more appropriate to have a final class with a private constructor so that it can't be instantiated / extended.

public final class Constants
{
      // to restrict instantiation
      private Constants() {}

      public static final double PI = 3.14159;
      public static final double PLANCK_CONSTANT = 6.62606896e-34;
}

...并将其与结合使用import static

import static Constants.PLANCK_CONSTANT;
import static Constants.PI;

public class Calculations
{   
      public double getReducedPlanckConstant()
      {       
            return PLANCK_CONSTANT / ( 2 * PI );   
      }
}

这篇关于恒定界面反模式澄清的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆