Skip to content

Latest commit

 

History

History
78 lines (64 loc) · 1.7 KB

File metadata and controls

78 lines (64 loc) · 1.7 KB

Return Type Consistency

The Problem

Functions that return different types are:

  • Unpredictable - Callers don't know what to expect
  • Error-prone - Easy to miss a case
  • Hard to test - Must test all return paths
  • Confusing - 0 vs false vs null vs -1

Bad Practice

function get_user_posts($user_id) {
    if (!$user_id) {
        return false;
    }
    $posts = get_posts(['author' => $user_id]);
    if (empty($posts)) {
        return null;
    }
    if (count($posts) === 1) {
        return $posts[0];  // WP_Post
    }
    return $posts;  // array
}

Returns 4 different types!

Good Practice

Option 1: Always Array

function get_user_posts( int $user_id ): array {
    return get_posts( [ 'author' => $user_id ] ) ?: [];
}

Option 2: Nullable

function find_post( int $id ): ?WP_Post {
    $post = get_post( $id );
    return $post instanceof WP_Post ? $post : null;
}

Option 3: Result Object

class ValidationResult {
    public function __construct(
        private readonly bool $is_valid,
        private readonly array $errors = []
    ) {}
}

Option 4: Union Types (PHP 8+)

function create_post( string $title ): int|WP_Error {
    // Always int or WP_Error, never false or null
}

Key Takeaways

One function = one return type
Use arrays for collections (never array|object)
Use null for "not found"
Use exceptions for errors
Use Result objects for complex returns
Document return type with PHPDoc

❌ Don't return array|false|null
❌ Don't return object|array
❌ Don't return int|false (0 is falsy!)
❌ Don't mix success/error return types