Static Import https://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html

In order to access static members, it is necessary to qualify references with the class they came from. For example, one must say:

double r = Math.cos(Math.PI * theta);

In order to get around this, people sometimes put static members into an interface and inherit from that interface. This is a bad idea. In fact, it's such a bad idea that there's a name for it: the Constant Interface Antipattern (see Effective Java Item 17). The problem is that a class's use of the static members of another class is a mere implementation detail. When a class implements an interface, it becomes part of the class's public API. Implementation details should not leak into public APIs.

The static import construct allows unqualified access to static members without inheriting from the type containing the static members. Instead, the program imports the members, either individually:

import static java.lang.Math.PI;

or en masse:

import static java.lang.Math.*;

Once the static members have been imported, they may be used without qualification:

double r = cos(PI * theta);

The static import declaration is analogous to the normal import declaration. Where the normal import declaration imports classes from packages, allowing them to be used without package qualification, the static import declaration imports static members from classes, allowing them to be used without class qualification.

So when should you use static import? Very sparingly! Only use it when you'd otherwise be tempted to declare local copies of constants, or to abuse inheritance (the Constant Interface Antipattern). In other words, use it when you require frequent access to static members from one or two classes. If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import. Readers of your code (including you, a few months after you wrote it) will not know which class a static member comes from. Importing all of the static members from a class can be particularly harmful to readability; if you need only one or two members, import them individually. Used appropriately, static import can make your program more readable, by removing the boilerplate of repetition of class names.

Constant interface - Wikipedia https://en.wikipedia.org/wiki/Constant_interface

Constant interface

From Wikipedia, the free encyclopedia
 
 

Jump to navigationJump to search

In the Java programming language, the constant interface pattern describes the use of an interface solely to define constants, and having classes implement that interface in order to achieve convenient syntactic access to those constants. However, since constants are very often merely an implementation detail, and the interfaces implemented by a class are part of its exported API, this practice amounts to putting implementations details into the API, which was considered inappropriate by, e.g., Java designer Joshua Bloch.[1] In general, collecting system constants into classes independent of behaviour might create a poor object-oriented design because it is often a sign of low cohesion. It is for these reasons that implementing constants interfaces may be considered to be an anti-pattern.

Use of this pattern has a few other downsides:

  1. It pollutes the class namespace with read-only variables that may not be of use.
  2. Contrary to the compile-time tactical utility of implementing a constants interface, the incidental run-time artifacts have little practical purpose (cf. marker interfaces which also have no methods but are useful at run-time).
  3. If binary code compatibility is required in future releases, the constants interface must remain forever an interface (it cannot be converted into a class), even though it has not been used as an interface in the conventional sense.
  4. Without an IDE that resolves where the constant are coming from, tracking it back to its containing class or interface can be time consuming.
  5. A variable (representing an instance) of the interface is syntactically no more useful than the interface name itself (since it has no methods).
  6. Unless a developer checks any implemented interfaces when adding a constant to a class, or does so but makes a typo in the new constant's name, the value of a constant can be silently changed. Consider Example 2 below.

Note that the Java libraries use constant interface pattern themselves, proving that it may be a reasonable choice in some situations.[2]

Example 1[edit]

public interface Constants {

	double PI = 3.14159;
double PLANCK_CONSTANT = 6.62606896e-34;
} public class Calculations implements Constants { public double getReducedPlanckConstant() {
return PLANCK_CONSTANT / (2 * PI);
}
}

Example 2[edit]

public interface Constants {

	public static final int	CONSTANT = 1;
} public class Class1 implements Constants { public static final int CONSTANT = 2; // * public static void main(String args[]) throws Exception {
System.out.println(CONSTANT);
}
}

Before the line marked with an asterisk is added, running Class1 prints 1. After adding the line, Class1 prints 2. Both versions compile without warnings or errors.

Alternatives[edit]

Many of the pitfalls of the anti-pattern can be avoided by converting the constants interface to a proper class with no instances:

public final class Constants {

	private Constants() {
// restrict instantiation
} public static final double PI = 3.14159;
public static final double PLANCK_CONSTANT = 6.62606896e-34;
}

This still leaves the original intent of the pattern mostly un-addressed (i.e., there is no syntax for accessing the constants unqualified). However, since Java 5, consider using static import[3] to achieve the same goal:

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

The constants can also be imported en masse by adding a import static Constants.* statement. This achieves the same goals as using an interface, allowing the constants to be referenced without the namespace.

To varying degrees, the issues listed above have now been addressed:

  1. Because static members can be imported specifically, the class namespace need not be polluted with all members of the constants interface.
  2. Run-time and compile-time semantics are more closely aligned when using static imports instead of constants interfaces.
  3. The compiled code has one fewer binary compatibility constraint (that "class Calculations implements Constants").
  4. Because static imports apply only to the current file (and not the whole class hierarchy) it is easier to discover where each static member is declared.
  5. There is less need to declare variables of the constants interface type, and it is potentially clearer that no concrete instances actually exist.

