Item 64: Refer to objects by their interfaces

64. Refer to the interface

It is more flexible to declare the type in the interface.

** All arguments, return values, variables, and fields should be declared as interface types, if any. ** ** The object class is referenced only in the constructor.

Below, we will look at LinkedHashSet, which is an implementation class of the Set interface, as an example.

// Good - uses interface as type
Set<Son> sonSet = new LinkedHashSet<>();

The above is a good example.

// Bad - uses class as type!
LinkedHashSet<Son> sonSet = new LinkedHashSet<>();

The above is a bad example.

In the example declared in the interface, the implementation class can be changed basically without error by simply changing as follows (because only the methods declared in the interface are used).

Set<Son> sonSet = new HashSet<>();

One thing to keep in mind, however, is that code that depends on features that aren't specified in the interface can have the effect of changing the implementation class. For example, if you depended on the LinkedHashSet reordering policy, changing the implementation to HashSet will have an impact.

When there is no proper interface

When there is no proper interface, it is correct to declare by class type.

value class For example, consider a value class that represents a value such as a String or BigInteger. The value class is unlikely to have multiple implementations. Also, it is a final class, and there is no corresponding interface. value class is a good type for arguments, variables, fields and return values.

When using a class-based framework

You are using a class-based framework, and sometimes the appropriate underlying type is a class rather than an interface. Even in such a case, it is better to inherit a suitable class (generally abstract). OutputStream of java.io corresponds to this.

There is no suitable interface, but a method suitable for the implementation class is implemented

For example, PriorityQueue has a comparator method, but the Queue interface does not. If you write a program that depends on the comparator method, refer to PriorityQueue. However, such cases are rare.

The above three cases are not exhaustive and convey somehow the scenes referenced in the class.

** If you don't have a suitable interface, you should refer to the most abstract class that has the desired functionality. ** **

Recommended Posts

Item 64: Refer to objects by their interfaces
Item 65: Prefer interfaces to reflection
Item 41: Use marker interfaces to define types