Skip to content

Domain Context Architecture Pattern

Document-centric domain separation architecture for multi-domain applications using the Context-Action framework.

Pattern Overview

Domain Context Architecture organizes application architecture around business domains and their corresponding documentation:

  • Business Context: Core business logic and domain rules
  • UI Context: Screen state and user interactions
  • Validation Context: Data validation and error handling
  • Design Context: Theme management and visual states
  • Architecture Context: System configuration and technical decisions

Context Separation Strategy

mermaid
graph TB
    subgraph "Document-Based Domain Architecture"
        subgraph Business["💼 Business Context"]
            B1["📋 Business Requirements"]
            B2["🔄 Workflows & Rules"] 
            B3["📊 Domain Logic"]
            B4["🎯 Business Processes"]
        end
        
        subgraph UI["👥 UI Context"]
            U1["🖥️ Screen State"]
            U2["🎭 User Interactions"]
            U3["📱 Component Behavior"]
            U4["🔄 UI Workflows"]
        end
        
        subgraph Validation["✅ Validation Context"]
            V1["📏 Data Rules"]
            V2["🛡️ Input Validation"]
            V3["❌ Error Handling"]
            V4["📋 Form Processing"]
        end
        
        subgraph Design["🎨 Design Context"]
            D1["🎭 Theme Management"]
            D2["🖼️ Visual States"]
            D3["📐 Layout Systems"]
            D4["🎨 Style Guidelines"]
        end
        
        subgraph Architecture["🏗️ Architecture Context"]
            A1["⚙️ System Configuration"]
            A2["🔧 Infrastructure"]
            A3["📈 Technical Decisions"]
            A4["🏗️ System Design"]
        end
    end
    
    Business -.->|"coordinates"| UI
    Business -.->|"validates"| Validation
    Business -.->|"styles"| Design
    Business -.->|"configures"| Architecture
    
    style Business fill:#e8f5e8
    style UI fill:#e3f2fd
    style Validation fill:#fff3e0
    style Design fill:#f3e5f5
    style Architecture fill:#fce4ec

Prerequisites

For complete domain context setup instructions including type definitions, multi-domain contexts, and provider composition, see Multi-Context Setup - Domain Context Architecture.

This document demonstrates implementation patterns using the domain context setup:

Domain Implementation Patterns

Business Context Implementation

typescript
// Business domain implementation using configured contexts
function useBusinessLogic() {
  const businessDispatch = useBusinessActionDispatch();
  const businessManager = useBusinessStoreManager();
  
  const processOrderHandler = useCallback(async (payload, controller) => {
    try {
      const ordersStore = businessManager.getStore('orders');
      const inventoryStore = businessManager.getStore('inventory');
      
      // Business logic implementation
      const order = await orderAPI.create(payload);
      ordersStore.update(orders => [...orders, order]);
      
      // Update inventory
      inventoryStore.update(inventory => 
        updateInventoryAfterOrder(inventory, payload.items)
      );
      
    } catch (error) {
      controller.abort('Order processing failed', error);
    }
  }, [businessManager]);
  
  useBusinessActionHandler('processOrder', processOrderHandler);
}

UI Context Implementation

UI Context uses the specifications from Multi-Context Setup - UI Domain:

typescript
// UI Context implementation using setup specifications
function useUILogic() {
  const uiDispatch = useUIActionDispatch();
  const uiManager = useUIStoreManager();
  
  const showModalHandler = useCallback(async (payload) => {
    const modalStore = uiManager.getStore('modal');
    modalStore.setValue({ isOpen: true, type: payload.type, data: payload.data });
  }, [uiManager]);
  
  const hideModalHandler = useCallback(async () => {
    const modalStore = uiManager.getStore('modal');
    modalStore.setValue({ isOpen: false, type: undefined, data: undefined });
  }, [uiManager]);
  
  useUIActionHandler('showModal', showModalHandler);
  useUIActionHandler('hideModal', hideModalHandler);
}

Validation Context Implementation

Validation Context uses the specifications from Multi-Context Setup - Validation Domain:

