Abstract Base Classes Enforce Contracts

Force subclasses to implement storage contracts with abstract members while concrete helpers on the base class keep shared logic in one place.

TypescriptData Integrity

Code

typescriptsnippet
35 lines
// 抽象基类(abstract base class):契约方法由子类补齐,共享逻辑留在基类
abstract class KeyValueStore {
  protected prefix: string;

  constructor(prefix: string) {
    this.prefix = prefix;
  }

  abstract get(key: string): string | null;

  qualified(key: string): string {
    return `${this.prefix}:${key}`;
  }
}

class MemoryStore extends KeyValueStore {
  private table = new Map<string, string>();

  constructor() {
    super('mem');
  }

  override get(key: string): string | null {
    return this.table.get(this.qualified(key)) ?? null;
  }

  set(key: string, value: string): void {
    this.table.set(this.qualified(key), value);
  }
}

const store = new MemoryStore();
store.set('token', 'abc123');
console.log('read:', store.get('token'));
console.log('missing:', store.get('absent'));

How it works

Abstract Base Classes Enforce Contracts reduces to the classes KeyValueStore and MemoryStore.

Top-level bindings store hold the demo state — nothing sits inside a function scope.

Applying it

The demo output is labeled (read:, missing:), so each printed line maps back to the step behind it.

Statements that matter

return this.table.get(this.qualified(key)) ?? null;
private table = new Map<string, string>();
return `${this.prefix}:${key}`;

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
No. The dependency list is empty; the code stays inside the standard library. Its state lives in module-level bindings: `store`.