<?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 Chapdast Dev on Medium]]></title>
        <description><![CDATA[Stories by Chapdast Dev on Medium]]></description>
        <link>https://medium.com/@chapdast.dev?source=rss-531bb418784f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YYoa3lV-RxP6xkOEa3iGnA.jpeg</url>
            <title>Stories by Chapdast Dev on Medium</title>
            <link>https://medium.com/@chapdast.dev?source=rss-531bb418784f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 11:01:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chapdast.dev/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[Base-First gRPC Composition in Go: Clean Inheritance Without Inheritance]]></title>
            <link>https://medium.com/@chapdast.dev/base-first-grpc-composition-in-go-clean-inheritance-without-inheritance-1e1a4ac1c20f?source=rss-531bb418784f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e1a4ac1c20f</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Chapdast Dev]]></dc:creator>
            <pubDate>Thu, 29 May 2025 09:54:46 GMT</pubDate>
            <atom:updated>2025-05-29T09:54:46.509Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Modular gRPC servers with explicit delegation and ordered behavior</em></p><p>In large Go applications — especially microservice backends that use gRPC — maintaining clean and modular service logic can be a challenge. One common trap is placing all responsibilities (business logic, side effects, external service calls, logging, metrics, etc.) into a single gRPC server implementation. This monolith grows, becomes harder to test, and violates separation of concerns.</p><p>In this article, we explore a lesser-known, yet highly effective composition pattern for gRPC servers in Go. It simulates OOP inheritance via explicit delegation and embraces the <strong>Template Method Pattern</strong> — but with a twist: the <strong>base logic is always called first</strong>, like super() in OOP. We call this the <strong>Base-First Composition Pattern</strong>.</p><h3>✅ Problem Statement</h3><p>Suppose you have a ProductsService gRPC server that serves the marketplace product listing endpoint:</p><ul><li>Returns a list of products available on the platform</li><li>Applies translations to product names, categories, etc., for the user</li><li>Converts product prices to the requested currency</li></ul><p>Originally, your ListProducts RPC might include all logic in one place, like:</p><pre>type ProductsService struct {<br>    productRepo     ProductRepository<br>    translationSvc  TranslationServiceClient<br>    exchangeSvc     ExchangeServiceClient<br>    marketplacev1.UnimplementedProductsServiceServer<br>}<br>func (s *ProductsService) ListProducts(ctx context.Context, req *pb.ListProductsRequest) (*pb.ListProductsResponse, error) {<br>    // query repo<br>    // translate text fields<br>    // apply currency conversion<br>    return &amp;pb.ListProductsResponse{...}, nil<br>}</pre><p>This violates SRP and makes testing difficult.</p><h3>💡 Solution: Base-First Composition Pattern</h3><p>Split the logic into composable gRPC server implementations. Each one handles a specific concern and delegates to a <strong>base implementation</strong> that defines the core logic.</p><h3>🔧 Core Implementation</h3><pre>type CoreProductsServer struct {<br>    repo ProductRepository<br>}<br><br>func (s *CoreProductsServer) ListProducts(ctx context.Context, req *pb.ListProductsRequest) (*pb.ListProductsResponse, error) {<br>    products := s.repo.Fetch(ctx, req.Filters)<br>    return &amp;pb.ListProductsResponse{Products: products}, nil<br>}</pre><h3>🌐 Translation Wrapper</h3><pre>type TranslatedProductsServer struct {<br>    base marketplacev1.ProductsServiceServer<br>    translator TranslationServiceClient<br>}<br>func (s *TranslatedProductsServer) ListProducts(ctx context.Context, req *pb.ListProductsRequest) (*pb.ListProductsResponse, error) {<br>    resp, err := s.base.ListProducts(ctx, req)<br>    if err != nil {<br>        return nil, err<br>    }<br>    for i, p := range resp.Products {<br>        translated, err := s.translator.Translate(ctx, p.Name, req.Language)<br>        if err == nil {<br>            resp.Products[i].Name = translated<br>        }<br>    }<br>    return resp, nil<br>}</pre><h3>💱 Exchange Wrapper</h3><pre>type ExchangedProductsServer struct {<br>    base marketplacev1.ProductsServiceServer<br>    exchanger ExchangeServiceClient<br>}<br><br>func (s *ExchangedProductsServer) ListProducts(ctx context.Context, req *pb.ListProductsRequest) (*pb.ListProductsResponse, error) {<br>    resp, err := s.base.ListProducts(ctx, req)<br>    if err != nil {<br>        return nil, err<br>    }<br>    for i, p := range resp.Products {<br>        newPrice, err := s.exchanger.Convert(ctx, p.Price, req.Currency)<br>        if err == nil {<br>            resp.Products[i].Price = newPrice<br>        }<br>    }<br>    return resp, nil<br>}</pre><h3>🧱 Assembling the Chain</h3><pre>core := &amp;CoreProductsServer{repo: productRepo}<br>translated := &amp;TranslatedProductsServer{base: core, translator: transClient}<br>exchanged := &amp;ExchangedProductsServer{base: translated, exchanger: exchClient}<br>grpcServer := grpc.NewServer()<br>marketplacev1.RegisterProductsServiceServer(grpcServer, exchanged))</pre><p>This guarantees:</p><ol><li>Core product retrieval is always run first</li><li>Then translations are applied</li><li>Then currency is adjusted</li></ol><p>Each extension only cares about its job.</p><h3>🧰 Visual Flowchart</h3><pre>┌─────────────────────┐<br>│ CoreProductsServer  │<br>│ - Fetches products  │<br>└─────────┬───────────┘<br>          │<br>          ▼<br>┌────────────────────────────┐<br>│ TranslatedProductsServer   │<br>│ - Translates product names │<br>└─────────┬──────────────────┘<br>          │<br>          ▼<br>┌─────────────────────────────┐<br>│ ExchangedProductsServer     │<br>│ - Converts product currency │<br>└─────────────────────────────┘</pre><p>Use this flowchart to visualize the composition clearly.</p><h3>🧱 Pattern Summary</h3><ul><li><strong>Base Implementation</strong> defines required core behavior.</li><li><strong>Wrapped Implementations</strong> use base.ListProducts() as the foundation.</li><li>Composition is <strong>ordered</strong>: base → translation → exchange.</li><li>Guarantees that core behavior <strong>always runs first</strong>.</li></ul><h3>⚙️ Comparison to Known Patterns</h3><pre>Pattern               | Similarity    |Notes<br>Template Method       | ✅✅✅        |The base defines the required flow; extensions add extra logic<br>Decorator (inverted)  | ✅✅          |It&#39;s like a decorator, but base runs first.<br>Explicit Delegation   | ✅✅          |Behavior layered via composition, not inheritance.</pre><p>This pattern is <strong>not middleware chaining</strong> (like HTTP handlers) where outer calls inner. It’s more like calling super() in OOP.</p><h3>🧪 Benefits</h3><ul><li>Enforces base business logic execution</li><li>Encourages separation of concerns</li><li>Facilitates testing each concern in isolation</li><li>Clean composable design with readable call order</li></ul><h3>⚠️ Gotchas</h3><ul><li>You must ensure each layer delegates to the base.</li><li>Codegen or interface embedding can help reduce boilerplate.</li><li>Use clear naming (base, not next) to avoid confusion with middleware.</li></ul><h3>🏁 Conclusion</h3><p>This Base-First Composition Pattern provides a clean, structured, and scalable way to build modular gRPC servers in Go. By simulating OOP-style inheritance through explicit delegation, you can enforce execution order while cleanly separating cross-cutting concerns.</p><p>In our example, each layer (product fetching, translation, exchange) stays simple and testable, while the full service behavior remains complete and correct.</p><h3>🛠 Bonus Tip</h3><p>If you find yourself repeating interface implementation code for each layer, consider using go:generate or a custom codegen tool to scaffold wrapper servers automatically.</p><p>Let your base logic shine. Let your extensions stay focused. Embrace Base-First Composition.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e1a4ac1c20f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>