typescript
// Validation Context implementation using setup specifications
function useValidationLogic() {
  const validationDispatch = useValidationActionDispatch();
  const validationManager = useValidationStoreManager();
  
  const validateFieldHandler = useCallback(async (payload) => {
    const { fieldName, value, rules } = payload;
    const validationResults = await validateFieldValue(value, rules);
    
    const fieldStatusesStore = validationManager.getStore('fieldStatuses');
    const formErrorsStore = validationManager.getStore('formErrors');
    
    if (validationResults.isValid) {
      fieldStatusesStore.update(statuses => ({ ...statuses, [fieldName]: 'valid' }));
      formErrorsStore.update(errors => {
        const newErrors = { ...errors };
        delete newErrors[fieldName];
        return newErrors;
      });
    } else {
      fieldStatusesStore.update(statuses => ({ ...statuses, [fieldName]: 'invalid' }));
      formErrorsStore.update(errors => ({ 
        ...errors, 
        [fieldName]: validationResults.errors 
      }));
    }
  }, [validationManager]);
  
  useValidationActionHandler('validateField', validateFieldHandler);
}

Design Context Implementation

Design Context uses the specifications from Multi-Context Setup - Design System Context:

typescript
// Design Context implementation using setup specifications
function useDesignLogic() {
  const designDispatch = useDesignActionDispatch();
  const designManager = useDesignStoreManager();
  
  const changeColorSchemeHandler = useCallback(async (payload) => {
    const colorSchemeStore = designManager.getStore('colorScheme');
    colorSchemeStore.setValue(payload.scheme);
    
    // Update theme based on color scheme
    const themeStore = designManager.getStore('theme');
    const currentTheme = themeStore.getValue();
    const updatedTheme = applyColorScheme(currentTheme, payload.scheme);
    themeStore.setValue(updatedTheme);
  }, [designManager]);
  
  const updateBreakpointHandler = useCallback(async (payload) => {
    const breakpointStore = designManager.getStore('breakpoint');
    breakpointStore.setValue(payload.breakpoint);
  }, [designManager]);
  
  useDesignActionHandler('changeColorScheme', changeColorSchemeHandler);
  useDesignActionHandler('updateBreakpoint', updateBreakpointHandler);
}

Cross-Domain Coordination

typescript
// hooks/useCrossDomainActions.ts
export function useOrderProcessingWorkflow() {
  const businessManager = useBusinessStoreManager();
  const uiManager = useUIStoreManager();
  const validationManager = useValidationStoreManager();
  
  const processOrderHandler = useCallback(async (payload, controller) => {
    // 1. UI Context - Show loading
    const screenStateStore = uiManager.getStore('screenState');
    screenStateStore.update(state => ({ ...state, isLoading: true }));
    
    // 2. Validation Context - Validate order
    const validationResult = await validateOrderData(payload);
    if (!validationResult.isValid) {
      const fieldErrorsStore = validationManager.getStore('fieldErrors');
      fieldErrorsStore.setValue(validationResult.errors);
      controller.abort('Validation failed');
      return;
    }
    
    // 3. Business Context - Process order
    try {
      const order = await orderAPI.create(payload);
      const ordersStore = businessManager.getStore('orders');
      ordersStore.update(orders => [...orders, order]);
      
      // 4. UI Context - Show success notification
      screenStateStore.update(state => ({
        ...state,
        isLoading: false,
        notifications: [...state.notifications, {
          message: 'Order processed successfully',
          type: 'success'
        }]
      }));
      
      return { success: true, orderId: order.id };
    } catch (error) {
      screenStateStore.update(state => ({ ...state, isLoading: false }));
      controller.abort('Order processing failed', error);
    }
  }, [businessManager, uiManager, validationManager]);
  
  useBusinessActionHandler('processOrder', processOrderHandler);
}

Application Composition

Uses Multi-Context Setup - Domain-Based Composition:

tsx
// App.tsx - Domain-based composition using setup specifications
function DomainContextApp() {
  // Use composed providers from setup specifications
  const DomainProviders = composeProviders([
    // Core Business Domain
    BusinessModelProvider,
    BusinessViewModelProvider,
    
    // User Interface Domain  
    UIModelProvider,
    UIViewModelProvider,
    
    // Validation Domain
    ValidationModelProvider,
    ValidationViewModelProvider,
    
    // Design System Domain
    DesignModelProvider,
    DesignViewModelProvider
  ]);
  
  return (
    <DomainProviders>
      {/* Cross-Domain Coordination */}
      <CrossDomainHandlers />
      
      {/* Application Components */}
      <OrderManagementScreen />
      <InventoryScreen />
      <CustomerScreen />
    </DomainProviders>
  );
}

