<?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 Mucahid Uslu on Medium]]></title>
        <description><![CDATA[Stories by Mucahid Uslu on Medium]]></description>
        <link>https://medium.com/@mcuslu?source=rss-45e9ed53665d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*44JnZqkquSN30-ai-fPM4Q.jpeg</url>
            <title>Stories by Mucahid Uslu on Medium</title>
            <link>https://medium.com/@mcuslu?source=rss-45e9ed53665d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 15:33:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mcuslu/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[If You Don’t Know What You Want, Use Claude. If You Do, Use GPT]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://mcuslu.medium.com/if-you-dont-know-what-you-want-use-claude-if-you-do-use-gpt-61eecf9068be?source=rss-45e9ed53665d------2"><img src="https://cdn-images-1.medium.com/max/1205/1*2GiuSW4vPWm49x5eisQP-Q.jpeg" width="1205"></a></p><p class="medium-feed-snippet">The difference between vibe coding and AI-assisted software engineering is less about the model and more about who is behind the wheel.</p><p class="medium-feed-link"><a href="https://mcuslu.medium.com/if-you-dont-know-what-you-want-use-claude-if-you-do-use-gpt-61eecf9068be?source=rss-45e9ed53665d------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://mcuslu.medium.com/if-you-dont-know-what-you-want-use-claude-if-you-do-use-gpt-61eecf9068be?source=rss-45e9ed53665d------2</link>
            <guid isPermaLink="false">https://medium.com/p/61eecf9068be</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[sofware-development]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[future-of-work]]></category>
            <dc:creator><![CDATA[Mucahid Uslu]]></dc:creator>
            <pubDate>Tue, 14 Jul 2026 06:50:26 GMT</pubDate>
            <atom:updated>2026-07-14T06:50:26.658Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Stop Picking a Single GPT-5.6 Model: Why Intelligent AI Routing Beats a One-Model Strategy]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://mcuslu.medium.com/stop-picking-a-single-gpt-5-6-model-why-intelligent-ai-routing-beats-a-one-model-strategy-2990cdbdffc2?source=rss-45e9ed53665d------2"><img src="https://cdn-images-1.medium.com/max/1326/1*74O8n-nh9nbhMTanY1npfg.jpeg" width="1326"></a></p><p class="medium-feed-snippet">How to choose between Sol Medium, Sol High, Terra, and Luna and why autonomous AI agents should route tasks instead of relying on a single&#x2026;</p><p class="medium-feed-link"><a href="https://mcuslu.medium.com/stop-picking-a-single-gpt-5-6-model-why-intelligent-ai-routing-beats-a-one-model-strategy-2990cdbdffc2?source=rss-45e9ed53665d------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://mcuslu.medium.com/stop-picking-a-single-gpt-5-6-model-why-intelligent-ai-routing-beats-a-one-model-strategy-2990cdbdffc2?source=rss-45e9ed53665d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2990cdbdffc2</guid>
            <category><![CDATA[gpt-56]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[chat-gpt-ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[llm-benchmarks]]></category>
            <dc:creator><![CDATA[Mucahid Uslu]]></dc:creator>
            <pubDate>Fri, 10 Jul 2026 06:33:45 GMT</pubDate>
            <atom:updated>2026-07-10T06:33:45.180Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Why We Ditched the Ephemeris: Building a Custom Astrology Engine with Pure Math and AI]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://mcuslu.medium.com/why-we-ditched-the-ephemeris-building-a-custom-astrology-engine-with-pure-math-and-ai-cae29d706e57?source=rss-45e9ed53665d------2"><img src="https://cdn-images-1.medium.com/max/1115/1*Z3f7l6NFR-44hzBXY9RlLA.jpeg" width="1115"></a></p><p class="medium-feed-snippet">If you&#x2019;ve ever dipped your toes into building an astrology application, you know there is a universally accepted rule: You must use the&#x2026;</p><p class="medium-feed-link"><a href="https://mcuslu.medium.com/why-we-ditched-the-ephemeris-building-a-custom-astrology-engine-with-pure-math-and-ai-cae29d706e57?source=rss-45e9ed53665d------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://mcuslu.medium.com/why-we-ditched-the-ephemeris-building-a-custom-astrology-engine-with-pure-math-and-ai-cae29d706e57?source=rss-45e9ed53665d------2</link>
            <guid isPermaLink="false">https://medium.com/p/cae29d706e57</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[astrology]]></category>
            <dc:creator><![CDATA[Mucahid Uslu]]></dc:creator>
            <pubDate>Thu, 09 Jul 2026 07:07:46 GMT</pubDate>
            <atom:updated>2026-07-09T07:20:30.085Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Logging with .NET Core and OpenSearch: Building Dashboards with Serilog, CloudWatch, and AWS Lambda]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://mcuslu.medium.com/logging-with-net-core-and-opensearch-building-dashboards-with-serilog-cloudwatch-and-aws-lambda-c06f9df510c3?source=rss-45e9ed53665d------2"><img src="https://cdn-images-1.medium.com/max/2600/1*ahxJODR7MNb09vU3Ef_bDw.gif" width="3750"></a></p><p class="medium-feed-snippet">When building cloud-native applications, logging is more than just writing messages, it is about gaining visibility, diagnosing issues&#x2026;</p><p class="medium-feed-link"><a href="https://mcuslu.medium.com/logging-with-net-core-and-opensearch-building-dashboards-with-serilog-cloudwatch-and-aws-lambda-c06f9df510c3?source=rss-45e9ed53665d------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://mcuslu.medium.com/logging-with-net-core-and-opensearch-building-dashboards-with-serilog-cloudwatch-and-aws-lambda-c06f9df510c3?source=rss-45e9ed53665d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c06f9df510c3</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloudwatch]]></category>
            <category><![CDATA[lambda-function]]></category>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[opensearch]]></category>
            <dc:creator><![CDATA[Mucahid Uslu]]></dc:creator>
            <pubDate>Mon, 23 Jun 2025 08:35:10 GMT</pubDate>
            <atom:updated>2025-06-23T08:35:10.402Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[OutBox Pattern: Mastering Data Consistency in Distributed Systems with .NET Core]]></title>
            <link>https://mcuslu.medium.com/outbox-pattern-mastering-data-consistency-in-distributed-systems-with-net-core-9c1a25323225?source=rss-45e9ed53665d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c1a25323225</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[event-driven]]></category>
            <dc:creator><![CDATA[Mucahid Uslu]]></dc:creator>
            <pubDate>Mon, 09 Jun 2025 09:54:03 GMT</pubDate>
            <atom:updated>2025-06-23T08:49:04.276Z</atom:updated>
            <content:encoded><![CDATA[<h3>OutBox Pattern: Mastering Data Consistency in Distributed Systems with .NET Core</h3><h3>A practical guide to implementing reliable event-driven architecture using flight check-in as a real-world example.</h3><p>Modern distributed systems rely heavily on asynchronous communication between services. However, achieving reliable communication, especially when persisting data and sending messages across services is not trivial. One of the most common challenges is the <strong>dual write problem</strong>, where writing to a database and sending a message to a queue must both succeed or fail together.</p><p>This is where the <strong>Outbox Pattern</strong> comes in.</p><p>&gt;&gt;&gt; In this article, we’ll explore the Outbox Pattern and implement it using <strong>.NET Core</strong> in the context of an <strong>online flight check-in system</strong>.</p><h4>The Problem: When Everything Goes Wrong at Once</h4><p>Imagine this: You’re building a flight check-in system. A passenger successfully checks in, but then your email service crashes right after saving the check-in data. The passenger is checked in according to your database, but they never receive their boarding pass. Your SMS service is down too, so no confirmation text. Even worse, their loyalty points aren’t updated because that service is also experiencing issues.</p><p>This is the classic <strong>dual-write problem</strong> in distributed systems. You need to write to your database AND communicate with external services, but these operations aren’t atomic. If any part fails, your system becomes inconsistent.</p><p>Welcome to the world of distributed systems, where Murphy’s Law reigns supreme.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ZpKRA8kBK8bF0eB3UvYbw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jannerboy62?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Nick Fewings</a> on <a href="https://unsplash.com/photos/building-interior-photograph-l5fDJ3I-9Uk?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h3>Enter the OutBox Pattern</h3><p>The OutBox Pattern is an elegant solution that ensures data consistency in distributed systems by leveraging database transactions and asynchronous processing. Instead of directly calling external services during your main business operation, you store events in an “outbox” table within the same database transaction. A background processor then reliably delivers these events to external systems.</p><p>Think of it as a reliable postal service for your microservices.</p><h3>Real-World Scenario: Flight Check-In System</h3><p>Let’s implement a flight check-in system where multiple things need to happen when a passenger checks in:</p><ol><li><strong>Save check-in data</strong> to the database</li><li><strong>Generate boarding pass</strong> via PDF service</li><li><strong>Send email</strong> with boarding pass attached</li><li><strong>Send SMS confirmation</strong></li><li><strong>Update loyalty points</strong></li></ol><p>If any of these steps fail, we don’t want to leave our system in an inconsistent state.</p><h4>The Implementation</h4><h4>Step 1: Domain Models and OutBox Event</h4><pre>// Domain Models<br>public class CheckIn<br>{<br>    public int Id { get; set; }<br>    public string PassengerId { get; set; }<br>    public string FlightNumber { get; set; }<br>    public string SeatNumber { get; set; }<br>    public DateTime CheckInTime { get; set; }<br>    public CheckInStatus Status { get; set; }<br>}<br><br>// OutBox Event Model<br>public class OutBoxEvent<br>{<br>    public int Id { get; set; }<br>    public string EventType { get; set; }<br>    public string EventData { get; set; }<br>    public DateTime CreatedAt { get; set; }<br>    public bool IsProcessed { get; set; }<br>    public DateTime? ProcessedAt { get; set; }<br>    public int RetryCount { get; set; }<br>}<br><br>// Event Data<br>public class CheckInCompletedEvent<br>{<br>    public string PassengerId { get; set; }<br>    public string FlightNumber { get; set; }<br>    public string SeatNumber { get; set; }<br>    public string PassengerEmail { get; set; }<br>    public string PassengerPhone { get; set; }<br>    public DateTime CheckInTime { get; set; }<br>}</pre><h4>Step 2: The Critical Transaction</h4><p>Here’s where the magic happens. The check-in service saves both the business data and the outbox event in a <strong>single database transaction</strong>:</p><pre>public class CheckInService<br>{<br>    private readonly FlightDbContext _context;<br>    private readonly ILogger&lt;CheckInService&gt; _logger;<br><br>    public async Task&lt;bool&gt; ProcessCheckInAsync(CheckInRequest request)<br>    {<br>        using var transaction = await _context.Database.BeginTransactionAsync();<br>        try<br>        {<br>            // 1. Save check-in data<br>            var checkIn = new CheckIn<br>            {<br>                PassengerId = request.PassengerId,<br>                FlightNumber = request.FlightNumber,<br>                SeatNumber = request.SeatNumber,<br>                CheckInTime = DateTime.UtcNow,<br>                Status = CheckInStatus.Completed<br>            };<br><br>            _context.CheckIns.Add(checkIn);<br><br>            // 2. Create OutBox Event - Same transaction!<br>            var checkInEvent = new CheckInCompletedEvent<br>            {<br>                PassengerId = request.PassengerId,<br>                FlightNumber = request.FlightNumber,<br>                SeatNumber = request.SeatNumber,<br>                PassengerEmail = request.Email,<br>                PassengerPhone = request.Phone,<br>                CheckInTime = checkIn.CheckInTime<br>            };<br><br>            var outBoxEvent = new OutBoxEvent<br>            {<br>                EventType = nameof(CheckInCompletedEvent),<br>                EventData = JsonSerializer.Serialize(checkInEvent),<br>                CreatedAt = DateTime.UtcNow,<br>                IsProcessed = false,<br>                RetryCount = 0<br>            };<br><br>            _context.OutBoxEvents.Add(outBoxEvent);<br><br>            // 3. Commit everything together<br>            await _context.SaveChangesAsync();<br>            await transaction.CommitAsync();<br><br>            return true;<br>        }<br>        catch (Exception ex)<br>        {<br>            await transaction.RollbackAsync();<br>            _logger.LogError(ex, $&quot;Check-in failed for passenger {request.PassengerId}&quot;);<br>            return false;<br>        }<br>    }<br>}</pre><p><strong>Key Point:</strong> Either both the check-in data AND the outbox event are saved, or neither is. This is our consistency garantee.</p><h4>Step 3: The Background Processor</h4><p>A background service continuously polls the outbox table and processes unhandled events:</p><pre>public class OutBoxProcessor : BackgroundService<br>{<br>    private readonly IServiceProvider _serviceProvider;<br>    private readonly ILogger&lt;OutBoxProcessor&gt; _logger;<br><br>    protected override async Task ExecuteAsync(CancellationToken stoppingToken)<br>    {<br>        while (!stoppingToken.IsCancellationRequested)<br>        {<br>            try<br>            {<br>                await ProcessOutBoxEventsAsync();<br>                await Task.Delay(5000, stoppingToken); // Poll every 5 seconds<br>            }<br>            catch (Exception ex)<br>            {<br>                _logger.LogError(ex, &quot;Error processing outbox events&quot;);<br>                await Task.Delay(10000, stoppingToken); // Wait 10s on error<br>            }<br>        }<br>    }<br><br>    private async Task ProcessOutBoxEventsAsync()<br>    {<br>        using var scope = _serviceProvider.CreateScope();<br>        var context = scope.ServiceProvider.GetRequiredService&lt;FlightDbContext&gt;();<br>        var eventPublisher = scope.ServiceProvider.GetRequiredService&lt;IEventPublisher&gt;();<br><br>        var unprocessedEvents = await context.OutBoxEvents<br>            .Where(e =&gt; !e.IsProcessed &amp;&amp; e.RetryCount &lt; 5)<br>            .OrderBy(e =&gt; e.CreatedAt)<br>            .Take(10)<br>            .ToListAsync();<br><br>        foreach (var outBoxEvent in unprocessedEvents)<br>        {<br>            try<br>            {<br>                await ProcessSingleEventAsync(eventPublisher, outBoxEvent);<br>                <br>                outBoxEvent.IsProcessed = true;<br>                outBoxEvent.ProcessedAt = DateTime.UtcNow;<br>            }<br>            catch (Exception ex)<br>            {<br>                outBoxEvent.RetryCount++;<br>                _logger.LogWarning(ex, $&quot;Failed to process event {outBoxEvent.Id}, retry: {outBoxEvent.RetryCount}&quot;);<br>            }<br>        }<br><br>        if (unprocessedEvents.Any())<br>        {<br>            await context.SaveChangesAsync();<br>        }<br>    }<br>}</pre><h4>Step 4: Event Publisher and External Service Integration</h4><p>The event publisher handles the actual communication with external services:</p><pre>public class EventPublisher : IEventPublisher<br>{<br>    private readonly IEmailService _emailService;<br>    private readonly ISmsService _smsService;<br>    private readonly IBoardingPassService _boardingPassService;<br>    private readonly ILoyaltyService _loyaltyService;<br><br>    public async Task PublishCheckInCompletedAsync(CheckInCompletedEvent eventData)<br>    {<br>        // Execute all external service calls in parallel<br>        var tasks = new List&lt;Task&gt;<br>        {<br>            SendBoardingPassEmailAsync(eventData),<br>            SendCheckInSmsAsync(eventData),<br>            UpdateLoyaltyPointsAsync(eventData)<br>        };<br><br>        await Task.WhenAll(tasks);<br>    }<br><br>    private async Task SendBoardingPassEmailAsync(CheckInCompletedEvent eventData)<br>    {<br>        try<br>        {<br>            var boardingPass = await _boardingPassService.GenerateBoardingPassAsync(<br>                eventData.PassengerId, <br>                eventData.FlightNumber, <br>                eventData.SeatNumber);<br>            <br>            await _emailService.SendBoardingPassAsync(<br>                eventData.PassengerEmail, <br>                boardingPass);<br>        }<br>        catch (Exception ex)<br>        {<br>            _logger.LogError(ex, $&quot;Failed to send boarding pass email&quot;);<br>            throw; // Let OutBox processor handle retry<br>        }<br>    }<br>}</pre><h3>Architecture Overview</h3><p>The complete flow works like this:</p><ol><li><strong>Request arrives</strong> → Check-in API receives the request</li><li><strong>Transaction begins</strong> → Both check-in data and outbox event are saved atomically</li><li><strong>Immediate response</strong> → User gets confirmation without waiting for external services</li><li><strong>Background processing</strong> → OutBox processor continuously polls for unprocessed events</li><li><strong>Event publishing</strong> → External services are called asynchronously</li><li><strong>Retry mechanism</strong> → Failed events are retried with exponential backoff</li><li><strong>Status update</strong> → Successful events are marked as processed.</li></ol><h3>Flight Check-in Service Diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3g5MoTQpTVCMN6UzWg6t6Q.jpeg" /></figure><p>&gt;&gt;&gt; Click here for <a href="https://www.mermaidchart.com/app/projects/5ac4f72c-53bc-429a-b54e-6144de74ec56/diagrams/b18f3818-c5ff-4108-bc34-183d8a133b12/version/v0.1/edit">flight check-in service diagram</a></p><h3>Benefits of OutBox Pattern</h3><h4>🎯 Atomicity</h4><p>Your busines operation and event creation happen in a single transaction. No partial failures.</p><h4>⚡ Performance</h4><p>Users get immediate responses. Heavy operations happen asynchronously in the background.</p><h4>🔄 Reliability</h4><p>Built-in retry mechanism handles temporary failures. Events are never lost.</p><h4>📈 Scalability</h4><p>Background procesors can be scaled independent based on load.</p><h4>🧩 Decoupling</h4><p>Your core busines logic isn’t tightly coupled to external service availability.</p><h4>* Idempotency is Key</h4><p>External services might receive the same event multiple times. Design them to handle duplicate requests gracefully:</p><pre>// Example: Idempotent email service<br>public async Task SendBoardingPassAsync(string email, byte[] boardingPass, string idempotencyKey)<br>{<br>    // Check if already sent using idempotency key<br>    if (await _emailRepository.HasBeenSentAsync(idempotencyKey))<br>    {<br>        return; // Already sent, skip<br>    }<br>    <br>    await SendEmailAsync(email, boardingPass);<br>    await _emailRepository.MarkAsSentAsync(idempotencyKey);<br>}</pre><h4>* Dead Letter Queue</h4><p>Events that fail multiple times need special handling:</p><pre>// In your processor<br>if (outBoxEvent.RetryCount &gt;= MAX_RETRIES)<br>{<br>    await MoveToDeadLetterQueueAsync(outBoxEvent);<br>    outBoxEvent.IsProcessed = true; // Don&#39;t retry anymore<br>}</pre><h4>* OutBox Cleanup</h4><p>Procesed events should be archived or deleted to prevent table growth:</p><pre>// Cleanup job<br>public async Task CleanupProcessedEventsAsync()<br>{<br>    var cutoffDate = DateTime.UtcNow.AddDays(-30);<br>    await _context.OutBoxEvents<br>        .Where(e =&gt; e.IsProcessed &amp;&amp; e.ProcessedAt &lt; cutoffDate)<br>        .DeleteAsync();<br>}</pre><h4>* Monitoring and Alerting</h4><p>Track OutBox health with metrics:</p><ul><li>Number of unprocessed events</li><li>Average processing time</li><li>Retry counts</li><li>Dead letter queue size</li></ul><h3>When to Use OutBox Pattern</h3><p><strong>✅ Use when:</strong></p><ul><li>You need to maintain data consistency across services</li><li>External service failures shouldn’t affect your core business logic</li><li>You’re building event-driven microservices</li><li>You need reliable message delivery</li></ul><p><strong>❌ Avoid when:</strong></p><ul><li>You need real-time synchronous processing</li><li>Your system is simple and doesnt require distributed transactions</li><li>Performance overhead of background processing is unacceptable</li></ul><h3>Summary</h3><p>The <strong>Outbox Pattern</strong> is a powerful and reliable approach to ensure consistency between your database and your event streams. In a system like an <strong>online flight check-in</strong>, it’s critical that other systems are notified of a check-in event. Using this pattern with .NET Core ensures that your event-driven architecture remains both robust and scalable.</p><h3>Conclusion</h3><p>The OutBox Pattern is a powerful tool for building resilient distributed systems. By leveraging database transactions and asynchronous processing, it solves the dual-write problem elegantly while providing excellent performance and reliability characteristics.</p><p>In our flight check-in example, passengers get immediate confirmation of their check-in while boarding passes, SMS notifications, and loyalty points are processed reliably in the background. Even if external services are temporarily unavailable, the system remains consistent and eventually delivers all promised functionality.</p><p>The pattern requires careful consideration of idempotency, error handling, and monitoring, but the benefits of consistency and reliability make it worthwhile for any serious distributed system.</p><p>Remember: In distributed systems, it’s not a matter of <em>if</em> something will fail, but <em>when</em>. The OutBox Pattern helps you sleep better at night knowing your system can handle those inevitable failures gracefully.</p><p>&gt;&gt;&gt; If you’re building distributed systems in .NET and care about data integrity, <strong>the Outbox Pattern should be in your toolkit</strong>.</p><p><em>Have you implemented the OutBox Pattern in your projects? What challenges did you face? Share your experiences in the comments below! Thank you.</em></p><p><em>Links</em></p><ul><li>My personal contact links here &gt;&gt; <a href="https://www.mcuslu.com/">https://www.mcuslu.com/</a></li><li>Flight Check-in Service Diagram &gt;&gt; <a href="https://www.mermaidchart.com/app/projects/5ac4f72c-53bc-429a-b54e-6144de74ec56/diagrams/b18f3818-c5ff-4108-bc34-183d8a133b12/version/v0.1/edit">diagram here..</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c1a25323225" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Legacy Systems Modernization: Code First OR Database First?]]></title>
            <link>https://mcuslu.medium.com/legacy-systems-modernization-code-first-or-database-first-c37e28debe7c?source=rss-45e9ed53665d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c37e28debe7c</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[code-first]]></category>
            <category><![CDATA[database-first]]></category>
            <category><![CDATA[legacy-systems]]></category>
            <dc:creator><![CDATA[Mucahid Uslu]]></dc:creator>
            <pubDate>Fri, 06 Jun 2025 18:06:07 GMT</pubDate>
            <atom:updated>2025-06-06T18:06:07.929Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This may be controversial, but I interpreted it according to both my own experience and the dynamics and realities of the projects I encountered in practice.</em></p><p>Modernizing legacy systems is a delicate balance between preserving business-critical functionality and embracing newer, maintainable technologies. One of the core decisions you’ll face when modernizing a legacy application backed by a large SQL Server database is:<br> <strong>Should we use Entity Framework Core with Code First or Database First?</strong></p><p>Having worked on real-world modernization efforts, I’d like to walk you through the reasoning, trade-offs, and a recommended strategy when you’re dealing with a mature SQL Server database with hundreds of tables, views, and stored procedures.</p><h3>The Legacy Landscape</h3><p>Let’s define what we’re dealing with:</p><ul><li>An ASP.NET (Web Forms or MVC) monolithic application</li><li>Backed by Microsoft SQL Server</li><li>Dozens or hundreds of tables</li><li>Heavy use of stored procedures, views, triggers, and hand-written SQL</li></ul><p>The goal? Transition the system to a more modern architecture, often using ASP.NET Core, Entity Framework Core, and a service-oriented or clean architecture pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QmMU4Lb5D592jXeUQT2RnA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@cedericvandenberghe?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Cederic Vandenberghe</a> on <a href="https://unsplash.com/photos/closeup-photo-of-castle-with-mist-21DP3hytVHw?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p><strong>** Code First Approach **</strong></p><p>Define models in code and let EF generate the database.</p><p>Best for : Greenfield projects or full redesigns.</p><p><strong>** Database First Approach **</strong></p><p>Scaffold models from an existing database schema.</p><p>Legacy systems with complex existing databases.</p><h3>Why <strong>Database First</strong> Makes More Sense for Legacy Systems</h3><h4>1. The Database is Already Stable and Production-Proven</h4><p>The existing schema is likely the result of years of real-world iteration. Attempting to re-create it using Code First is not only time-consuming, but it also introduces risk.</p><h4>2. Stored Procedures and Views are Everywhere</h4><p>Many legacy systems use stored procedures for core logic, performance tuning, or security boundaries. EF Core (especially v7+) supports calling stored procedures and mapping to models, but reverse engineering this setup is easier with Database First.</p><h4>3. Faster Time-to-Value</h4><p>Using Scaffold-DbContext, you can generate all your entity classes and a working DbContext in minutes. That gives you a head start in building APIs, services, and even front-end apps, without having to redesign your database.</p><h4>When NOT to Use Code First</h4><ul><li>You’re not allowed to alter the database schema freely</li><li>You have complex logic encapsulated in Stored Procedures or triggers..</li><li>The schema is huge, and mapping it manually would take weeks</li></ul><h4>When Code First Might Be a Good Choice</h4><ul><li>You’re building <strong>new services or modules</strong> in parallel</li><li>You’re allowed to <strong>refactor and redesign</strong> the schema gradually</li><li>You’re adopting <strong>Domain-Driven Design (DDD)</strong> and want models to evolve independently</li></ul><p>You can even <strong>mix and match</strong>: keep the legacy parts on Database First, and build new services or bounded contexts using Code First.</p><h3>Recommended Migration Strategy</h3><p>Here’s a practical approach you can take:</p><h4>Step 1: Use Scaffold-DbContext to Reverse Engineer</h4><h4>Step 2: Wrap Legacy Logic in a Service Layer</h4><p>Start adding abstractions (services, repositories) on top of your generated models.</p><h4>Step 3: Use Dapper or Raw SQL for Complex SPs (if needed)</h4><p>EF Core can work, but Dapper can still be more practical in legacy-heavy areas.</p><h4>Step 4: Introduce Code First in New Services</h4><p>As you carve out new features or microservices, adopt Code First where you can define the domain and schema from scratch.</p><h4>Step 5: Gradually Rebuild / Refactor When Needed</h4><p>If parts of the schema become bottlenecks, consider refactoring those areas into modern modules.</p><p>Modernizing a legacy ASP.NET + SQL Server application is not a one-size-fits-all task. <strong>Database First gives you a safe and pragmatic starting point</strong>, especially when working with an established, complex schema. From there, you can gradually evolve parts of the system into <strong>Code First</strong>, testable, and maintainable domains.</p><p>It’s not about choosing one or the other forever, it’s about choosing the right tool for each stage of your journey.</p><p><em>Have you modernized a legacy system recently? Share your experience in the comments!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c37e28debe7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flight Ticketing System with Decorator and Factory Patterns in C#]]></title>
            <link>https://mcuslu.medium.com/flight-ticketing-system-with-decorator-and-factory-patterns-in-c-d962f759433d?source=rss-45e9ed53665d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d962f759433d</guid>
            <category><![CDATA[factory-pattern]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[decorator-pattern]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Mucahid Uslu]]></dc:creator>
            <pubDate>Mon, 02 Jun 2025 04:18:52 GMT</pubDate>
            <atom:updated>2025-06-02T06:14:52.481Z</atom:updated>
            <content:encoded><![CDATA[<p>In modern software architecture, flexibility and extensibility are essential. Today, we’ll walk through a real-world example where we design a <strong>Flight Ticket Booking System</strong> using the <strong>Decorator</strong> and <strong>Factory</strong> design patterns in C#.</p><blockquote><em>This post is ideal for intermediate developers looking to apply design patterns in practical scenarios.</em></blockquote><h4>Scenario: The Ticket System</h4><p>Imagine we’re building a flight booking system where a customer can:</p><ul><li>Choose a <strong>base ticket class</strong>: Economy or Business</li><li>Add <strong>optional features</strong>: Extra baggage, lounge access, priority check-in, etc.</li><li>Apply <strong>promotions</strong> like discounts</li></ul><p>The system must allow combining any number of extras without changing the original ticket logic.</p><p>Decorator Pattern Simple UML :</p><pre>        Component (Interface / Abstract)<br>           ↑<br>ConcreteComponent <br>           ↑<br>    Decorator (Abstract)<br>           ↑<br>ConcreteDecorator </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P5iYppJbvoRV8oLhaVx3Mg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@joshwithers?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Josh Withers</a> on <a href="https://unsplash.com/photos/a-large-sign-with-a-lot-of-numbers-on-it-L4Yc_e-IAYU?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>#1: Define the Ticket Interface</p><pre>public interface IFlightTicket<br>{<br>    string GetDescription();<br>    double GetPrice();<br>}</pre><p>#2: Base Ticket Types</p><pre>public class EconomyTicket : IFlightTicket<br>{<br>    public string GetDescription() =&gt; &quot;Economy Class Ticket&quot;;<br>    public double GetPrice() =&gt; 1000;<br>}<br><br>public class BusinessTicket : IFlightTicket<br>{<br>    public string GetDescription() =&gt; &quot;Business Class Ticket&quot;;<br>    public double GetPrice() =&gt; 2500;<br>}</pre><p>#3: Base Decorator Class</p><pre>public abstract class TicketDecorator : IFlightTicket<br>{<br>    protected IFlightTicket _baseTicket;<br><br>    protected TicketDecorator(IFlightTicket baseTicket)<br>    {<br>        _baseTicket = baseTicket;<br>    }<br><br>    public virtual string GetDescription() =&gt; _baseTicket.GetDescription();<br>    public virtual double GetPrice() =&gt; _baseTicket.GetPrice();<br>}</pre><p>#4: Concrete Decorators</p><pre>public class ExtraBaggage : TicketDecorator<br>{<br>    public ExtraBaggage(IFlightTicket baseTicket) : base(baseTicket) { }<br><br>    public override string GetDescription() =&gt; _baseTicket.GetDescription() + &quot;, Extra Baggage&quot;;<br>    public override double GetPrice() =&gt; _baseTicket.GetPrice() + 200;<br>}<br><br>public class LoungeAccess : TicketDecorator<br>{<br>    public LoungeAccess(IFlightTicket baseTicket) : base(baseTicket) { }<br><br>    public override string GetDescription() =&gt; _baseTicket.GetDescription() + &quot;, Lounge Access&quot;;<br>    public override double GetPrice() =&gt; _baseTicket.GetPrice() + 300;<br>}<br><br>public class PriorityCheckIn : TicketDecorator<br>{<br>    public PriorityCheckIn(IFlightTicket baseTicket) : base(baseTicket) { }<br><br>    public override string GetDescription() =&gt; _baseTicket.GetDescription() + &quot;, Priority Check-In&quot;;<br>    public override double GetPrice() =&gt; _baseTicket.GetPrice() + 150;<br>}<br><br>public class PromoDiscount : TicketDecorator<br>{<br>    private readonly double _discount;<br><br>    public PromoDiscount(IFlightTicket baseTicket, double discount) : base(baseTicket)<br>    {<br>        _discount = discount;<br>    }<br><br>    public override string GetDescription() =&gt; _baseTicket.GetDescription() + $&quot; (Promo -{_discount}%)&quot;;<br>    public override double GetPrice() =&gt; _baseTicket.GetPrice() * ((100 - _discount) / 100.0);<br>}</pre><p>#5: Adding Factory Logic for Extras</p><pre>public static class TicketDecoratorFactory<br>{<br>    public static IFlightTicket ApplyDecorators(IFlightTicket baseTicket, List&lt;string&gt; decorators)<br>    {<br>        IFlightTicket ticket = baseTicket;<br><br>        foreach (var decorator in decorators)<br>        {<br>            if (decorator.StartsWith(&quot;PromoDiscount&quot;))<br>            {<br>                var parts = decorator.Split(&#39;:&#39;);<br>                if (parts.Length == 2 &amp;&amp; double.TryParse(parts[1], out double discount))<br>                {<br>                    ticket = new PromoDiscount(ticket, discount);<br>                }<br>            }<br>            else<br>            {<br>                switch (decorator)<br>                {<br>                    case &quot;ExtraBaggage&quot;:<br>                        ticket = new ExtraBaggage(ticket);<br>                        break;<br>                    case &quot;LoungeAccess&quot;:<br>                        ticket = new LoungeAccess(ticket);<br>                        break;<br>                    case &quot;PriorityCheckIn&quot;:<br>                        ticket = new PriorityCheckIn(ticket);<br>                        break;<br>                }<br>            }<br>        }<br><br>        return ticket;<br>    }<br>}</pre><p>#6: JSON Configuration Support</p><p>We want to dynamically create tickets based on a JSON input like this:</p><pre>{<br>  &quot;ticketType&quot;: &quot;Economy&quot;,<br>  &quot;extras&quot;: [<br>    &quot;ExtraBaggage&quot;,<br>    &quot;LoungeAccess&quot;,<br>    &quot;PromoDiscount:10&quot;<br>  ]<br>}</pre><p>Configuration Class:</p><pre>public class TicketConfig<br>{<br>    public string TicketType { get; set; } = &quot;Economy&quot;;<br>    public List&lt;string&gt; Extras { get; set; } = new();<br>}</pre><p>Ticket Factory:</p><pre>public static class TicketFactory<br>{<br>    public static IFlightTicket CreateBaseTicket(string ticketType)<br>    {<br>        return ticketType switch<br>        {<br>            &quot;Economy&quot; =&gt; new EconomyTicket(),<br>            &quot;Business&quot; =&gt; new BusinessTicket(),<br>            _ =&gt; throw new ArgumentException($&quot;Unknown ticket type: {ticketType}&quot;)<br>        };<br>    }<br>}</pre><p>Complete Builder:</p><pre>public static class FlightTicketBuilder<br>{<br>    public static IFlightTicket BuildFromConfig(TicketConfig config)<br>    {<br>        var baseTicket = TicketFactory.CreateBaseTicket(config.TicketType);<br>        var fullTicket = TicketDecoratorFactory.ApplyDecorators(baseTicket, config.Extras);<br>        return fullTicket;<br>    }<br>}</pre><p>Usage:</p><pre>var json = &quot;&quot;&quot;<br>{<br>  &quot;ticketType&quot;: &quot;Economy&quot;,<br>  &quot;extras&quot;: [<br>    &quot;ExtraBaggage&quot;,<br>    &quot;LoungeAccess&quot;,<br>    &quot;PromoDiscount:10&quot;<br>  ]<br>}<br>&quot;&quot;&quot;;<br><br>var config = JsonSerializer.Deserialize&lt;TicketConfig&gt;(json)!;<br><br>var finalTicket = FlightTicketBuilder.BuildFromConfig(config);<br><br>Console.WriteLine(finalTicket.GetDescription());<br>// Economy Class Ticket, Extra Baggage, Lounge Access (Promo -10%)<br><br>Console.WriteLine(finalTicket.GetPrice());</pre><h4>What We Learned</h4><ul><li><strong>Decorator Pattern</strong> lets us add behavior without modifying original classes.</li><li><strong>Factory Pattern</strong> helps manage instantiation dynamically.</li><li>Combining them provides a powerful and extensible architecture.</li><li>Real-world systems like booking engines benefit greatly from this approach.</li></ul><h4>Ideas ++</h4><ul><li>We can create combo packs (e.g., <em>Comfort Pack</em> = Lounge + Priority + Extra Baggage)</li><li>Allow decorators to be registered dynamically using reflection</li><li>Apply SOLID principles by abstracting creation and configuration</li></ul><p>Design patterns aren’t about complexity, they’re about <strong>clarity</strong>, <strong>reusability</strong>, and <strong>extensibility</strong>. By combining Decorator and Factory patterns, you can elegantly build flexible systems that grow with your product.</p><p>❋ <em>Thanks for reading! If you enjoyed this article, follow me for more design pattern deep dives and real-world C# solutions.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d962f759433d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Applying SOLID Principles in .NET Core: Flight Search & Ticket Booking Example]]></title>
            <link>https://mcuslu.medium.com/applying-solid-principles-in-net-core-flight-search-ticket-booking-example-9e811837333d?source=rss-45e9ed53665d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e811837333d</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[solid-principles]]></category>
            <dc:creator><![CDATA[Mucahid Uslu]]></dc:creator>
            <pubDate>Sun, 01 Jun 2025 08:49:27 GMT</pubDate>
            <atom:updated>2025-06-01T13:18:51.634Z</atom:updated>
            <content:encoded><![CDATA[<h3>Applying SOLID Principles in .NET Core: Flight Search &amp; Ticket Example</h3><p>Clean, maintainable, and testable code isn’t a luxury, it’s a necessity in modern software development. One of the best ways to achieve this is by following the <strong>SOLID</strong> principles.</p><p>In this article, we’ll walk through each SOLID principle using a real-world <strong>Flight Search and Ticket Booking</strong> scenario built with <strong>.NET Core</strong>. You’ll see not only the theory, but how it translates to clean architecture and extensible code.</p><h4>What is SOLID?</h4><p><strong>SOLID</strong> is an acronym for five design principles that help software developers build better code:</p><ol><li><strong>S</strong>ingle Responsibility Principle</li><li><strong>O</strong>pen/Closed Principle</li><li><strong>L</strong>iskov Substitution Principle</li><li><strong>I</strong>nterface Segregation Principle</li><li><strong>D</strong>ependency Inversion Principle</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y2fJWOfW6uK-7Yj2wn7CGA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@anniespratt?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Annie Spratt</a> on <a href="https://unsplash.com/photos/group-of-people-using-laptop-computer-QckxruozjRg?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h4>The Scenario</h4><p>We’re building a system where users can:</p><ul><li>Search available flights.</li><li>Book tickets for selected flights.</li><li>Process payments and check seat availability.</li><li>Apply discounts based on policies.</li></ul><p>Let’s break this system down with SOLID principles.</p><h4>* (S)ingle Responsibility Principle (SRP)</h4><blockquote><em>A class should have one and only one reason to change.</em></blockquote><p>Each class should focus on a single task, not mix responsibilities like flight search, seat check, or payment.</p><h4>Example</h4><p>Each class handles <strong>only one</strong> concern.</p><pre>public class FlightSearchService<br>{<br>    private readonly IFlightRepository _repository;<br><br>    public FlightSearchService(IFlightRepository repository)<br>    {<br>        _repository = repository;<br>    }<br><br>    public IEnumerable&lt;Flight&gt; SearchFlights(string origin, string destination, DateTime date)<br>    {<br>        return _repository.GetFlights(origin, destination, date);<br>    }<br>}</pre><pre>public class TicketPurchaseService<br>{<br>    private readonly IPaymentService _paymentService;<br>    private readonly ISeatAvailabilityService _seatService;<br>    private readonly ITicketRepository _ticketRepository;<br><br>    public TicketPurchaseService(IPaymentService paymentService, ISeatAvailabilityService seatService, ITicketRepository ticketRepository)<br>    {<br>        _paymentService = paymentService;<br>        _seatService = seatService;<br>        _ticketRepository = ticketRepository;<br>    }<br><br>    public Ticket Purchase(Guid flightId, string passengerName, string creditCard)<br>    {<br>        if (!_seatService.IsSeatAvailable(flightId))<br>            throw new Exception(&quot;No seats available.&quot;);<br><br>        _paymentService.ProcessPayment(creditCard);<br><br>        var ticket = new Ticket(Guid.NewGuid(), flightId, passengerName, DateTime.UtcNow);<br>        _ticketRepository.Save(ticket);<br><br>        return ticket;<br>    }<br>}</pre><h4>* (O)pen/Closed Principle (OCP)</h4><blockquote><em>Classes should be open for extension but closed for modification.</em></blockquote><p>You should be able to add new features without changing existing code.</p><h4>Example: Discount Policies</h4><p>Adding new discount types doesn’t affect existing logic.</p><pre>public interface IDiscountPolicy<br>{<br>    decimal Apply(decimal basePrice);<br>}<br><br>public class NoDiscount : IDiscountPolicy<br>{<br>    public decimal Apply(decimal basePrice) =&gt; basePrice;<br>}<br><br>public class StudentDiscount : IDiscountPolicy<br>{<br>    public decimal Apply(decimal basePrice) =&gt; basePrice * 0.8m;<br>}</pre><pre>public class TicketPriceCalculator<br>{<br>    private readonly IDiscountPolicy _discountPolicy;<br><br>    public TicketPriceCalculator(IDiscountPolicy discountPolicy)<br>    {<br>        _discountPolicy = discountPolicy;<br>    }<br><br>    public decimal Calculate(decimal basePrice)<br>    {<br>        return _discountPolicy.Apply(basePrice);<br>    }<br>}</pre><h4>* (L)iskov Substitution Principle (LSP)</h4><blockquote><em>Subtypes must be substitutable for their base types.</em></blockquote><p>Derived classes should work as drop-in replacements for their base class without altering behavior.</p><h4>Example: Flight Duration</h4><p>The Print() method works regardless of the flight type.</p><pre>public class FlightDurationPrinter<br>{<br>    public void Print(Flight flight)<br>    {<br>        Console.WriteLine($&quot;Flight {flight.Code} duration: {flight.GetDuration()}&quot;);<br>    }<br>}</pre><h4>* (I)nterface Segregation Principle (ISP)</h4><blockquote><em>No client should be forced to depend on methods it does not use.</em></blockquote><p>Split large interfaces into smaller, more specific ones.</p><h4>Refactored Interface Design</h4><p>Now, flight search and booking consumers depend only on the functionality they need.</p><pre>public interface IFlightSearchService<br>{<br>    IEnumerable&lt;Flight&gt; Search(string origin, string destination, DateTime date);<br>}<br><br>public interface IBookingService<br>{<br>    Ticket Book(Guid flightId, string passengerName);<br>}</pre><h4>* (D)ependency Inversion Principle (DIP)</h4><blockquote><em>High-level modules should not depend on low-level modules. Both should depend on abstractions.</em></blockquote><p>Depend on interfaces, not concrete implementations.</p><h4>Example: Payment Abstraction</h4><p>You can switch payment providers without changing the business logic.</p><pre>public interface IPaymentGateway<br>{<br>    void Pay(string creditCard, decimal amount);<br>}<br><br>public class CreditCardPaymentGateway : IPaymentGateway<br>{<br>    public void Pay(string creditCard, decimal amount)<br>    {<br>        // bank integration here<br>    }<br>}<br><br>public class PaymentService : IPaymentService<br>{<br>    private readonly IPaymentGateway _gateway;<br><br>    public PaymentService(IPaymentGateway gateway)<br>    {<br>        _gateway = gateway;<br>    }<br><br>    public void ProcessPayment(string creditCard)<br>    {<br>        _gateway.Pay(creditCard, 1234.50); // total price<br>    }<br>}</pre><p>By applying <strong>SOLID principles</strong>, we create a flexible, decoupled, and maintainable codebase.</p><h3><strong>Summary</strong></h3><p>These principles aren’t just theory, they’re <strong>practical tools</strong> that will improve your development workflow and team collaboration. Whether you’re building booking systems, e-commerce platforms, or enterprise services, <strong>SOLID</strong> will keep your architecture sane.</p><p><strong>Principle =&gt; Applied In</strong></p><p>SRP =&gt; FlightSearchService and TicketPurchaseService separation</p><p>OCP =&gt; New Discount Policies</p><p>LSP =&gt; Flight types (domestic/international)</p><p>ISP =&gt; Separate interfaces for search and booking</p><p>DIP =&gt; IPaymentGateway abstraction</p><p>❋ <em>I hope this article was useful to you.</em></p><p>❋ <em>Thank you for reading and for your support.</em></p><p>❋ <em>Mücahid Uslu , Software Architect</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e811837333d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Domain-Driven Design in .NET: A Practical Guide with Hotel Booking Example]]></title>
            <link>https://mcuslu.medium.com/domain-driven-design-in-net-a-practical-guide-with-hotel-booking-example-04476a52442f?source=rss-45e9ed53665d------2</link>
            <guid isPermaLink="false">https://medium.com/p/04476a52442f</guid>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Mucahid Uslu]]></dc:creator>
            <pubDate>Sun, 01 Jun 2025 05:58:14 GMT</pubDate>
            <atom:updated>2025-06-01T13:23:45.107Z</atom:updated>
            <content:encoded><![CDATA[<h3>Domain-Driven Design in .NET: A Practical Guide with Hotel Booking Example</h3><p>Learn how to apply Domain-Driven Design (DDD) in .NET with real-world hotel booking examples. Discover key concepts like entities, value objects, aggregates, repositories, and services, and structure your application for better testability and scalability.</p><p><strong>Domain-Driven Design (DDD)</strong> is a powerful architectural approach to building maintainable, testable, and business-aligned applications, especially when working with complex domains.</p><p>In this article, we’ll walk through the core DDD concepts and show how to implement them in a real-world hotel booking context using .NET.</p><h4>What Is Domain-Driven Design?</h4><p>DDD approach, introduced by Eric Evans (2004), emphasizes aligning software models closely with business concepts. It helps teams:</p><ul><li>Focus on core business logic</li><li>Create rich domain models</li><li>Separate infrastructure concerns</li><li>Speak a <strong>Ubiquitous Language</strong> shared by both developers and domain experts</li></ul><h4>Suggested Architecture</h4><p>Here’s how to organize our solution:</p><pre>/Domain<br>   ├── Entities<br>   ├── ValueObjects<br>   ├── Interfaces<br>   └── DomainServices<br><br>/Application<br>   └── UseCases / AppServices<br><br>/Infrastructure<br>   ├── Repositories<br>   └── ExternalServices<br><br>/WebApi<br>   └── Controllers</pre><h4>Ubiquitous Language in Action</h4><p>With DDD, both developers and business experts use the same terms:<br> “Hotel”, “Availability”, “Booking”, “Check-in” , these are reflected directly in code.</p><p>This makes your code not just technical, but <strong>communicative</strong> and <strong>understandable</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wkKgRCrNV6VDx8ke6fA2xA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@elishavision?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Elizeu Dias</a> on <a href="https://unsplash.com/photos/coconut-tree-near-shore-within-mountain-range-RN6ts8IZ4_0?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h4>Core DDD Building Blocks</h4><p>Let’s explore the key components of DDD using a <strong>hotel booking</strong> scenario.</p><h4>1. Entity</h4><p>An entity has a unique identity and changes over time.</p><p>Hotel</p><pre>public class Hotel<br>{<br>    public Guid Id { get; }<br>    public string Name { get; }<br>    public Address Address { get; }<br><br>    private readonly List&lt;Booking&gt; _bookings = new();<br><br>    public Hotel(Guid id, string name, Address address)<br>    {<br>        Id = id;<br>        Name = name;<br>        Address = address;<br>    }<br><br>    public bool IsAvailable(DateTime checkIn, DateTime checkOut)<br>    {<br>        return !_bookings.Any(b =&gt; (checkIn &lt; b.CheckOut) &amp;&amp; (checkOut &gt; b.CheckIn));<br>    }<br><br>    public Guid Book(DateTime checkIn, DateTime checkOut)<br>    {<br>        if (!IsAvailable(checkIn, checkOut))<br>            throw new InvalidOperationException(&quot;Hotel is not available for the selected dates.&quot;);<br><br>        var booking = new Booking(this.Id, checkIn, checkOut);<br>        _bookings.Add(booking);<br>        return booking.Id;<br>    }<br><br>    public BookingStatus GetBookingStatus(Guid bookingId)<br>    {<br>        var booking = _bookings.FirstOrDefault(b =&gt; b.Id == bookingId);<br>        if (booking == null)<br>            return BookingStatus.NotFound;<br><br>        return booking.Status;<br>    }<br>}</pre><p>Booking</p><pre>public class Booking<br>{<br>    public Guid Id { get; }<br>    public Guid HotelId { get; set;}<br>    public DateTime CheckIn { get; }<br>    public DateTime CheckOut { get; }<br>    public BookingStatus Status { get; private set; }<br><br>    public Booking(Guid hotelId, DateTime checkIn, DateTime checkOut)<br>    {<br>        if (checkIn &gt;= checkOut)<br>            throw new ArgumentException(&quot;Check-out must be after check-in.&quot;);<br><br>        Id = Guid.NewGuid();<br>        HotelId = hotelId;<br>        CheckIn = checkIn;<br>        CheckOut = checkOut;<br>        Status = BookingStatus.Confirmed;<br>    }<br>}</pre><pre>public enum BookingStatus<br>{<br>    Confirmed,<br>    Cancelled,<br>    Completed,<br>    NotFound<br>}</pre><h4>2. Value Object</h4><p>A value object has no identity and is compared by its properties.</p><p>HotelLocation</p><pre>public class HotelLocation<br>{<br>    public string City { get; }<br>    public string Country { get; }<br>    public string Region { get; }<br>    public double Latitude { get; }<br>    public double Longitude { get; }<br><br>    public HotelLocation(string city, string country, string region, double latitude, double longitude)<br>    {<br>        City = city;<br>        Country = country;<br>        Region = region;<br>        Latitude = latitude;<br>        Longitude = longitude;<br>    }<br><br>    public override bool Equals(object? obj) =&gt;<br>        obj is HotelLocation other &amp;&amp;<br>        City == other.City &amp;&amp;<br>        Country == other.Country &amp;&amp;<br>        Region == other.Region &amp;&amp;<br>        Latitude == other.Latitude &amp;&amp;<br>        Longitude == other.Longitude;<br><br>    public override int GetHashCode() =&gt;<br>        HashCode.Combine(City, Country, Region, Latitude, Longitude);<br>}</pre><h4>3. Aggregate Root</h4><p>Aggregates group related entities and ensure consistency boundaries. Access and modify data only through the aggregate root.</p><p>HotelSearch</p><pre>public class HotelSearch<br>{<br>    private readonly List&lt;Hotel&gt; _hotels = new();<br><br>    public IReadOnlyCollection&lt;Hotel&gt; Results =&gt; _hotels;<br><br>    public void AddHotel(Hotel hotel)<br>    {<br>        if (_hotels.Any(h =&gt; h.Id == hotel.Id)) return;<br>        _hotels.Add(hotel);<br>    }<br><br>    public Hotel? FindAvailableHotel(Guid hotelId, DateTime checkIn, DateTime checkOut)<br>    {<br>        var hotel = _hotels.FirstOrDefault(h =&gt; h.Id == hotelId); // .. search logic<br>        return hotel?.IsAvailable(checkIn, checkOut) == true ? hotel : null;<br>    }<br>}</pre><h4>4. Repository Interface</h4><p>Repositories abstract data access and operate only on aggregate roots.</p><pre>public interface IHotelRepository<br>{<br>    Hotel? GetById(Guid id);<br>    void Save(Hotel hotel);<br>}</pre><h4>5. Domain Service</h4><p>Use domain services when logic spans across multiple entities and doesn’t naturally fit within one.</p><p>HotelBookingService</p><pre>public class HotelBookingService<br>{<br>    private readonly IHotelRepository _repository;<br><br>    public HotelBookingService(IHotelRepository repository)<br>    {<br>        _repository = repository;<br>    }<br><br>    public Guid BookHotel(Guid hotelId, DateTime checkIn, DateTime checkOut)<br>    {<br>        var hotel = _repository.GetById(hotelId);<br>        if (hotel == null)<br>            throw new InvalidOperationException(&quot;Hotel not found.&quot;);<br><br>        var bookingId = hotel.Book(checkIn, checkOut);<br>        _repository.Save(hotel);<br><br>        return bookingId;<br>    }<br><br>    public BookingStatus GetBookingStatus(Guid hotelId, Guid bookingId)<br>    {<br>        var hotel = _repository.GetById(hotelId);<br>        return hotel?.GetBookingStatus(bookingId) ?? BookingStatus.NotFound;<br>    }<br>}</pre><h4>6. Application Service</h4><p>Coordinates domain operations, serving as an entry point for external interfaces (like APIs).</p><p>HotelAppService</p><pre>public class HotelAppService<br>{<br>    private readonly HotelBookingService _bookingService;<br>    private readonly HotelSearch _hotelSearch;<br><br>    public HotelAppService(HotelBookingService bookingService, HotelSearch hotelSearch)<br>    {<br>        _bookingService = bookingService;<br>        _hotelSearch = hotelSearch;<br>    }<br><br>    public Guid MakeBooking(Guid hotelId, DateTime checkIn, DateTime checkOut)<br>    {<br>        return _bookingService.BookHotel(hotelId, checkIn, checkOut);<br>    }<br><br>    public BookingStatus QueryBookingStatus(Guid hotelId, Guid bookingId)<br>    {<br>        return _bookingService.GetBookingStatus(hotelId, bookingId);<br>    }<br><br>    public IReadOnlyCollection&lt;Hotel&gt; SearchAvailability(DateTime checkIn, DateTime checkOut)<br>    {<br>        return _hotelSearch<br>            .Results<br>            .Where(h =&gt; h.IsAvailable(checkIn, checkOut))<br>            .ToList();<br>    }<br>}</pre><h4>Unit Test Example</h4><p>With proper boundaries and clear responsibilities, testing becomes painless.</p><pre>[Fact]<br>public void Hotel_Should_Return_Correct_Booking_Status()<br>{<br>    var location = new HotelLocation(&quot;Antalya&quot;, &quot;Turkiye&quot;, &quot;Belek&quot;, 37.6050, 39.9633);<br>    var hotel = new Hotel(Guid.NewGuid(), &quot;SandBeachX Resort&quot;, location);<br><br>    var bookingId = hotel.Book(DateTime.Today.AddDays(1), DateTime.Today.AddDays(3));<br><br>    var status = hotel.GetBookingStatus(bookingId);<br><br>    Assert.Equal(BookingStatus.Confirmed, status);<br>}</pre><p>We’ve modeled a hotel booking domain using Domain-Driven Design principles in .NET.</p><p>Key takeaways:</p><ul><li>Use <strong>Value Objects</strong> (like HotelLocation) for rich, immutable data.</li><li>Keep <strong>Entities</strong> like Hotel and Booking focused on business rules.</li><li>Delegate workflows like availability and booking to <strong>Application Services</strong>.</li><li>Use <strong>Domain Services</strong> for coordinating behavior that spans multiple entities.</li></ul><p>This layered approach helps build systems that are expressive, testable, and easy to evolve.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04476a52442f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Code in .NET: Writing Maintainable and Testable C# Applications]]></title>
            <link>https://mcuslu.medium.com/clean-code-in-net-writing-maintainable-and-testable-c-applications-500a1c16fdee?source=rss-45e9ed53665d------2</link>
            <guid isPermaLink="false">https://medium.com/p/500a1c16fdee</guid>
            <category><![CDATA[dot-net-development]]></category>
            <category><![CDATA[code-quality-standards]]></category>
            <category><![CDATA[clean-code-principle]]></category>
            <category><![CDATA[programming-tips]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Mucahid Uslu]]></dc:creator>
            <pubDate>Sat, 31 May 2025 11:42:09 GMT</pubDate>
            <atom:updated>2025-06-01T13:26:21.453Z</atom:updated>
            <content:encoded><![CDATA[<h3>Clean Code in .NET: Writing Maintainable and Testable C# Applications</h3><blockquote><em>“Clean code always looks like it was written by someone who cares.”<br> — </em>Robert C. Martin (Uncle Bob)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y85SMFWG4C8vmPUFvtfYFQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@rkdamedia?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Tim Chow</a> on <a href="https://unsplash.com/photos/green-fern-plant-inside-clear-glass-vase-9IcKPSQ9G5Q?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>In the world of software development, writing code that works is just the beginning. <strong>Clean code</strong> is about writing code that is <strong>easy to read, understand, maintain, and extend</strong>. It minimizes friction between team members, simplifies debugging, and reduces technical debt over time.</p><p>In this article, we’ll break down the core ideas behind clean code and reinforce them with practical examples using C#/.NET Core and a sample HotelSearchService.</p><h4>Why Clean Code Matters</h4><ul><li>Easier to understand =&gt; faster onboarding.</li><li>️Easier to change =&gt; faster delivery.</li><li>Easier to debug =&gt; fewer bugs.</li><li>Easier to test =&gt; higher quality.</li></ul><p>Bad code works, until it doesn’t. Clean code is an investment in <strong>sustainability</strong>.</p><h4>1. Meaningful Names</h4><p># Good names describe <em>what</em> the code does, not how.</p><pre>// ! Bad<br>var h = service.Search(&quot;2024-10-01&quot;, &quot;2024-10-05&quot;, 2);<br><br>// ✔ Good<br>var searchResult = hotelSearchService.Search(checkIn, checkOut, guestCount);</pre><p><strong>Tips:</strong></p><ul><li>Use domain terminology.</li><li>Avoid meaningless prefixes (temp, data, value, etc.).</li><li>Avoid abbreviations.</li></ul><h4>2. Functions Should Do One Thing</h4><p>This aligns with the <strong>Single Responsibility Principle (SRP)</strong>. A function should do <em>one thing</em>, and do it well.</p><pre>// ! Bad: does too much<br>public void SearchAndNotify(string city)<br>{<br>    var results = Search(city);<br>    SaveToCache(results);<br>    SendNotification(results);<br>}<br><br>// ✔ Good: clear separation<br>public List&lt;Hotel&gt; SearchHotels(string city)<br>{<br>    return hotelSearchEngine.Search(city);<br>}<br><br>public void CacheResults(List&lt;Hotel&gt; results)<br>{<br>    cacheService.Save(results);<br>}<br><br>public void Notify(List&lt;Hotel&gt; results)<br>{<br>    notifier.Send(results);<br>}</pre><h4>3. Avoid Comments That Replace Clean Code</h4><p>Comments are often used to compensate for unclear code. If your code needs a comment to explain what it does, consider <strong>renaming</strong>, <strong>refactoring</strong>, or <strong>extracting methods</strong>.</p><pre>// ! &quot;magic string&quot; and unclear logic<br>// if departure is Antalya, apply special discount<br>if (request.Departure == &quot;AYT&quot;) { ApplyTransferDiscount(); }<br><br>// ✔ Expressive<br>const string SpecialDeparture = &quot;AYT&quot;;<br>if (request.Departure == SpecialDeparture) { ApplyTransferDiscount(); }</pre><h4>4. Write Testable Code</h4><p>Clean code is naturally testable. Avoid static classes and tightly coupled dependencies.</p><pre>// ! Hard to test<br>public class HotelSearchService<br>{<br>    public List&lt;Hotel&gt; Search(string city) =&gt; ExternalApi.SearchHotels(city);<br>}<br><br>// ✔ Use abstraction<br>public class HotelSearchService<br>{<br>    private readonly IHotelSearchProvider _searchProvider;<br><br>    public HotelSearchService(IHotelSearchProvider searchProvider)<br>    {<br>        _searchProvider = searchProvider;<br>    }<br><br>    public List&lt;Hotel&gt; Search(string city) =&gt; _searchProvider.Search(city);<br>}</pre><h4>5. DRY — Don’t Repeat Yourself</h4><p>Duplicated code leads to inconsistent behavior and more maintenance cost.</p><pre>// ! Repeated logic<br>if (city == &quot;Istanbul&quot;) { /* apply .. */ }<br>// ...<br>if (city == &quot;Istanbul&quot;) { /* apply .. */ }<br><br>// ✔ Extract method<br>bool IsDomesticCity(string city) =&gt; city == &quot;Istanbul&quot;;</pre><h4>Other Clean Code Practices</h4><ul><li>! <strong>Avoid long parameter lists</strong> =&gt; use DTOs or request models.</li><li>!<strong> Avoid deep nestin</strong>g =&gt; return early.</li><li><strong>✓</strong> <strong>Refactor often =&gt; </strong>it’s a discipline, not a one-time event.</li><li><strong>✓</strong> <strong>Use consistent naming, spacing, and formatting</strong> =&gt; consider tools like EditorConfig, StyleCop, Resharper.</li></ul><h4>Tools That Help in .NET</h4><ul><li><strong>Rider / Visual Studio</strong>: powerful refactoring and suggestions.</li><li><strong>.editorconfig</strong>: enforce consistent code style.</li><li><strong>FxCopAnalyzers / Roslyn Analyzers</strong>: automatic code quality checks.</li><li><strong>SonarQube</strong>: static code analysis and tech debt tracking.</li><li><strong>NDepend</strong>: metrics and code quality trends.</li></ul><h4>Recommended Resources</h4><ul><li><em>Clean Code</em> by Robert C. Martin</li><li><em>Refactoring</em> by Martin Fowler</li><li><em>The Art of Readable Code</em> by Dustin Boswell</li></ul><p>Clean code is not about perfection, it’s about <strong>clarity</strong>. You don’t write clean code for the machine, you write it for the next developer, which is often… <em>you</em>.</p><p>Investing in clean code pays back tenfold in agility, teamwork, and peace of mind.</p><p>Understanding and avoiding technical debt starts with clean code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=500a1c16fdee" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>