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.

  • 相关阅读:
    [转]Go语言中的make和new
    Python中的get和set方法
    协程是个啥玩意
    聊聊Python中的is和==
    聊聊Python中的闭包和装饰器
    聊聊Python中的生成器和迭代器
    聊聊动态语言那些事(Python)
    在mac上安装svn客户端
    关于mac mini组装普液晶显示器
    IOS 日志输出控制
  • 原文地址:https://www.cnblogs.com/haokaibo/p/refer-to-objects-by-their-interfaces.html
Copyright © 2011-2022 走看看