スタンプ結合

 このサンプルコードでは、UserクラスのオブジェクトがUserEmailManagerに渡されUserEmailManagerUserオブジェクトの一部だけ(id プロパティ)を使用してユーザーのメールアドレスを取得しています。
この場合、引数として必要なデータを渡すだけの方が効率的で保守性が高まります。

<?php

class User
{
    private int $id;
    private string $name;

    public function __construct(int $id, string $name)
    {
        $this->id = $id;
        $this->name = $name;
    }

    public function getId(): int
    {
        return $this->id;
    }

    public function getName(): string
    {
        return $this->name;
    }
}
                    
<?php

class UserEmailManager
{
    public static function findUserEmailAddress(User $user): string
    {
        // ここでは $userオブジェクトのidプロパティを使用して、ユーザーのメールアドレスを取得
        if ($user->id === 1) {
            return 'user1@example.com';
        } else {
            return 'unknown@example.com';
        }
    }
}
                    
<?php

// スタンプ結合の問題を示す例
$user = new User(1, 'John Doe');

// ユーザーのメールアドレスを取得
$emailAddress = UserEmailManager::findUserEmailAddress($user);

echo "{$user->getName()}'s email address is: $emailAddress";
                    

スタンプ結合の改善例

 このサンプルコードでは、必要なデータだけを引数として渡すようにし、Userオブジェクト自体は渡しません。
これにより、スタンプ結合の問題を解消し、コードがシンプルで保守性が向上します。

<?php

class UserEmailManager
{
    public static function findUserEmailAddress(int $userId): string
    {
        // ここでは userId のみを使用して、ユーザーのメールアドレスを取得
        if ($userId === 1) {
            return 'user1@example.com';
        } else {
            return 'unknown@example.com';
        }
    }
}
                        
<?php

$user = $user = new User(1, 'John Doe');

// ユーザーのメールアドレスを取得
$emailAddress = UserEmailManager::findUserEmailAddress($user->id);

echo "User's email address is: $emailAddress";