Inheritance Pattern for Field Classes

System Design · flowchart diagram · unknown license

Illustrates a common inheritance pattern for field classes, showing how subclasses override base methods for type narrowing and add type-specific logic.

Source: https://github.com/beynar/viborm/blob/08ed661ab4fb1301ca6e73f571579e83ca2ac2f8/readme/SCHEMA_ARCHITECTURE.md
Curated by beynar
inheritance design pattern object-oriented programming type safety typescript class hierarchy software architecture

Mermaid source

flowchart TB
    subgraph "BaseField (shared logic)"
        CW["cloneWith()"]
        CM["nullable() / array() / id() / unique() / default()"]
        INT["~ internals initialization"]
    end
    
    subgraph "Subclass (type-specific)"
        OV["Override methods for return type narrowing"]
        SP["Type-specific methods (uuid, int, now...)"]
        CF["Config with fieldType"]
    end
    
    CW --> OV
    CM --> OV
    OV --> SP

What this diagram shows

This flowchart illustrates an inheritance pattern where a 'BaseField' class provides shared logic and common methods, while 'Subclass' implementations override these methods for return type narrowing and introduce type-specific functionalities. It highlights the flow from shared logic to type-specific overrides and configurations.

When to use it

Use this pattern when designing a hierarchy of classes where a base class provides common functionality, and derived classes need to specialize return types or add unique methods while reusing the core logic. This is common in ORM field definitions, schema builders, or configuration systems.

How to adapt it for your project

Adapt this by defining a generic base class with common methods. Subclasses should extend the base, overriding methods to return their specific type (e.g., StringField returning StringField<T>). Introduce type-specific methods in subclasses and use a configuration or factory to set fieldType.

Key concepts