Note however, the changes do nothing to improve the cohesion of the Constants class nor prevent the accidental silent modification of a constant's value, so static imports should not be considered to be a panacea.

References

  1. Jump up^ Bloch, Joshua, Effective Java, 2nd Edition, p. 98
  2. Jump up^ "SwingConstants"
  3. Jump up^ "Static Import"

Static Import Constant interface的更多相关文章

  1. JDK1.5新特性(二)……Static Import

    援引 Static Import - This facility lets you avoid qualifying static members with class names without t ...

  2. 理解使用static import 机制(转)

    J2SE 1.5里引入了“Static Import”机制,借助这一机制,可以用略掉所在的类或接口名的方式,来使用静态成员.本文介绍这一机制的使用方法,以及使用过程中的注意事项. 在Java程序中,是 ...

  3. 理解使用static import 机制

    J2SE 1.5里引入了“Static Import”机制,借助这一机制,可以用略掉所在的类或接口名的方式,来使用静态成员.本文介绍这一机制的使用方法,以及使用过程中的注意事项. 在Java程序中,是 ...

  4. Java Static Import的用法

    在头部使用的imoirt static ***方式叫做静态引入,在Java SE 1.5.0(JDK 5)引入的特性. 官方文档的介绍: 为了访问静态成员,有必要限定它们来自的类的引用.例如,必须这样 ...

  5. 静态导入Static import

    静态导入Static import 要使用静态成员(方法和变量)我们必须给出提供这个静态成员的类. 使用静态导入可以使被导入类的静态变量和静态方法在当前类直接可见,使用这些静态成员无需再给出他们的类名 ...

  6. static import和import的区别

    import static静态导入是JDK1.5中的新特性.一般我们导入一个类都用 import com.....ClassName;而静态导入是这样:import static com.....Cl ...

  7. 静态导入(static import)

    1.传统静态方法的调用方式 定义一个Common类,里面有静态方法和静态常量 package com.example.common; public class Common { public stat ...

  8. import static和import的区别

    import static静态导入是JDK1.5中的新特性.一般我们导入一个类都用 import com.....ClassName;而静态导入是这样:import static com.....Cl ...

  9. Java基础知识强化02:import static 和 import

    1.import static静态导入是JDK1.5中的新特性.一般我们导入一个类都用 import com.....ClassName;而静态导入是这样:import static com..... ...

随机推荐

  1. 深入理解Spark 2.1 Core (十一):Shuffle Reduce 端的原理与源代码分析

    http://blog.csdn.net/u011239443/article/details/56843264 在<深入理解Spark 2.1 Core (九):迭代计算和Shuffle的原理 ...

  2. IBM websphere MQ 消息发送与获取

    一. 所需依赖包,安装 IBM websphere MQ 后,在安装目录下的 java 目录内 import java.io.IOException; import java.util.Propert ...

  3. rip中的连续子网以及不连续子网

    RIPv1 RIPv2 距离矢量2 距离矢量 最大跳计数15 最大跳计数15 有类的 无类的 基于广播的    基于组播224.0.09 不支持VLSM 支持VLSM 无认证 允许MD5认证 不支持不 ...

  4. Java Mail(一):telnet实现发送收取邮件

    http://blog.csdn.net/ghsau/article/details/8602076 ******************************* 最近要做一个解析邮件的东东,就顺便 ...

  5. DelphiXE8FMX工程实现无边框托动(FMX内部方法)

    注意: 可以实现效果,但不知道我的用法对不对(或着说是不是最优化的用法),望高手们指教. 实例代码: unit Unit1; interface uses System.SysUtils, Syste ...

  6. Unix系统编程()信号:概念和概述

    这篇将一口气学完信号的基本概念,但是有很多的细节,所以篇幅较长,请做好心理准备. (他大爷的,一口气没有学完,太懒了) 有以下主题: 各种不同信号及其用途 内核可能为进程产生信号的环境,以及某一进程向 ...

  7. Unix系统编程()复制文件描述符

    Bourne shell的IO重定向语法2>&1,意在通知shell把标准错误(文件描述符2)重定向到标准输出(文件描述符1).因此下列命令将把标准输出和标准错误写入result.log ...

  8. 十步理解Sql

    很多程序员视 SQL 为洪水猛兽.SQL 是一种为数不多的声明性语言,它的运行方式完全不同于我们所熟知的命令行语言.面向对象的程序语言.甚至是函数语言(尽管有些人认为 SQL 语言也是一种函数式语言) ...

  9. Sencha Touch快速入门(译)

    翻译自:http://www.sencha.com/learn/sencha-touch-quick-start/ 1.下载Sencha Touch SDK——下载链接 2.安装Safari或Chro ...

  10. erlang的汉字字符串和二进制的相互转换,并还原成汉字打印

    19> Hanzi = <<"汉字"/utf8>>. <<230,177,137,229,173,151>> 20> i ...