Skip to content

Stop Chaining Through Objects

Quick Tips•
November 27, 2026

When a caller walks $order->getCustomer()->getAddress()->getCountry()->getCode(), it depends on four classes and on the shape of the path between them. If Address stops holding a Country object and stores a plain country code, every caller that reached through it breaks. The caller only wanted a country code, but it had to know the whole path to get one.

Don't do this

PHP
<?php declare(strict_types=1); namespace App\Shipping; use App\Orders\Order; final readonly class ShippingCalculator { public function rateFor(Order $order): int { $countryCode = $order->getCustomer()->getAddress()->getCountry()->getCode(); return $countryCode === 'US' ? 500 : 1500; } }

Do this instead

PHP
<?php declare(strict_types=1); namespace App\Shipping; use App\Orders\Order; final readonly class ShippingCalculator { public function rateFor(Order $order): int { return $order->shippingCountryCode() === 'US' ? 500 : 1500; } }
PHP
<?php declare(strict_types=1); namespace App\Orders; use App\Customers\Customer; final readonly class Order { public function __construct( private Customer $customer, ) {} public function shippingCountryCode(): string { return $this->customer->shippingCountryCode(); } }
PHP
<?php declare(strict_types=1); namespace App\Customers; final readonly class Customer { public function __construct( private Address $address, ) {} public function shippingCountryCode(): string { return $this->address->countryCode(); } }

Each class now exposes what its caller needs and keeps the rest private. The calculator asks $order->shippingCountryCode() and does not know how many objects sit between the order and the code. When Address changes how it stores the country, you edit Address::countryCode() and nothing else.