Java 接口常量反模式及如何定义 Java 常量

初学 Java 的人很不经意间就会把常量定义在接口中,大概唯一的理由是接口不能实例化,而使用接口中定义的常量也是不用附着在实例上的。这主要还是 JDK 本身给我们做了很多这样的榜样, 如  java.io.ObjectStreamConstans,多是出现在 Enum 类型到来之前。

其实 Java 的接口常量是一种反模式,理由如下:

1. 接口是不能阻止被实现或继承的,也就是说子接口或实现中是能够覆盖掉常量的定义(重名),这样通过父,子接口(或实现) 去引用常量是可能不一致的
2. 同样的,由于被实现或继承,造成在继承树中可以用大量的接口, 类 或实例去引用 同一个常量,从而造成接口中定义的常量污染了命名空间。(Java 编译器竟然允许使用实例去引用类变量)
3. 接口暗含的意思是:它是需被实现的,代表着一种类型,它的公有成员是要被暴露的 API。而在接口中定义的常量说不上是 API

4. 这点有些重复,Java 允许通过子类去引用父类中定义的常量,各级对像实例去引用父类的常量,所以这会造成相当的混乱不堪。定义的常量不能保证单一的引用方式。

参见: Effective java 第 19 条: 接口只用于定义类型

既然接口中不适于定义常量,那么该在何处为常量安家呢?接口为 实现/继承 而生,如果放在类中,并且这个类是 final,且封闭掉构造方法就行。于是我们先前的接口常量定义 阅读全文 >>

fish 2.2.0 (July 12, 2015) 支持 vi 模式

随着 Mac 下终端的使用日益增多,系统默认的 bash 已经满足不了需求了,于是有了更为强劲的 fishzsh,以及它们各自的强心剂 Oh-My-FishOh-My-Zsh. 我的选择是 Fish 和 Oh-My-Fish。

到目前为止,最新的 fish 2.2.0 于 2015 年 7 月 12 日发布,Release notes 如下 http://fishshell.com/release_notes.html,其中显著改变有:

  • Abbreviations: the new abbr command allows for interactively-expanded abbreviations, allowing quick access to frequently-used commands (#731).
  • Vi mode: run fish_vi_mode to switch fish into the key bindings and prompt familiar to users of the Vi editor (#65).
  • New inline and interactive pager, which will be familiar to users of zsh (#291).
  • Underlying architectural changes: the fishd universal variable server has been removed as it was a source of many bugs and security problems. Notably, old fish sessions will not be able to communicate universal variable changes with new fish sessions. For best results, restart all running instances of fish.
  • The web-based configuration tool has been redesigned, featuring a prompt theme chooser and other improvements.
  • New German, Brazilian Portuguese, and Chinese translations.

我对第二点比较感兴趣,即增加了 vi 模式,在 fish 下运行 fish_vi_mode 命令,或者在 ~/.config/fish/config.fish 中加上 fish_vi_mode 便自动进入 vi 模式。 阅读全文 >>