Video in progress

Strong Middle 🧱 OOP and SOLID

How do you choose between a marker interface (`Serializable`, `RandomAccess`) and an annotation?

A marker interface creates a type: you can use it as a parameter type to catch mistakes at compile time and check it with instanceof. An annotation doesn't create a type, but it can go on methods, fields and packages, and it can take extra parameters. Need a type: interface. Need metadata: annotation.

📖 Answer

Examples from the JDK:

  • RandomAccess: Collections.binarySearch checks list instanceof RandomAccess and picks an index-based or an iterator-based algorithm;
  • Serializable: unfortunately, the parameter of ObjectOutputStream.writeObject(Object) is Object, so the main benefit of the marker (a compile-time check) is lost;
  • @FunctionalInterface: an annotation, because it exists for the compiler to check and adds nothing to the type.

In your own code:

public interface Auditable {}                       // marker type

public void record(Auditable entity) { ... }        // you can't pass anything that isn't Auditable

vs

@Target(METHOD) @Retention(RUNTIME)
public @interface Audited { String action(); }      // has a parameter, goes on a method

The strength of annotations is metadata for frameworks: @Transactional(readOnly = true), @Cacheable("rates"). But there is a price: errors show up at runtime, and the behavior isn't visible when you read the code.

The short version of the Effective Java rule: if you want to write "a method that accepts only objects with this mark", use a marker interface. If you need to mark elements other than classes, or pass configuration, use an annotation.