Jump to content

Marker interface pattern

From Alfawiki
Adapted from the English Wikipedia article Marker interface pattern, available under CC BY-SA 4.0Updated 9 August 2025

The marker interface pattern represents a design pattern applied in programming languages that support run-time type information, used to link metadata to a class when explicit metadata mechanisms are absent.

A class adopts a marker interface—also known as a tagging interface—which is an interface without any methods. Functions operating on instances check for the implementation of this interface. Unlike conventional interfaces that define mandatory methods, a marker interface serves solely as an indicator of particular behavior. There are hybrid interfaces that combine marker characteristics with method declarations; however, improper use of these can lead to ambiguity.

Example

Within Java, the following interface exemplifies this concept:

<syntaxhighlight lang="java"> package java.io;

public interface Serializable { } </syntaxhighlight>

By implementing this interface, a class signals that its non-transient fields are eligible for serialization. The writeObject0(Object,boolean) method verifies the presence of Serializable using instanceof; if the check fails, a NotSerializableException is thrown.

Critique

One limitation of marker interfaces is that their contracts are inherited by subclasses and cannot be revoked. For instance, subclasses not intended for serialization must explicitly throw a NotSerializableException.

Contemporary programming languages have addressed this drawback by introducing direct metadata capabilities:

  • Both the .NET Framework and Java (from version 5 onwards) provide custom attributes or annotations which allow attaching metadata to classes, fields, and methods accessible through reflection.
  • In Python, frameworks such as Zope and Plone utilize interfaces as metadata markers, enabling subclasses to limit inherited interfaces via implementsOnly.

See also

  • Design marker for additional information related to this pattern.

Further reading

Effective Java authored by Joshua Bloch.