Patternadvanced
Marker interface
Also called marker interface pattern, tagging interface, tag interface, marker trait.
A marker interface is an interface with no methods. A class implements it only to say that it has a property, and code that receives an object tests for the interface.
- Family
- structural-design
- Intent
- Attach a property to a class with an interface that declares no members, so that code can test for the property with a type check at run time or with a type bound at compile time.
- Also called
- Tagging interface
Intent
Attach a property to a class with an interface that declares no members. The class implements the interface only to say that it has the property, and code that receives an object tests for the interface.1
Problem
A logger writes each value it receives. Some values are secrets, such as a password or an API key, and the logger must not write them. The logger cannot know every secret class, and the secret classes have nothing in common that the logger could call.
The forces are these:
- The property is a fact about the class, not a behaviour. There is no method to call.
- The code that tests the property is far from the classes that have it.
- The language has types and type checks, but perhaps no other way to attach data to a class.
Solution
Declare an empty interface, and let each class with the property implement it. The code that needs the property tests whether an object is an instance of the interface.
interface Sensitive { } (no members)
class Password implements Sensitive class Username
| |
v v
log(value): value instanceof Sensitive ? "[redacted]" : value
The pattern needs a language with type information at run time, or a type system that can check the interface at compile time. It gives a way to associate metadata with a class where the language has no direct support for metadata.1
The Java standard library has three well-known markers:
| Interface | What it marks |
|---|---|
java.io.Serializable |
the serialization interface has no methods or fields and serves only to identify the semantics of being serializable2 |
java.lang.Cloneable |
it is legal for Object.clone() to make a field-for-field copy; without it, clone throws CloneNotSupportedException3 |
java.util.RandomAccess |
a List supports fast, generally constant-time, random access4 |
Example
The example files show one logger in each language. Password and ApiKey carry the marker, and Username does not. The logger writes each value, and writes [redacted] for a marked value:
user: ann
password: [redacted]
api key: [redacted]
The marker takes a different form in each language:
| Language | Marker | Test |
|---|---|---|
| Python | an empty class | isinstance at run time |
| JavaScript | a Symbol property on the class |
the in operator |
| TypeScript | an interface with a unique symbol brand |
the in operator, which also narrows the type |
| Java | an empty interface | instanceof |
| C# | a custom attribute, as CA1040 advises5 | GetCustomAttribute |
| C++ | a type trait specialized for each marked type | if constexpr at compile time |
| Go | an interface with one unexported, empty method | a type assertion |
| Rust | a trait with no items | a trait bound at compile time |
Go and TypeScript cannot use a truly empty interface. In Go, all types implement the empty interface, so a marker needs at least one method.6 The go/ast package uses an unexported method, exprNode(), so that only expression nodes can be assigned to an Expr.7 In TypeScript, the empty object type {} means any value that is defined, because of structural typing.8 A brand property with a unique symbol fixes this.
class Sensitive:
"""Marker: the value must not be written to a log."""
class Username:
def __init__(self, value: str) -> None:
self.value = value
class Password(Sensitive):
def __init__(self, value: str) -> None:
self.value = value
class ApiKey(Sensitive):
def __init__(self, value: str) -> None:
self.value = value
def log(label: str, item: Username | Password | ApiKey) -> None:
shown = "[redacted]" if isinstance(item, Sensitive) else item.value
print(f"{label}: {shown}")
log("user", Username("ann"))
log("password", Password("hunter2"))
log("api key", ApiKey("k-123"))
user: ann
password: [redacted]
api key: [redacted]
- Verdict: idiom. An empty class works as the marker, and
isinstancetests it at run time. - A subclass of a marked class is marked too, and it cannot remove the marker.
#include <iostream>
#include <string>
#include <type_traits>
struct Username { std::string value; };
struct Password { std::string value; };
struct ApiKey { std::string value; };
// The marker is a trait outside the classes.
template <class T> struct is_sensitive : std::false_type {};
template <> struct is_sensitive<Password> : std::true_type {};
template <> struct is_sensitive<ApiKey> : std::true_type {};
template <class T>
void log(const std::string& label, const T& item) {
if constexpr (is_sensitive<T>::value) {
std::cout << label << ": [redacted]\n";
} else {
std::cout << label << ": " << item.value << "\n";
}
}
int main() {
log("user", Username{"ann"});
log("password", Password{"hunter2"});
log("api key", ApiKey{"k-123"});
}
user: ann
password: [redacted]
api key: [redacted]
- Verdict: idiom. A type trait marks a type from outside its class, so a library type can be marked too.
if constexprtests the marker at compile time, and the unmarked branch is not even compiled for a marked type. - An empty base class with
std::is_base_of_vis the form closest to the Java interface.
interface Value {
String value();
}
interface Sensitive {}
record Username(String value) implements Value {}
record Password(String value) implements Value, Sensitive {}
record ApiKey(String value) implements Value, Sensitive {}
public class Main {
static void log(String label, Value item) {
String shown = item instanceof Sensitive ? "[redacted]" : item.value();
System.out.println(label + ": " + shown);
}
public static void main(String[] args) {
log("user", new Username("ann"));
log("password", new Password("hunter2"));
log("api key", new ApiKey("k-123"));
}
}
user: ann
password: [redacted]
api key: [redacted]
- Verdict: idiom.
Sensitivedeclares no methods, asjava.io.Serializabledoes, andinstanceoftests it. - A method can also take a
Sensitiveparameter, so that the compiler rejects an unmarked argument.
using System;
using System.Reflection;
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
sealed class SensitiveAttribute : Attribute { }
record Username(string Value);
[Sensitive]
record Password(string Value);
[Sensitive]
record ApiKey(string Value);
class Program
{
static void Log(string label, object item, string value)
{
bool marked = item.GetType().GetCustomAttribute<SensitiveAttribute>() != null;
Console.WriteLine($"{label}: {(marked ? "[redacted]" : value)}");
}
static void Main()
{
var user = new Username("ann");
var password = new Password("hunter2");
var key = new ApiKey("k-123");
Log("user", user, user.Value);
Log("password", password, password.Value);
Log("api key", key, key.Value);
}
}
user: ann
password: [redacted]
api key: [redacted]
- Verdict: idiom. The .NET rule CA1040 advises a custom attribute in place of an empty interface when the test happens at run time.
Inherited = falsemeans that a subclass is not marked unless it declares the attribute too.
const sensitive = Symbol("sensitive");
class Username {
constructor(value) {
this.value = value;
}
}
class Password {
static {
this.prototype[sensitive] = true;
}
constructor(value) {
this.value = value;
}
}
class ApiKey {
static {
this.prototype[sensitive] = true;
}
constructor(value) {
this.value = value;
}
}
function log(label, item) {
const shown = sensitive in item ? "[redacted]" : item.value;
console.log(`${label}: ${shown}`);
}
log("user", new Username("ann"));
log("password", new Password("hunter2"));
log("api key", new ApiKey("k-123"));
user: ann
password: [redacted]
api key: [redacted]
- Verdict: idiom. JavaScript has no interfaces, so a property with a private
Symbolkey is the marker. Theinoperator also finds the property on the prototype.
const sensitive: unique symbol = Symbol("sensitive");
interface Sensitive {
readonly [sensitive]: true;
}
class Username {
readonly value: string;
constructor(value: string) {
this.value = value;
}
}
class Password implements Sensitive {
readonly [sensitive] = true as const;
readonly value: string;
constructor(value: string) {
this.value = value;
}
}
class ApiKey implements Sensitive {
readonly [sensitive] = true as const;
readonly value: string;
constructor(value: string) {
this.value = value;
}
}
function log(label: string, item: Username | Password | ApiKey): void {
const shown = sensitive in item ? "[redacted]" : item.value;
console.log(`${label}: ${shown}`);
}
log("user", new Username("ann"));
log("password", new Password("hunter2"));
log("api key", new ApiKey("k-123"));
user: ann
password: [redacted]
api key: [redacted]
- Verdict: idiom. An empty interface would match every object, because TypeScript types are structural. The brand property with a
unique symbolkey makes the interface match only the classes that declare it.
package main
import "fmt"
type Value interface {
Text() string
}
// Sensitive has one unexported method, so only types in this package
// can be marked. An interface with no methods would match every type.
type Sensitive interface {
sensitive()
}
type Username struct{ value string }
type Password struct{ value string }
type ApiKey struct{ value string }
func (u Username) Text() string { return u.value }
func (p Password) Text() string { return p.value }
func (k ApiKey) Text() string { return k.value }
func (Password) sensitive() {}
func (ApiKey) sensitive() {}
func log(label string, item Value) {
shown := item.Text()
if _, ok := item.(Sensitive); ok {
shown = "[redacted]"
}
fmt.Printf("%s: %s\n", label, shown)
}
func main() {
log("user", Username{"ann"})
log("password", Password{"hunter2"})
log("api key", ApiKey{"k-123"})
}
user: ann
password: [redacted]
api key: [redacted]
- Verdict: idiom. The marker is an interface with one empty, unexported method, as
go/astdoes withexprNode(). A type assertion tests it at run time.
use std::fmt::Display;
/// Marker: the value must not be written to a log.
trait Sensitive {}
struct Username(String);
struct Password(String);
struct ApiKey(String);
impl Sensitive for Password {}
impl Sensitive for ApiKey {}
impl Display for Username {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
fn log<T: Display>(label: &str, item: &T) {
println!("{label}: {item}");
}
// Only a marked type can be passed here; the compiler checks the bound.
fn log_secret<T: Sensitive>(label: &str, _item: &T) {
println!("{label}: [redacted]");
}
fn main() {
log("user", &Username("ann".to_string()));
log_secret("password", &Password("hunter2".to_string()));
log_secret("api key", &ApiKey("k-123".to_string()));
}
user: ann
password: [redacted]
api key: [redacted]
- Verdict: idiom. A trait with no items is the marker, and a trait bound tests it at compile time.
log_secretwith aUsernamedoes not compile. - The standard library uses the same form in
std::marker, forCopy,Send,SizedandSync.PasswordandApiKeydo not implementDisplay, so they cannot reach the normallogby mistake.
Consequences
A marker interface defines a type. Effective Java names this as its main advantage over a marker annotation: the compiler can then reject a call with an unmarked object, where an annotation is found only at run time.9 The test is also cheap, and the marker shows in the documentation of the class.
The costs:
- No contract. The interface says nothing about what the property means.
Cloneabledoes not contain theclonemethod, so a class that implements it is not cloneable for that reason alone.3 - A marker cannot be removed. A subclass inherits the interface, and it cannot unimplement it.1 A subclass that adds a field which cannot be serialized still passes the test:
This code runs but gives a wrong answer on purpose.
import pickle
import threading
class Serializable:
"""Marker: instances can be saved."""
class Cache(Serializable):
def __init__(self):
self.items = {}
class LockedCache(Cache):
def __init__(self):
super().__init__()
self.lock = threading.Lock()
def save(obj):
if not isinstance(obj, Serializable):
return f"{type(obj).__name__}: not serializable"
try:
pickle.dumps(obj)
return f"{type(obj).__name__}: saved"
except TypeError as e:
return f"{type(obj).__name__}: {e}"
for obj in [Cache(), LockedCache()]:
print(save(obj))
Cache: saved
LockedCache: cannot pickle '_thread.lock' object
The test passed for LockedCache, and the save failed later. Java has the same problem: a subclass of a serializable class that must not be serialized has to throw NotSerializableException itself.1
When not to use it
Do not use an empty interface for a property that only code at run time reads, when the language has attributes or annotations. The .NET rule CA1040 says that an empty interface defines no contract. If the identification occurs at run time, the correct way is a custom attribute. If it must occur at compile time, an empty interface is acceptable.5
Do not use a marker when the property needs a method. Declare the method in the interface, so that the type states both the property and the contract.
Do not use an empty interface in a language with structural typing. In TypeScript and Go, an interface with no members matches every value, so it marks nothing.86
Variants and related patterns
Marker annotation. Java annotations and C# attributes attach metadata with no change to the type. Effective Java gives the rule: use a marker interface if you want to define a type, and a marker annotation for other program elements or for a framework that already uses annotations.9 See Annotations.
Marker trait. Rust represents basic properties of types as traits in std::marker, such as Copy, Send, Sized and Sync.10 Send marks types that can be transferred across thread boundaries, and the compiler uses it in trait bounds, not at run time.10
Tag dispatch. A marker can select an algorithm. The main purpose of RandomAccess is to allow generic algorithms to change their behaviour for random or sequential access lists.4
Hybrid interface. An interface can act as a marker and also declare methods, but this can confuse its readers if it is used badly.1
Known uses
- Java: java/util/Collections.java at jdk-25+36.
binarySearchtestslist instanceof RandomAccess. A marked list, or a small list, gets the indexed search, and other lists get the iterator search.114 - Go: go/ast/ast.go at go1.25.0 declares
Exprwith the marker methodexprNode(), which each expression node implements with an empty body.7
References
- Marker interface pattern, Wikipedia, Introduction; Example; Critique
- Serializable, Java SE 25 API, interface description
- Cloneable, Java SE 25 API, interface description
- RandomAccess, Java SE 25 API, interface description
- CA1040: Avoid empty interfaces, Microsoft Learn, Rule description; How to fix violations
- The Go Programming Language Specification, Interface types (the empty interface)
- Go go1.25.0 source, src/go/ast/ast.go, the Expr interface and its exprNode method
- no-empty-object-type, typescript-eslint, rule description
- Joshua Bloch, Effective Java, third edition, Addison-Wesley, 2018, Item 41, Use marker interfaces to define types
- Module std::marker, The Rust Standard Library, module description; Traits
- OpenJDK jdk-25+36 source, java/util/Collections.java, binarySearch, lines 213 to 219
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag D8XWAX Edit this page History Report an error Markdown