<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Oyebanji Jacob on Medium]]></title>
        <description><![CDATA[Stories by Oyebanji Jacob on Medium]]></description>
        <link>https://medium.com/@pyjac?source=rss-38a898824d50------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*fE30e50nYBmUSarZ.jpg</url>
            <title>Stories by Oyebanji Jacob on Medium</title>
            <link>https://medium.com/@pyjac?source=rss-38a898824d50------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 03:24:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pyjac/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to avoid coupling external DTOs to your codebase]]></title>
            <link>https://engineering.hometogo.com/how-to-avoid-coupling-external-dtos-to-your-codebase-9dc8670f0439?source=rss-38a898824d50------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dc8670f0439</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Oyebanji Jacob]]></dc:creator>
            <pubDate>Wed, 07 May 2025 13:57:28 GMT</pubDate>
            <atom:updated>2025-05-07T13:57:28.042Z</atom:updated>
            <content:encoded><![CDATA[<p>Integrating with external APIs or internal microservices is a common task in modern software development. These integrations often involve exchanging data using Data Transfer Objects (DTOs). While convenient, allowing these external DTOs to permeate deep into your application’s codebase can lead to tight coupling, making your system brittle and difficult to maintain, especially when those external APIs evolve.</p><p>This article explores the challenges of such coupling and demonstrates how to avoid it by decoupling your internal domain from external DTOs, leading to a more robust and adaptable codebase. We’ll walk through a practical example, refactoring from a tightly coupled state to a clean, decoupled design using the Adapter pattern.</p><h3><strong>The initial setup: a common scenario</strong></h3><p>Consider a typical micro-service interaction: a <strong>Product Service</strong> needs to display products along with their prices, which are determined by a separate <strong>Price Service</strong> due to complex business rules. The <strong>Product Service</strong> calls the <strong>Price Service</strong> API to fetch this pricing information.</p><figure><img alt="Image illustrating the connection between two services: Product Service and Price Service" src="https://cdn-images-1.medium.com/max/800/0*dfYKe5Ez_9_xOogB.png" /></figure><p>Suppose the <strong>Product Service</strong> uses a shared library provided by the <strong>Price Service</strong> which includes DTOs for the API responses.</p><p>The <strong>Price Service</strong> V1 DTO might look like this:</p><pre>namespace CompanyNamespace\PriceServiceLib\Dto;<br><br>// DTO from the external Price Service V1 library<br>class PriceInfo {<br>  public string $productId;<br>  public int $basePrice; <br>  public string $currency;<br>  public int $discountAmount;<br>}</pre><p>And the <strong>Product</strong> entity within the <strong>Product Service</strong> might directly use this DTO:</p><pre>namespace CompanyNamespace\ProductService\Entity;<br><br>// Direct dependency on the external DTO<br>use CompanyNamespace\PriceServiceLib\Dto\PriceInfo;<br><br>class Product {<br>  private string $id;<br>  private string $name;<br>   // Tightly coupled: Product holds a reference to the external DTO<br>  public ?PriceInfo $priceInfo = null;<br><br>  // Assume getters for id and name exist<br>  public function getId(): string { return $this-&gt;id; }<br>  public function getName(): string { return $this-&gt;name; }<br>}</pre><p>A service class fetches products and enriches them with price information:</p><pre>namespace CompanyNamespace\ProductService\Service;<br><br>use CompanyNamespace\ProductService\Repository\ProductRepository;<br>use CompanyNamespace\PriceServiceLib\Client\PriceServiceClient;<br>use CompanyNamespace\ProductService\Entity\Product;<br><br>class ProductService {<br>   private ProductRepository $productRepository;<br>   private PriceServiceClient $priceServiceClient; // Client for the Price Service API<br>   // Constructor injection…<br><br>   public function getProductsByIds(array $ids): array {<br>     $products = $this-&gt;productRepository-&gt;getByIds($ids);<br>     $productsByIdMap = [];<br>     foreach ($products as $product) {<br>       $productsByIdMap[$product-&gt;getId()] = $product;<br>     }<br><br>     // Fetch DTOs from the external service<br>     $productsPriceInfo = $this-&gt;priceServiceClient-&gt;getPriceInfosByIds($ids); // Returns PriceInfo[] DTOs<br>     foreach ($productsPriceInfo as $productPriceInfo) {<br>       if (isset($productsByIdMap[$productPriceInfo-&gt;productId])) {<br>         $product = $productsByIdMap[$productPriceInfo-&gt;productId];<br>         // Direct assignment of the external DTO to the Product entity<br>         $product-&gt;priceInfo = $productPriceInfo;<br>       }<br>     }<br><br>     return $products; // Array of Product entities<br>  }<br>}</pre><p>Finally, a controller uses the <strong>Product Service</strong> to build an API response:</p><pre>namespace CompanyNamespace\ProductService\Controller;<br><br>use CompanyNamespace\ProductService\Service\ProductService;<br>use Symfony\Component\HttpFoundation\Request;<br>use Symfony\Component\HttpFoundation\JsonResponse;<br><br>class ProductController {<br>  private ProductService $productService;<br><br>  // Constructor injection…<br>  public function getProducts(Request $request): JsonResponse {<br>    $ids = []; // Assume IDs are extracted from the request<br>    $products = $this-&gt;productService-&gt;getProductsByIds($ids);<br>    $response = [];<br>    foreach ($products as $product) {<br>      // Directly accessing properties of the external DTO through the Product entity<br>      $priceData = null;<br>      if ($product-&gt;priceInfo !== null) {<br>        $priceData = [<br>         &quot;basePrice&quot; =&gt; $product-&gt;priceInfo-&gt;basePrice,<br>         &quot;currency&quot; =&gt; $product-&gt;priceInfo-&gt;currency,<br>         &quot;discount&quot; =&gt; $product-&gt;priceInfo-&gt;discountAmount<br>        ];<br>      }<br><br>      $response[$product-&gt;getId()] = [<br>        &quot;id&quot; =&gt; $product-&gt;getId(),<br>        &quot;name&quot; =&gt; $product-&gt;getName(),<br>        &quot;price&quot; =&gt; $priceData<br>      ]; <br>    }<br> <br>    return new JsonResponse($response);<br>  }<br>}</pre><p>This setup might seem straightforward initially and works fine. However, the <strong>Product</strong> entity, <strong>Product Service</strong>, and <strong>Product Controller</strong> are all directly coupled to the structure of the <strong>Price Info</strong> DTO from the external <strong>Price Service</strong>. The <strong>Product</strong> entity, potentially a core part of your domain, now has a direct dependency on an external data structure.</p><h3><strong>The challenge of API evolution</strong></h3><p>The problems with tight coupling surface when the external API changes. Suppose the <strong>Price Service</strong> releases a V2 API with a different structure for its <strong>Price Info</strong> DTO, perhaps nesting the price and currency:</p><pre>namespace CompanyNamespace\PriceServiceLib\Dto\V2;<br><br>class Price {<br> public int $price; <br> public string $currency;<br>}<br><br>class PriceInfo { // V2 DTO<br> public string $productId;<br> public Price $basePrice; // Changed structure: nested object<br> public int $discountAmount;<br>}</pre><p>Now, the <strong>Product Service</strong> needs to support both V1 and V2 responses, perhaps during a transition period or for different client configurations. How do we handle this with the existing coupling?</p><h3>Naive approach</h3><p>A naive approach might be to change the <strong>Product</strong> entity to hold either DTO version using a union type:</p><pre>namespace CompanyNamespace\ProductService\Entity;<br><br>use CompanyNamespace\PriceServiceLib\Dto\PriceInfo as V1PriceInfo;<br>use CompanyNamespace\PriceServiceLib\Dto\V2\PriceInfo as V2PriceInfo;<br><br>class Product {<br>  // … other properties<br>  // Now Product needs to know about BOTH external DTO versions<br>  public V1PriceInfo|V2PriceInfo|null $priceInfo = null; <br>}</pre><p>This forces complexity downstream. Any code interacting with <strong>$product-&gt;priceInfo</strong> must now check its type:</p><pre>// Inside ProductController or other consumers…<br>// …<br>$priceInfo = $product-&gt;priceInfo;<br>$priceData = null;<br>if ($priceInfo instanceof V1PriceInfo) {<br>  $priceData = [<br>    &quot;basePrice&quot; =&gt; $priceInfo-&gt;basePrice,<br>    &quot;currency&quot; =&gt; $priceInfo-&gt;currency,<br>    &quot;discount&quot; =&gt; $priceInfo-&gt;discountAmount<br>  ];<br>} elseif ($priceInfo instanceof V2PriceInfo) {<br>  $priceData = [<br>    &quot;basePrice&quot; =&gt; $priceInfo-&gt;basePrice-&gt;price, // Access path changed<br>    &quot;currency&quot; =&gt; $priceInfo-&gt;basePrice-&gt;currency, // Access path changed<br>    &quot;discount&quot; =&gt; $priceInfo-&gt;discountAmount<br>  ];<br>}<br>$response[$product-&gt;getId()][&quot;price&quot;] = $priceData;<br>// …</pre><p>This approach is problematic because it:</p><ol><li><strong>violates encapsulation</strong>:<strong> </strong>the internal structure of external DTOs leaks into various parts of the <strong>Product Service</strong>.</li><li><strong>increases complexity</strong>: conditional logic (<strong>instanceof</strong>) spreads throughout the codebase wherever price information is needed.</li><li><strong>results in poor maintainability</strong>: adding support for a V3 would require modifying all these conditional blocks. The Product entity becomes increasingly burdened with knowledge of external systems.</li></ol><p>This tight coupling makes the codebase fragile and resistant to change.</p><h3>The decoupling principle: isolating external data</h3><p>The core principle to solve this is <strong>decoupling</strong>. Treat external DTOs purely as data carriers for crossing service boundaries.</p><blockquote><strong>Principle</strong>: Do not allow external API DTOs to be directly accessed or passed around deep within your application’s logic after being fetched from an API client.</blockquote><p>DTOs, as the name suggests, are just data transfer objects. Their main purpose is just to convey data to be transferred over the network to another service. They are not objects meant to be passed around after fetched from a client in the dependent service.</p><p>Instead, immediately map the incoming DTO to an internal representation (an object or data structure defined within your service’s domain) at the boundary — typically right after receiving it from the API client. This internal representation acts as an adapter, shielding the rest of your codebase from the specifics of the external API’s structure.</p><p>If you need to access data from the external DTO later, do so indirectly through this internal adapter object.</p><h3>Implementing the adapter pattern</h3><p>Let’s create an internal adapter class within <strong>Product Service</strong> to represent the price information we actually need, regardless of the DTO version. Based on the <strong>Product Controller’s</strong> requirements, we need base price, currency, and discount amount.</p><p>Let’s call our adapter <strong>InternalPriceInfo</strong>:</p><pre>namespace CompanyNamespace\ProductService\&lt;…&gt;\&lt;…&gt;; // Internal representation<br><br>use CompanyNamespace\PriceServiceLib\Dto\PriceInfo as V1PriceInfo;<br>use CompanyNamespace\PriceServiceLib\Dto\V2\PriceInfo as V2PriceInfo;<br><br>class InternalPriceInfo {<br>    // The adapter holds the original DTO but doesn&#39;t expose it directly<br>    public function __construct(private readonly V1PriceInfo|V2PriceInfo $externalPriceInfo) {}<br><br>    // Methods provide a stable internal interface to the data<br>    public function getBasePrice(): int {<br>        if ($this-&gt;externalPriceInfo instanceof V2PriceInfo) {<br>            return $this-&gt;externalPriceInfo-&gt;basePrice-&gt;price;<br>        }<br>        // Assumes V1 otherwise (can be made more robust)<br>        return $this-&gt;externalPriceInfo-&gt;basePrice;<br>    }<br><br>    public function getCurrency(): string {<br>        if ($this-&gt;externalPriceInfo instanceof V2PriceInfo) {<br>            // Bug Fix: V2 currency is nested<br>            return $this-&gt;externalPriceInfo-&gt;basePrice-&gt;currency;<br>        }<br>        return $this-&gt;externalPriceInfo-&gt;currency;<br>    }<br><br>    public function getDiscountAmount(): int {<br>        // This property happens to be the same in V1 and V2<br>        return $this-&gt;externalPriceInfo-&gt;discountAmount;<br>    }<br>}</pre><p>Now, update the <strong>Product</strong> entity to use this internal adapter:</p><pre>namespace CompanyNamespace\ProductService\Entity;<br><br>// Dependency is now on an internal adapter, not the external DTO<br>use CompanyNamespace\ProductService\&lt;...&gt;\InternalPriceInfo; <br><br>class Product {<br>    private string $id;<br>    private string $name;<br>    // Product now depends on the internal adapter<br>    public ?InternalPriceInfo $priceInfo = null; <br><br>    // ... getters ...<br>}</pre><p>The <strong>Product Service</strong> is responsible for performing the mapping (adaptation) immediately after fetching the external DTOs:</p><pre>namespace CompanyNamespace\ProductService\Service;<br><br>use CompanyNamespace\ProductService\&lt;...&gt;\InternalPriceInfo; <br>// Other use statements...<br><br>class ProductService {<br>    // ... properties and constructor ...<br><br>    public function getProductsByIds(array $ids): array {<br>        // ... fetch products ...<br><br>        $productsPriceInfo = $this-&gt;priceServiceClient-&gt;getPriceInfosByIds($ids); // Returns V1 or V2 PriceInfo DTOs<br><br>        foreach ($productsPriceInfo as $externalDto) {<br>            $productId = $externalDto-&gt;productId; // Assuming productId exists in both DTOs<br>             if (isset($productsByIdMap[$productId])) {<br>                 $product = $productsByIdMap[$productId];<br>                 // Adapt the external DTO to the internal representation<br>                 $product-&gt;priceInfo = new InternalPriceInfo($externalDto); <br>            }<br>        }<br>        return $products; <br>    }<br>}</pre><p>And the <strong>Product Controller</strong> becomes much cleaner, interacting only with the stable interface of the <strong>InternalPriceInfo</strong> adapter:</p><pre>namespace CompanyNamespace\ProductService\Controller;<br><br>// Other use statements...<br><br>class ProductController {<br>    // ... property and constructor ...<br><br>    public function getProducts(Request $request): JsonResponse {<br>        // ... get ids, fetch products ...<br>        $response = [];<br>        foreach ($products as $product) {<br>            // Access data via the adapter&#39;s stable methods<br>            $priceData = null;<br>            if ($product-&gt;priceInfo !== null) {<br>                 $priceData = [<br>                     &quot;basePrice&quot; =&gt; $product-&gt;priceInfo-&gt;getBasePrice(), // Use getter<br>                     &quot;currency&quot; =&gt; $product-&gt;priceInfo-&gt;getCurrency(), // Use getter<br>                     &quot;discount&quot; =&gt; $product-&gt;priceInfo-&gt;getDiscountAmount() // Use getter<br>                 ];<br>            }<br>            $response[$product-&gt;getId()] = [<br>                &quot;id&quot; =&gt; $product-&gt;getId(),<br>                &quot;name&quot; =&gt; $product-&gt;getName(),<br>                &quot;price&quot; =&gt; $priceData<br>            ];    <br>        }<br><br>        return new JsonResponse($response);<br>    }<br>}</pre><h3><strong>Refining the adapter with polymorphism</strong></h3><p>Our <strong>InternalPriceInfo</strong> adapter still contains conditional <strong>instanceof</strong> checks.</p><pre>public function getBasePrice(): int {<br>    if ($this-&gt;externalPriceInfo instanceof V2PriceInfo) {<br>       return $this-&gt;externalPriceInfo-&gt;basePrice-&gt;price;<br>    }<br>    // Assumes V1 otherwise (can be made more robust)<br>    return $this-&gt;externalPriceInfo-&gt;basePrice;<br>}</pre><p>While better than spreading them around, we can improve this further using <strong>polymorphism</strong>, adhering to <strong>the Open/Closed Principle (open for extension, closed for modification).</strong></p><p>We can do better by creating individual <strong>InternalPriceInfo</strong> classes for each version of price info object. Since we want to be able to call <strong>getBasePrice</strong>, <strong>getCurrency</strong> and <strong>getDiscountAmount</strong> from the whatever version, we can make an interface <strong>InternalPriceInfoInterface</strong> which any class we want to create must implement.</p><p>Define an interface for our internal price representation:</p><pre>namespace CompanyNamespace\ProductService\&lt;...&gt;;<br><br>interface InternalPriceInfoInterface {<br>    public function getBasePrice(): int;<br>    public function getCurrency(): string;<br>    public function getDiscountAmount(): int;<br>}</pre><p>Create specific adapter classes for each DTO version, implementing this interface:</p><pre>// V1 Adapter<br>namespace CompanyNamespace\ProductService\&lt;...&gt;\V1;<br><br>use CompanyNamespace\PriceServiceLib\Dto\PriceInfo as V1PriceInfo;<br>use CompanyNamespace\ProductService\&lt;...&gt;\InternalPriceInfoInterface;<br><br>class PriceInfoAdapter implements InternalPriceInfoInterface {<br>    public function __construct(private readonly V1PriceInfo $priceInfo) {}<br><br>    public function getBasePrice(): int {<br>        return $this-&gt;priceInfo-&gt;basePrice;<br>    }<br>    public function getCurrency(): string {<br>        return $this-&gt;priceInfo-&gt;currency;<br>    }<br>    public function getDiscountAmount(): int {<br>        return $this-&gt;priceInfo-&gt;discountAmount;<br>    }<br>}<br><br>// V2 Adapter<br>namespace CompanyNamespace\ProductService\&lt;...&gt;\V2;<br><br>use CompanyNamespace\PriceServiceLib\Dto\V2\PriceInfo as V2PriceInfo;<br>use CompanyNamespace\ProductService\&lt;...&gt;\InternalPriceInfoInterface;<br><br>class PriceInfoAdapter implements InternalPriceInfoInterface {<br>    public function __construct(private readonly V2PriceInfo $priceInfo) {}<br><br>    public function getBasePrice(): int {<br>        return $this-&gt;priceInfo-&gt;basePrice-&gt;price;<br>    }<br>    public function getCurrency(): string {<br>        return $this-&gt;priceInfo-&gt;basePrice-&gt;currency;<br>    }<br>    public function getDiscountAmount(): int {<br>        return $this-&gt;priceInfo-&gt;discountAmount;<br>    }<br>}</pre><p>Update the <strong>Product</strong> entity to depend on the interface:</p><pre>namespace CompanyNamespace\ProductService\Entity;<br><br>use CompanyNamespace\ProductService\&lt;...&gt;\InternalPriceInfoInterface; // Depend on the abstraction<br><br>class Product {<br>    // ... other properties<br>    public ?InternalPriceInfoInterface $priceInfo = null; // Use the interface type<br>    // ... getters ...<br>}</pre><p>To simplify creating the correct adapter instance, we can use a <strong>Factory</strong>:</p><pre>namespace CompanyNamespace\ProductService\&lt;...&gt;;<br><br>use CompanyNamespace\PriceServiceLib\Dto\PriceInfo as V1PriceInfo;<br>use CompanyNamespace\PriceServiceLib\Dto\V2\PriceInfo as V2PriceInfo;<br>use CompanyNamespace\ProductService\&lt;...&gt;\V1\InternalPriceInfo as V1InternalPriceInfo;<br>use CompanyNamespace\ProductService\&lt;...&gt;\V2\InternalPriceInfo as V2InternalPriceInfo;<br><br>class InternalPriceInfoFactory {<br>    public static function create(V1PriceInfo|V2PriceInfo $externalDto): InternalPriceInfoInterface {<br>        if ($externalDto instanceof V2PriceInfo) {<br>            return new V2InternalPriceInfo($externalDto);<br>        }<br>        // Assume V1 if not V2 (could add explicit check or error handling)<br>        if ($externalDto instanceof V1PriceInfo) {<br>           return new V1InternalPriceInfo($externalDto);<br>        }<br><br>        // Handle cases where the DTO type is unexpected<br>        throw new \InvalidArgumentException(&quot;Unsupported PriceInfo DTO type provided.&quot;);<br>    }<br>}</pre><p>Finally, update the <strong>Product Service</strong> to use the factory:</p><pre>namespace CompanyNamespace\ProductService\Service;<br><br>use CompanyNamespace\ProductService\&lt;...&gt;\InternalPriceInfoFactory; <br>// Other use statements...<br><br>class ProductService {<br>    // ... properties and constructor ...<br><br>    public function getProductsByIds(array $ids): array {<br>        // ... fetch products ...<br><br>        $productsPriceInfo = $this-&gt;priceServiceClient-&gt;getPriceInfosByIds($ids); // Returns V1 or V2 PriceInfo DTOs<br><br>        foreach ($productsPriceInfo as $externalDto) {<br>             $productId = $externalDto-&gt;productId; <br>             if (isset($productsByIdMap[$productId])) {<br>                 $product = $productsByIdMap[$productId];<br>                 // Use the factory to create the appropriate adapter instance<br>                 $product-&gt;priceInfo = InternalPriceInfoFactory::create($externalDto); <br>            }<br>        }<br>        return $products; <br>    }<br>}</pre><p>Now, the <strong>Product Service</strong> uses the factory to create the correct adapter, and the rest of the code (like <strong>Product</strong> entity and <strong>Product Controller</strong>) interacts purely with the <strong>InternalPriceInfoInterface</strong>. Adding support for a V3 DTO would involve creating a new V3 adapter class and updating the factory — no changes needed in the <strong>Product</strong> entity, <strong>ProductController</strong>, or other consumers. This design is much more maintainable and follows the <strong>Open/Closed Principle</strong>.</p><h3>Conclusion</h3><p>Directly coupling your application’s domain logic and entities to external API DTOs creates fragility and hinders maintainability. When external APIs inevitably change, this coupling forces complex and widespread modifications throughout your codebase.</p><p>By applying the adapter pattern at the boundary where external data enters your system, you can isolate your core logic from the volatile structures of external DTOs. Mapping external DTOs to stable internal representations (interfaces and implementing classes) leads to:</p><ul><li><strong>improved maintainability</strong>: changes in external APIs only affect the specific adapter implementation and potentially a factory, not the entire codebase.</li><li><strong>enhanced robustness</strong>: your core domain logic is shielded from external volatility.</li><li><strong>better testability</strong>: you can easily test your internal logic using mock implementations of the internal interfaces.</li><li><strong>clearer boundaries</strong>: it enforces a clean separation between your internal domain and external integration concerns.</li></ul><p>While it requires a bit more upfront effort to create these adapters, the long-term benefits in flexibility and reduced maintenance costs make decoupling from external DTOs a worthwhile investment for any application interacting with external services.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dc8670f0439" width="1" height="1" alt=""><hr><p><a href="https://engineering.hometogo.com/how-to-avoid-coupling-external-dtos-to-your-codebase-9dc8670f0439">How to avoid coupling external DTOs to your codebase</a> was originally published in <a href="https://engineering.hometogo.com/">HomeToGo Data &amp; Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>