function CrossDomainHandlers() {
  // Register cross-domain workflows
  useOrderProcessingWorkflow();
  useCustomerValidationWorkflow();
  useInventoryUpdateWorkflow();
  useUINotificationWorkflow();
  
  return null;
}

Domain Responsibilities

Business Context

  • ✅ Core business logic and rules
  • ✅ Domain entity management
  • ✅ Business process orchestration
  • ✅ Data transformation and processing
  • ❌ UI presentation concerns
  • ❌ Visual styling decisions
  • ❌ Input validation rules

UI Context

  • ✅ Screen state management
  • ✅ User interaction handling
  • ✅ Navigation and routing
  • ✅ Modal and overlay management
  • ❌ Business logic implementation
  • ❌ Data validation rules
  • ❌ Visual theme management

Validation Context

  • ✅ Input validation rules
  • ✅ Form validation logic
  • ✅ Error message management
  • ✅ Data integrity checks
  • ❌ Business process logic
  • ❌ UI state management
  • ❌ Visual styling

Design Context

  • ✅ Theme and visual state
  • ✅ Layout configuration
  • ✅ Style management
  • ✅ Responsive design state
  • ❌ Business logic
  • ❌ Data validation
  • ❌ User interaction logic

Architecture Context

  • ✅ System configuration
  • ✅ Infrastructure settings
  • ✅ Technical parameters
  • ✅ Environment management
  • ❌ Business domain logic
  • ❌ User interface concerns
  • ❌ Visual presentation

Document-Centric Design

Each context corresponds to specific documentation:

Business Documentation → Business Context

  • Requirements documents
  • Business process flows
  • Domain models
  • User stories

UI Specifications → UI Context

  • Wireframes and mockups
  • User interaction flows
  • Screen specifications
  • Navigation maps

Validation Specifications → Validation Context

  • Validation rules documentation
  • Error handling procedures
  • Data integrity requirements
  • Form validation specs

Design Guidelines → Design Context

  • Style guides
  • Design systems
  • Theme specifications
  • Branding guidelines

Architecture Documents → Architecture Context

  • System architecture diagrams
  • Technical specifications
  • Infrastructure documentation
  • Configuration guides

Cross-Domain Communication Patterns

Coordinated Actions

typescript
// Business triggers UI updates
const businessHandler = useCallback(async (payload, controller) => {
  // Process business logic
  const result = await processBusinessLogic(payload);
  
  // Trigger UI notification
  dispatch('showNotification', {
    message: 'Business process completed',
    type: 'success'
  });
}, []);

Validation Integration

typescript
// UI triggers validation before business logic
const uiHandler = useCallback(async (payload, controller) => {
  // Validate first
  const isValid = await dispatch('validateForm', payload);
  
  if (isValid) {
    // Process business logic
    await dispatch('processOrder', payload);
  }
}, []);

Best Practices

✅ Do's

  1. Clear Domain Boundaries

    • Keep each context focused on its domain
    • Use explicit cross-domain communication
    • Document domain responsibilities
    • Maintain domain isolation
  2. Document Alignment

    • Align contexts with documentation structure
    • Keep domain docs updated with code
    • Use contexts to organize deliverables
    • Maintain traceability
  3. Cross-Domain Coordination

    • Use explicit action dispatching between domains
    • Implement coordinated workflows
    • Handle cross-domain errors gracefully
    • Monitor inter-domain dependencies

❌ Don'ts

  1. Domain Mixing

    • Don't put business logic in UI context
    • Don't handle validation in design context
    • Don't manage UI state in business context
    • Don't mix architectural concerns
  2. Tight Coupling

    • Don't directly access other domain stores
    • Don't create circular dependencies
    • Don't bypass the action pipeline
    • Don't share context instances

When to Use Domain Context Architecture

✅ Perfect For

  • Multi-domain business applications
  • Applications with clear business boundaries
  • Teams organized by business domains
  • Document-heavy development processes
  • Microservice architecture alignment

❌ Consider Alternatives For

  • Simple single-domain applications (use MVVM)
  • Applications with minimal business complexity
  • Small teams preferring technical organization
  • Performance-critical applications requiring tighter integration

Released under the Apache-2.0 License.