zoukankan      html  css  js  c++  java
  • Effective Java 52 Refer to objects by their interfaces

    Principle

    1. If appropriate interface types exist, then parameters, return values, variables, and fields should all be declared using interface types. The only time you really need to refer to an object's class is when you're creating it with a constructor.

      // Good - uses interface as type

      List<Subscriber> subscribers = new Vector<Subscriber>();

    2. If you depend on any special properties of an implementation, document these requirements where you declare the variable.

      One caveat

      If the original implementation offered some special functionality not required by the general contract of the interface and the code depended on that functionality, then it is critical that the new implementation provide the same functionality.

    3. It is entirely appropriate to refer to an object by a class rather than an interface if no appropriate interface exists.

      Examples:

    • Value classes - String, BigDecimal
    • Class-based framework - java.util.TimerTask
    • Classes that implement an interface but provide extra methods not found in the interface - LinkedHashMap

      Summary

      In practice, it depends whether a given object has an appropriate interface. If it does, your program will be more flexible if you use the interface to refer to the object; if not, just use the least specific class in the class hierarchy that provides the required functionality.

  • 相关阅读:
    SSL评测
    EF+SQLSERVER控制并发下抢红包减余额(改进)
    关于游标嵌套时@@FETCH_STATUS的值
    windows下限制Redis端口只能由本机访问
    windows下配置Redis
    Node.js 使用gm处理图像
    Git 与其他系统
    git-svn 简易 操作指南
    git-svn — 让git和svn协同工作
    Git和SVN共存的方法
  • 原文地址:https://www.cnblogs.com/haokaibo/p/refer-to-objects-by-their-interfaces.html
Copyright © 2011-2022 走看看