search

Fail Fast

Dec 08, 2024 pm 12:33 PM

Fail Fast

Core Principle

Detect and report failures as soon as they occur, preventing invalid states from propagating through the system.

1. Input Validation

class UserRegistration {
    public function register(array $data): void {
        // Validate all inputs immediately
        $this->validateEmail($data['email']);
        $this->validatePassword($data['password']);
        $this->validateAge($data['age']);

        // Only proceed if all validations pass
        $this->createUser($data);
    }

    private function validateEmail(string $email): void {
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw new ValidationException('Invalid email format');
        }
        if ($this->emailExists($email)) {
            throw new DuplicateEmailException('Email already registered');
        }
    }
}

Purpose:

  • Prevents invalid data from entering the system
  • Saves resources by failing before complex operations
  • Provides clear error messages to users
  • Maintains data integrity

2. Configuration Loading

class AppConfig {
    private array $config;

    public function __construct(string $configPath) {
        if (!file_exists($configPath)) {
            throw new ConfigurationException("Config file not found: $configPath");
        }

        $config = parse_ini_file($configPath, true);
        if ($config === false) {
            throw new ConfigurationException("Invalid config file format");
        }

        $this->validateRequiredSettings($config);
        $this->config = $config;
    }

    private function validateRequiredSettings(array $config): void {
        $required = ['database', 'api_key', 'environment'];
        foreach ($required as $key) {
            if (!isset($config[$key])) {
                throw new ConfigurationException("Missing required config: $key");
            }
        }
    }
}

Purpose:

  • Ensures application starts with valid configuration
  • Prevents runtime errors due to missing settings
  • Makes configuration problems immediately visible
  • Simplifies debugging configuration issues

3. Resource Initialization

class DatabaseConnection {
    private PDO $connection;

    public function __construct(array $config) {
        try {
            $this->validateDatabaseConfig($config);
            $this->connection = new PDO(
                $this->buildDsn($config),
                $config['username'],
                $config['password'],
                [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
            );
        } catch (PDOException $e) {
            throw new DatabaseConnectionException(
                "Failed to connect to database: " . $e->getMessage()
            );
        }
    }

    private function validateDatabaseConfig(array $config): void {
        $required = ['host', 'port', 'database', 'username', 'password'];
        foreach ($required as $param) {
            if (!isset($config[$param])) {
                throw new DatabaseConfigException("Missing $param in database config");
            }
        }
    }
}

Purpose:

  • Ensures resources are properly initialized
  • Prevents application from running with invalid resources
  • Makes resource problems visible during startup
  • Avoids cascading failures due to invalid resources

4. External Service Calls

class PaymentGateway {
    public function processPayment(Order $order): PaymentResult {
        // Validate API credentials
        if (!$this->validateApiCredentials()) {
            throw new ApiConfigurationException('Invalid API credentials');
        }

        // Validate order before external call
        if (!$order->isValid()) {
            throw new InvalidOrderException('Invalid order state');
        }

        try {
            $response = $this->apiClient->charge($order);

            if (!$response->isSuccessful()) {
                throw new PaymentFailedException($response->getError());
            }

            return new PaymentResult($response);
        } catch (ApiException $e) {
            throw new PaymentProcessingException(
                "Payment processing failed: " . $e->getMessage()
            );
        }
    }
}

Purpose:

  • Prevents unnecessary API calls with invalid data
  • Saves time and resources
  • Provides immediate feedback on API issues
  • Maintains system reliability during external service interactions

5. Data Processing Pipelines

class DataProcessor {
    public function processBatch(array $records): array {
        $this->validateBatchSize($records);

        $results = [];
        foreach ($records as $index => $record) {
            try {
                $this->validateRecord($record);
                $results[] = $this->processRecord($record);
            } catch (ValidationException $e) {
                throw new BatchProcessingException(
                    "Failed at record $index: " . $e->getMessage()
                );
            }
        }

        return $results;
    }

    private function validateBatchSize(array $records): void {
        if (empty($records)) {
            throw new EmptyBatchException('Empty batch provided');
        }

        if (count($records) > 1000) {
            throw new BatchSizeException('Batch size exceeds maximum limit');
        }
    }
}

Purpose:

  • Ensures data consistency throughout processing
  • Prevents partial processing of invalid data
  • Makes data problems visible early
  • Simplifies error tracking in complex pipelines
  • Maintains data integrity across transformations

Benefits of Fail Fast

  1. Early error detection
  2. Cleaner debugging
  3. Prevents cascading failures
  4. Maintains data integrity
  5. Improves system reliability

Best Practices

  1. Use strong type declarations
  2. Implement thorough input validation
  3. Throw specific exceptions
  4. Validate early in the process
  5. Use assertions in development
  6. Implement proper error handling
  7. Log failures appropriately

When to Use Fail Fast

  1. Input validation
  2. Configuration loading
  3. Resource initialization
  4. External service calls
  5. Data processing pipelines

The above is the detailed content of Fail Fast. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor