<?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 Hadiuzzaman on Medium]]></title>
        <description><![CDATA[Stories by Hadiuzzaman on Medium]]></description>
        <link>https://medium.com/@md-hadi?source=rss-3e2e8c53b23b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oDuHSxfkG-xj9cQoI-dwPQ.png</url>
            <title>Stories by Hadiuzzaman on Medium</title>
            <link>https://medium.com/@md-hadi?source=rss-3e2e8c53b23b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 18:15:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@md-hadi/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[IPTV vs OTT vs Cable vs Satellite: Understanding Modern TV Technology]]></title>
            <link>https://md-hadi.medium.com/iptv-vs-ott-vs-cable-vs-satellite-understanding-modern-tv-technology-26bb0a1c314e?source=rss-3e2e8c53b23b------2</link>
            <guid isPermaLink="false">https://medium.com/p/26bb0a1c314e</guid>
            <category><![CDATA[iptv]]></category>
            <category><![CDATA[m3u8]]></category>
            <category><![CDATA[xtiva]]></category>
            <category><![CDATA[iptv-player]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Hadiuzzaman]]></dc:creator>
            <pubDate>Sat, 03 Oct 2026 11:49:54 GMT</pubDate>
            <atom:updated>2026-10-03T11:49:54.241Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qq-iODBIsK8--DeplLtIEQ.png" /></figure><p>Television has changed a lot.</p><p>For decades, watching TV usually meant connecting an antenna, cable line, or satellite dish.</p><p>Today, a television can stream live channels, movies, series, and other content through an internet connection.</p><p>That shift has introduced terms like <strong>IPTV, OTT, streaming, cable TV, and satellite TV</strong>.</p><p>They’re often used interchangeably, but they aren’t exactly the same.</p><p>So, what actually separates them?</p><p>And where does IPTV fit into modern television?</p><p>Let’s break it down.</p><h3>What Is IPTV?</h3><p><strong>IPTV stands for Internet Protocol Television.</strong></p><p>Simply put, IPTV delivers television content using <strong>IP-based networks</strong>.</p><p>Instead of relying primarily on traditional broadcast signals, cable frequencies, or satellite transmission, video content is delivered as data over an IP network.</p><p>A simplified IPTV workflow looks like this:</p><p><strong>Content Source → Encoding → IPTV Infrastructure → IP Network → IPTV Player → Screen</strong></p><p>Depending on the service architecture, IPTV can support:</p><ul><li>Live TV</li><li>Video on demand</li><li>Catch-up TV</li><li>Electronic program guides (EPG)</li><li>Subtitles</li><li>Multiple audio tracks</li><li>Interactive features</li></ul><p>But there’s an important distinction:</p><blockquote><strong><em>IPTV isn’t simply “Netflix over the internet.”</em></strong></blockquote><p>IPTV can operate through managed networks and service-provider infrastructure, while OTT services generally deliver content over the public internet.</p><p>There is some overlap between the two, and modern video services don’t always fit neatly into a single category.</p><h3>How Does IPTV Work?</h3><p>At a high level, an IPTV system consists of several layers.</p><h3>1. Content</h3><p>Television channels, movies, series, and other video content come from content providers.</p><h3>2. Encoding</h3><p>The original video is encoded into formats suitable for digital distribution.</p><h3>3. Streaming Infrastructure</h3><p>The encoded content is made available through streaming servers and distribution infrastructure.</p><h3>4. Network Delivery</h3><p>The video data travels through an IP network to the viewer’s device.</p><h3>5. IPTV Player</h3><p>The player receives the stream, handles playback, and provides the interface through which the viewer interacts with the content.</p><p>This last part is easy to overlook.</p><p>The same IPTV service can feel completely different depending on the quality of the player application.</p><h3>IPTV vs Cable TV</h3><p>Traditional cable television delivers TV through a physical cable network operated by a service provider.</p><p>IPTV uses <strong>IP networking</strong> as its primary delivery mechanism.</p><h3>Cable TV</h3><p>Cable TV traditionally depends on a physical cable infrastructure connecting the service provider to the viewer.</p><p>The provider controls much of the delivery infrastructure, equipment, and service experience.</p><h3>IPTV</h3><p>IPTV uses IP-based networking to deliver television content.</p><p>This makes software and connected devices a much bigger part of the overall experience.</p><p>IPTV can also make it easier to build experiences around:</p><ul><li>Multiple devices</li><li>Interactive guides</li><li>On-demand content</li><li>Catch-up functionality</li><li>Personalized interfaces</li></ul><p>However, the distinction isn’t always purely technical.</p><p>Modern cable networks can also use IP technologies, and many traditional TV providers now combine television, internet, and streaming technologies.</p><p>The bigger difference is the <strong>overall service architecture and delivery model</strong>.</p><h3>IPTV vs Satellite TV</h3><p>Satellite TV uses satellites to transmit television signals to receiving equipment, typically through a satellite dish.</p><p>IPTV delivers content through IP networks.</p><h3>Satellite TV</h3><p>Traditional satellite television typically requires:</p><ul><li>A satellite dish</li><li>A receiver</li><li>Satellite signal coverage</li></ul><p>One of its biggest strengths is geographic coverage. Satellite technology can deliver television to areas where terrestrial infrastructure may be difficult to deploy.</p><h3>IPTV</h3><p>IPTV generally relies on an IP network and compatible connected device.</p><p>This enables software-driven experiences such as:</p><ul><li>Interactive program guides</li><li>Catch-up TV</li><li>Multiple playback options</li><li>Multi-device support</li><li>Custom interfaces</li></ul><p>The trade-off is that IPTV depends on network connectivity and the quality of the underlying network.</p><h3>IPTV vs OTT Streaming</h3><p>This is probably the most confusing comparison.</p><p><strong>OTT</strong> stands for <strong>Over-The-Top</strong>.</p><p>OTT services deliver video over internet infrastructure without relying on traditional television distribution systems.</p><p>Popular streaming platforms are examples of OTT services.</p><p>Both IPTV and OTT use IP technology, but their architectures and business models can be different.</p><h3>IPTV</h3><p>IPTV generally refers to television services delivered through IP-based infrastructure, often with characteristics associated with managed service-provider networks.</p><h3>OTT</h3><p>OTT generally refers to video services delivered over the general internet directly to applications, websites, smart TVs, phones, and other connected devices.</p><p>But there’s significant overlap.</p><p>Modern video platforms can use combinations of:</p><ul><li>Cloud infrastructure</li><li>Content delivery networks</li><li>Adaptive streaming</li><li>IP networks</li><li>Managed networks</li><li>Internet delivery</li></ul><p>So the boundary between IPTV and OTT isn’t always perfectly clear.</p><p>The terms often describe <strong>different service and distribution approaches rather than completely separate technologies</strong>.</p><h3>IPTV vs Traditional Broadcast TV</h3><p>Traditional broadcast television sends the same television signal to many receivers through radio frequencies.</p><p>The viewer needs an appropriate antenna and receiving equipment.</p><p>IPTV takes a different approach by treating television content as data that can travel through IP networks.</p><p>That makes <strong>software</strong> a much bigger part of the television experience.</p><p>Features such as:</p><ul><li>Search</li><li>Electronic program guides</li><li>Catch-up TV</li><li>Subtitles</li><li>Multiple audio tracks</li><li>Picture-in-picture</li><li>Continue watching</li><li>Personalized interfaces</li></ul><p>can all become part of the application experience.</p><p>Television starts looking less like a traditional receiver and more like a <strong>software platform</strong>.</p><h3>The IPTV Player Is More Important Than It Looks</h3><p>When people talk about IPTV, they often focus on the server, stream URL, or content provider.</p><p>But there’s another important component:</p><p><strong>the player.</strong></p><p>The player sits between the IPTV infrastructure and the viewer.</p><p>It needs to handle much more than simply pressing play.</p><p>For example:</p><ul><li>Stream playback</li><li>Channel switching</li><li>Buffering</li><li>Audio tracks</li><li>Subtitles</li><li>Playlist management</li><li>Program information</li><li>Remote-control navigation</li><li>Different screen sizes</li><li>Playback errors</li><li>Network changes</li></ul><p>And things become even more interesting when the same application needs to work across phones, tablets, Android TV, and large-screen devices.</p><h3>Mobile TV Isn’t the Same as TV TV</h3><p>A mobile interface can rely on touch gestures, scrolling, and compact layouts.</p><p>A television interface has a completely different interaction model.</p><p>Users may be sitting several meters away from the screen and navigating with a remote control or D-pad.</p><p>That changes how an application should be designed.</p><p>A good TV interface needs:</p><p><strong>Large targets → Focus-based navigation → Clear hierarchy → Minimal interaction steps</strong></p><p>What works beautifully on a phone can feel frustrating on a television.</p><p>That’s one of the areas where a well-designed IPTV player can make a significant difference.</p><h3>Why IPTV Players Matter More as Content Grows</h3><p>Modern IPTV services can provide access to hundreds or even thousands of channels, along with large libraries of movies and series.</p><p>But having more content creates another problem:</p><blockquote><strong><em>How do you navigate all of it?</em></strong></blockquote><p>A good player needs to make large amounts of content feel manageable.</p><p>Ideally, the experience should be simple:</p><p><strong>1. Open the app.</strong></p><p><strong>2. Find what you want to watch.</strong></p><p><strong>3. Start playback.</strong></p><p><strong>4. Control the experience.</strong></p><p><strong>5. Come back later and continue watching.</strong></p><p>The technology underneath can be extremely complicated.</p><p><strong>The user experience shouldn’t be.</strong></p><h3>Building Xtiva</h3><p>This is one of the reasons I built <strong>Xtiva</strong>.</p><p>Xtiva is a modern IPTV player designed around a simple idea:</p><blockquote><strong><em>IPTV shouldn’t feel unnecessarily complicated.</em></strong></blockquote><p>It supports IPTV playlists and focuses on providing a clean viewing experience across supported devices.</p><p>Some of the features include:</p><ul><li>Live TV</li><li>Movies and series</li><li>Xtream Codes support</li><li>M3U playlist support</li><li>Catch-up TV where supported by the provider</li><li>Subtitle support</li><li>Multiple audio tracks</li><li>Picture-in-picture on supported devices</li><li>Continue watching</li><li>TV-friendly navigation</li><li>Multiple themes and customization options</li><li>Performance improvements</li></ul><p>The goal isn’t to become another content provider.</p><p>Instead, Xtiva acts as the <strong>player layer between your IPTV service and your screen</strong>.</p><p>Your IPTV provider supplies the content.</p><p><strong>Xtiva provides the interface and playback experience.</strong></p><h3>IPTV Is Still Evolving</h3><p>The evolution of television isn’t simply about replacing cable with the internet.</p><p>It’s a broader transition from hardware-driven television experiences toward <strong>software-driven experiences</strong>.</p><p>Broadcast, cable, satellite, IPTV, and OTT each have different architectures and use cases.</p><p>But IP-based technologies make it possible to build television experiences that are much more flexible than traditional channel-based interfaces.</p><p>And as smart TVs become more capable, the IPTV player becomes an increasingly important part of the experience.</p><p>The future of television isn’t only about <strong>how video is delivered</strong>.</p><p>It’s also about <strong>how people discover, navigate, and experience that video</strong>.</p><p>That’s the problem we’re exploring with Xtiva.</p><blockquote><strong><em>Simple interface. Flexible IPTV playback. Built for modern screens.</em></strong></blockquote><h3>Try Xtiva</h3><p>If you already use an IPTV service and are looking for a modern player, you can try Xtiva on Google Play:</p><p><a href="https://play.google.com/store/apps/details?id=com.metawave.xtreamiptv&amp;utm_source=medium&amp;utm_medium=blog&amp;utm_campaign=iptv_comparison"><strong>Get Xtiva on Google Play</strong></a></p><p>Your IPTV provider supplies the content and subscription.</p><p><strong>Xtiva is the player used to access and watch your own IPTV content.</strong></p><p>#IPTV #XtreamCodes #M3U #IptvPlayer #Xtiva #Kotlin #Compose</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26bb0a1c314e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Tap-to-Connect to WireGuard Handshake: Building a Production VPN Flow on Android]]></title>
            <link>https://md-hadi.medium.com/from-tap-to-connect-to-wireguard-handshake-building-a-production-vpn-flow-on-android-ee1c5d6dda01?source=rss-3e2e8c53b23b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee1c5d6dda01</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[wireguard]]></category>
            <category><![CDATA[vpn]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Hadiuzzaman]]></dc:creator>
            <pubDate>Thu, 27 Aug 2026 14:31:01 GMT</pubDate>
            <atom:updated>2026-08-27T14:31:01.099Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zmk_1rm1XkL76koOeVfhPg.png" /></figure><p>Most VPN tutorials stop at “call VpnService and you&#39;re done.&quot; Real VPN apps are nothing like that. Between the moment a user taps the connect button and the moment the first encrypted packet flows, there is a permission dance, a foreground service, a config fetch from your backend, a userspace tunnel, a handshake watchdog, and a state machine that has to survive process death, system revokes, and Android&#39;s increasingly hostile background-execution rules.</p><p>This post walks through the complete connect/disconnect sequence of AnyVPN, a production WireGuard-based Android VPN built with Jetpack Compose and clean architecture. Every snippet is real code from the app, and the complete interactive connection-flow diagram is available in the docs: <a href="https://hadiuzzaman524.github.io/vpn-android/index.html">VPN Connection Flow — Sequence Diagram</a>. The flow follows this sequence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pA5YkwUr-69WdR_8jEtvSg.png" /></figure><blockquote>Six actors, four phases:</blockquote><ol><li>User taps to connect — UI → ViewModel, plus the VPN consent dialog if needed</li><li>Start the foreground service — ViewModel → Controller → Service</li><li>Fetch config &amp; open tunnel — Service fetches a WireGuard config from the backend</li><li>Build the network tunnel — Manager brings the tunnel up and confirms a real handshake</li></ol><p>Then everything flows <em>back up</em> reactively: CONNECTED state, live throughput, and the session timer stream to the notification and the Compose UI through a single StateFlow.</p><blockquote>Explore the animated flow here — <a href="https://hadiuzzaman524.github.io/vpn-android/index.html">VPN Connection Flow — Sequence Diagram</a></blockquote><h3>The architecture in one paragraph</h3><p>The design rule that makes everything else fall into place: exactly one component owns the tunnel. VpnConnectionManager is an app-singleton that owns the WireGuard backend and publishes two StateFlows — state (connection status) and traffic (live throughput). Everyone else either <em>drives</em> it (the foreground service) or <em>observes</em> it (the Compose UI, the notification). The ViewModel never touches the tunnel; the service never touches the UI; the UI never touches Android services. Messages travel down the chain as commands and travel back up as state emissions.</p><pre>@Single<br>class VpnConnectionManager(<br>    private val context: Context,<br>    private val stateStore: VpnStateStore,<br>) {<br>    private val backend: Backend by lazy { GoBackend(context) }<br>    private val tunnel = AppTunnel(TUNNEL_NAME)<br>    private val _state = MutableStateFlow(VpnConnectionState())<br>    val state: StateFlow&lt;VpnConnectionState&gt; = _state.asStateFlow()<br>    private val _traffic = MutableStateFlow(VpnTraffic())<br>    val traffic: StateFlow&lt;VpnTraffic&gt; = _traffic.asStateFlow()<br>    ...<br>}</pre><p>The state model is deliberately small. WireGuard’s GoBackend only knows UP/DOWN, so the app layers its own semantics on top:</p><pre>data class VpnConnectionState(<br>    val status: ConnectionStatus = ConnectionStatus.DISCONNECTED, // CONNECTING / CONNECTED / DISCONNECTED<br>    val error: VpnError? = null,          // one-shot, consumed by the ViewModel<br>    val connectedSinceEpochMs: Long? = null, // set on real handshake; drives the session timer<br>    val serverName: String? = null,<br>    val serverIp: String? = null,<br>    val serverCountryName: String? = null,<br>    val serverCountryCode: String? = null,<br>)</pre><p>Note what’s <em>not</em> there: no FAILED status. Failures are carried in error while status falls back to DISCONNECTED — the UI reverts the connect button and shows the error as a one-shot snackbar rather than getting stuck in a distinct error state.</p><h3>Step 1 — User taps to connect (and the permission alt-path)</h3><p>The tap calls VPNViewModel.connect(). Before anything can happen, Android requires user consent for any app that wants to route the device&#39;s traffic. VpnService.prepare() is the check: it returns null if consent was already granted, or an Intent that must be launched <em>from an Activity</em> to show the system consent dialog.</p><p>The ViewModel can’t launch activities, so this is modeled as a one-shot event:</p><pre>/** One-shot effects the Home screen must run against an Activity/UI. */<br>sealed interface HomeEvent {<br>    /** The VPN consent dialog must be launched from the Activity via this intent. */<br>    data class RequestVpnPermission(val intent: Intent) : HomeEvent<br>    data class ShowError(@StringRes val messageRes: Int) : HomeEvent<br>}<br>/** Triggered by tap-to-connect. Requires VPN consent (once), then starts the service. */<br>fun connect() {<br>    val consentIntent = vpnController.prepare()<br>    if (consentIntent != null) {<br>        _events.tryEmit(HomeEvent.RequestVpnPermission(consentIntent))<br>    } else {<br>        vpnManager.markConnecting()<br>        vpnController.connect()<br>    }<br>}<br>/** Called by the screen after the system VPN-consent dialog resolves. */<br>fun onPermissionResult(granted: Boolean) {<br>    if (granted) {<br>        vpnManager.markConnecting()<br>        vpnController.connect()<br>    } else {<br>        _events.tryEmit(HomeEvent.ShowError(VpnError.NOT_AUTHORIZED.messageRes))<br>    }<br>}</pre><p>On the Compose side, the consent dialog is wired with an ActivityResult launcher — the sequence diagram&#39;s [ VPN permission not yet granted ] alt-block:</p><pre>val consentLauncher = rememberLauncherForActivityResult(<br>    ActivityResultContracts.StartActivityForResult()<br>) { result -&gt;<br>    viewModel.onPermissionResult(result.resultCode == Activity.RESULT_OK)<br>}<br>LaunchedEffect(Unit) {<br>    viewModel.events.collect { event -&gt;<br>        when (event) {<br>            is HomeEvent.RequestVpnPermission -&gt; consentLauncher.launch(event.intent)<br>            is HomeEvent.ShowError -&gt;<br>                snackbarHostState.showSnackbar(context.getString(event.messageRes))<br>        }<br>    }<br>}</pre><p>Why markConnecting() before anything else? The config fetch takes a network round-trip. Without an optimistic CONNECTING emission, the button would sit idle for a second or two after the user&#39;s tap — the classic &quot;did my tap register?&quot; moment. Setting state first makes the UI respond instantly while the real work happens behind it:</p><pre>/** Optimistic CONNECTING state used before the config fetch resolves. */<br>fun markConnecting() {<br>    _traffic.value = VpnTraffic()<br>    _state.update {<br>        it.copy(status = ConnectionStatus.CONNECTING, error = null, connectedSinceEpochMs = null)<br>    }<br>}</pre><h3>Step 2 — Start the foreground service</h3><p>The ViewModel never touches Context or service intents. A thin bridge does:</p><pre>/**<br> * Thin Android-glue bridge between the ViewModel and VpnForegroundService, so<br> * the ViewModel never touches Context or service intents directly.<br> */<br>@Single<br>class VpnController(private val context: Context) {<br>  <br>    fun prepare(): Intent? = VpnService.prepare(context)<br>    <br>    fun connect() {<br>            ContextCompat.startForegroundService(context, VpnForegroundService.connectIntent(context))<br>        }<br>    fun disconnect() {<br>        // startForegroundService (not startService): a plain startService throws<br>        // IllegalStateException on API 26+ if the app has slipped into the background.<br>        ContextCompat.startForegroundService(context, VpnForegroundService.disconnectIntent(context))<br>    }<br>}</pre><p>That comment on disconnect() is a scar from real debugging: on API 26+ you cannot startService() from the background, and a disconnect tap from the notification arrives while the app <em>is</em> in the background.</p><p>Why a foreground service at all? Two reasons:</p><ol><li>WireGuard’s GoBackend runs the tunnel in your process (its own internal GoBackend$VpnService). If Android kills your process, the tunnel dies with it. A foreground service keeps the process alive.</li><li>The user needs a persistent, glanceable status — “connected via Netherlands, 42 Mbps down” — and a disconnect button that works without opening the app.</li></ol><p>Crucially, this service is a plain Service, not a VpnService:</p><pre>/**<br> * Foreground orchestrator that keeps the process (and therefore WireGuard&#39;s own<br> * in-process GoBackend$VpnService) alive in the background, owns the persistent<br> * status notification, and drives connect/disconnect. It is a plain Service,<br> * NOT a android.net.VpnService — the tunnel interface is owned by GoBackend.<br> */<br>class VpnForegroundService : Service() {<br><br>override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {<br>        ensureChannels()<br><br>        // Seed CONNECTING before observing so the observer never stops us on the<br>        // initial DISCONNECTED snapshot (which would abort the connect).<br>        if (intent?.action == ACTION_CONNECT) manager.markConnecting()<br>        // Must call startForeground synchronously and early to avoid an ANR/crash.<br>        startInForeground(buildStatusNotification(manager.state.value, manager.traffic.value))<br>        when (intent?.action) {<br>            ACTION_CONNECT -&gt; {<br>                startObserving()<br>                scope.launch { connectAndScheduleLimit(freshSession = true) }<br>            }<br>            ACTION_DISCONNECT -&gt; {<br>                startObserving()<br>                handleDisconnect()<br>            }<br>            // Null intent: the system restarted us (START_STICKY) after killing the<br>            // process. Reconnect if that&#39;s what the user last asked for.<br>            else -&gt; handleRestart()<br>        }<br>        return START_STICKY<br>    }<br>}</pre><p>Three production details worth stealing:</p><ul><li>startForeground() synchronously in onStartCommand. Android gives you ~5 seconds after startForegroundService() to call startForeground(), or it crashes the app. Don&#39;t put a coroutine between them.</li><li>Seed CONNECTING before startObserving(). The observer stops the service whenever it sees DISCONNECTED — which is exactly what the initial state snapshot is. Without the seed, the service would kill itself before the connect even started. Classic reactive-startup race.</li><li>FOREGROUND_SERVICE_TYPE_SPECIAL_USE on Android 14+. Since UPSIDE_DOWN_CAKE, foreground services must declare a type, and VPN orchestration falls under specialUse.</li></ul><h3>Step 3 — Fetch config &amp; open tunnel</h3><p>With the service alive and the notification showing “Connecting…”, the actual work starts. The service records the user’s <em>intent</em> (more on that later), fetches a fresh WireGuard config from the backend, and hands it to the manager:</p><pre>private suspend fun connectAndScheduleLimit(freshSession: Boolean) {<br>    if (freshSession) stateStore.clearSession()<br>    stateStore.setDesiredOn(true)<br>    // Retried: right after a tunnel teardown (e.g. a server switch) the device<br>    // network needs a moment to settle and the first request often times out.<br>    val entity = retry { getVpnConnection.execute() }<br>    if (entity == null) {<br>        stateStore.setDesiredOn(false)<br>        manager.reportError(VpnError.CONFIG_FETCH)<br>        return<br>    }<br>    manager.connect(entity)<br>    scheduleFreeSessionLimit()<br>}<br>private suspend fun &lt;T&gt; retry(attempts: Int = CONNECT_RETRIES, block: suspend () -&gt; T): T? {<br>    repeat(attempts) { attempt -&gt;<br>        runCatching { return block() }<br>        if (attempt &lt; attempts - 1) delay(CONNECT_RETRY_DELAY_MS.milliseconds)<br>    }<br>    return null<br>}</pre><p>The config fetch goes through a clean-architecture chain — use case → repository → Retrofit data source:</p><pre>@Single<br>class GetVpnConnectionUseCase(private val repository: VpnConnectionRepository) {<br>    suspend fun execute(): VpnConnectionEntity = repository.get()<br>}<br><br>@Single(binds = [VpnConnectionRepository::class])<br>class VpnConnectionRepositoryImpl(<br>    private val api: VpnApiService,<br>    private val serverSelection: ServerSelectionRepository,<br>) : VpnConnectionRepository {<br>    override suspend fun get(): VpnConnectionEntity {<br>        val request = StartSessionRequest(serverId = serverSelection.get()?.id)<br>        return api.startSession(request).data.toEntity()<br>    }<br>}<br><br>interface VpnApiService {<br>    /** serverId is optional; null lets the backend pick the best server. */<br>    @POST(&quot;api/v1/vpn/session/start&quot;)<br>    suspend fun startSession(@Body request: StartSessionRequest): ApiResponse&lt;VpnSessionDto&gt;<br>    @DELETE(&quot;api/v1/vpn/session/end&quot;)<br>        suspend fun endSession(): ApiResponse&lt;Unit&gt;<br>}<br><br>data class StartSessionRequest(val serverId: String? = null)</pre><p><em>(API names, endpoints, and request bodies here are illustrative placeholders — swap in your own backend contract.)</em></p><p>What comes back is everything the tunnel and the UI need:</p><pre>data class VpnConnectionEntity(<br>    val vpnConfig: String,        // full WireGuard config text ([Interface] + [Peer])<br>    val serverName: String,<br>    val serverIp: String,<br>    val serverCountry: ServerCountryEntity,<br>)</pre><p>Why fetch the config per-connect instead of shipping it in the app? Because the backend allocates a session: it picks a server (or honors the user’s serverId), assigns the client an address, and registers the peer. That&#39;s also why disconnect calls the session-end endpoint — the server needs to release that session. Config material is short-lived and per-session, which is exactly what you want for a WireGuard fleet.</p><h3>Step 4 — Build the network tunnel</h3><p>Now the manager takes over. This is the densest part of the flow, and the sequence diagram expands it into its own view: parse the config, handle the server-swap case, bring the interface up, then start two background jobs — a 1-second polling loop and a 15-second watchdog.</p><pre>suspend fun connect(entity: VpnConnectionEntity) = mutex.withLock {<br>    _state.update {<br>        it.copy(<br>            status = ConnectionStatus.CONNECTING,<br>            serverName = entity.serverName,<br>            serverIp = entity.serverIp,<br>            serverCountryName = entity.serverCountry.name,<br>            serverCountryCode = entity.serverCountry.code,<br>        )<br>    }<br><br>    <br>    val config = try {<br>        Config.parse(entity.vpnConfig.byteInputStream())<br>    } catch (e: Exception) {<br>        fail(VpnError.CONFIG_PARSE)<br>        return@withLock<br>    }<br>    if (isTunnelRunning()) {<br>        if (entity.vpnConfig == activeConfigText) {<br>            // Re-issued connect for the same server: just resume.<br>            markConnected()<br>            startPolling()<br>            return@withLock<br>        }<br>        // Server switch: bounce the tunnel, suppressing the intermediate DOWN so<br>        // observers (and the foreground service) don&#39;t treat it as a disconnect.<br>        swappingConfig = true<br>        try {<br>            withContext(Dispatchers.IO) { backend.setState(tunnel, Tunnel.State.DOWN, null) }<br>        } finally {<br>            swappingConfig = false<br>        }<br>    }<br>    try {<br>        withContext(Dispatchers.IO) { backend.setState(tunnel, Tunnel.State.UP, config) }<br>    } catch (e: Exception) {<br>        fail(mapBackendError(e))<br>        return@withLock<br>    }<br>    activeConfigText = entity.vpnConfig<br>    // Tunnel interface is up; poll flips CONNECTING -&gt; CONNECTED on first handshake.<br>    startPolling()<br>    startHandshakeWatchdog()<br>}</pre><p>Things to notice:</p><ul><li>A Mutex guards connect/disconnect. A user can tap connect, immediately tap disconnect, and pick a new server within a second. Serializing tunnel mutations turns that from a race into a queue.</li><li>The server-swap alt-path. Switching servers means DOWN then UP. But the manager’s own DOWN callback treats an unexpected drop as a disconnect. The swappingConfig flag marks the intermediate DOWN as <em>ours</em>, so the notification never flashes &quot;Disconnected&quot; mid-switch.</li><li>setState(UP, config) is where Android actually builds the tunnel. Under the hood, GoBackend&#39;s VpnService calls Builder.establish(), creating the TUN interface — this is the moment the key icon appears in the status bar.</li></ul><h3>CONNECTED means “handshake seen”, not “interface up”</h3><p>Here’s the subtle bug most VPN apps ship with: Tunnel.State.UP does not mean you&#39;re connected. The interface can be up while the server is unreachable — wrong port, dead server, blocked UDP. The user sees &quot;Connected&quot; and has no internet.</p><p>WireGuard is silent (no persistent control channel), but it does expose <em>statistics</em>: byte counters and the timestamp of the latest peer handshake. So the manager treats the first handshake as the true CONNECTED signal, checked by the polling job:</p><pre>/** Sample rx/tx once per second → Mbps, and confirm real connectivity via handshake. */<br>private fun startPolling() {<br>    pollJob?.cancel()<br>    pollJob = scope.launch {<br>        var lastRx = 0L; var lastTx = 0L<br>        var lastNanos = System.nanoTime()<br>        var primed = false<br>        while (isActive) {<br>            val stats = runCatching { backend.getStatistics(tunnel) }.getOrNull()<br>            if (stats != null) {<br>                val now = System.nanoTime()<br>                val seconds = ((now - lastNanos).coerceAtLeast(1)) / 1_000_000_000.0<br>                val rx = stats.totalRx(); val tx = stats.totalTx()<br>                if (primed) {<br>                    val down = (rx - lastRx).coerceAtLeast(0) * 8.0 / seconds / 1_000_000.0<br>                    val up = (tx - lastTx).coerceAtLeast(0) * 8.0 / seconds / 1_000_000.0<br>                    _traffic.value = VpnTraffic(down, up, rx, tx)<br>                }<br>                lastRx = rx; lastTx = tx; lastNanos = now; primed = true<br><br>                val latestHandshake = stats.peers()<br>                                    .maxOfOrNull { stats.peer(it)?.latestHandshakeEpochMillis() ?: 0L } ?: 0L<br>                                if (latestHandshake &gt; 0L &amp;&amp; _state.value.status != ConnectionStatus.CONNECTED) {<br>                                    markConnected()  // CONNECTING -&gt; CONNECTED on first real handshake<br>                                }<br>                            }<br>                            delay(POLL_INTERVAL_MS) // 1 second<br>                  }<br>          }<br>}</pre><p>One loop, two jobs done: throughput (delta of byte counters → Mbps, primed skips the garbage first sample) and liveness (handshake timestamp → CONNECTED).</p><h3>The watchdog: fail loudly, not silently</h3><p>If the handshake never arrives, the user must not stare at “Connecting…” forever. A watchdog gives the handshake 15 seconds, then tears everything down:</p><pre>/** If no handshake lands within the window, tear the tunnel down and report a timeout. */<br>private fun startHandshakeWatchdog() {<br>    watchdogJob?.cancel()<br>    watchdogJob = scope.launch {<br>        val connected = withTimeoutOrNull(HANDSHAKE_TIMEOUT_MS) {   // 15s<br>            state.first { it.status == ConnectionStatus.CONNECTED }<br>            true<br>        }<br>        if (connected == null &amp;&amp; _state.value.status != ConnectionStatus.CONNECTED) {<br>            mutex.withLock {<br>                if (_state.value.status != ConnectionStatus.CONNECTED) {<br>                    runCatching {<br>                        withContext(Dispatchers.IO) { backend.setState(tunnel, Tunnel.State.DOWN, null) }<br>                    }<br>                    fail(VpnError.HANDSHAKE_TIMEOUT)<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>Note the double-check of status around the lock — the handshake may land while the watchdog is waiting for the mutex. Success cancels the watchdog implicitly (the state.first { CONNECTED } completes); timeout cancels the connection explicitly.</p><h3>✓ Connected — state flows back up</h3><p>Nothing in the upward direction is a callback. Both consumers just collect the same two flows.</p><p>The service mirrors state into the notification and stops itself when the tunnel is gone:</p><pre>private fun startObserving() {<br>    if (observing) return<br>    observing = true<br>    scope.launch {<br>        combine(manager.state, manager.traffic) { s, t -&gt; s to t }.collect { (state, traffic) -&gt;<br>            if (state.status == ConnectionStatus.DISCONNECTED) {<br>                stopSelfSafely()<br>            } else {<br>                postStatusNotification(state, traffic)<br>            }<br>        }<br>    }<br>}</pre><p>(With one nice touch: it fingerprints the rendered content and skips the notify() binder call when nothing visible changed — traffic updates arrive every second, and there&#39;s no reason to spam the notification manager.)</p><p>The ViewModel mirrors the same flows into Compose state — speed sparklines, the session timer, and the map marker:</p><pre>private fun observeVpn() {<br>    screenModelScope.launch {<br>        combine(vpnManager.state, vpnManager.traffic) { s, t -&gt; s to t }.collect { (s, t) -&gt;<br>            _state.update {<br>                it.copy(<br>                    connectionStatus = s.status,<br>                    downloadMbps = t.downloadMbps,<br>                    uploadMbps = t.uploadMbps,<br>                    downloadHistory = (it.downloadHistory + t.downloadMbps.toFloat())<br>                        .takeLast(SPARKLINE_SAMPLES),<br>                    connectedSinceEpochMs = s.connectedSinceEpochMs,<br>                    countryName = s.serverCountryName ?: it.countryName,<br>                    ...<br>                )<br>            }<br>            s.error?.let { err -&gt;<br>                _events.tryEmit(HomeEvent.ShowError(err.messageRes))<br>                vpnManager.clearError()   // one-shot: consume so it never re-fires<br>            }<br>        }<br>    }<br>}</pre><p>A small trick hides in the map logic: the geo lookup for the server’s coordinates is kicked off already at CONNECTING — the server IP is known before the tunnel takes over routing, so the lookup usually completes on the untunneled network and the marker is ready the very moment the state flips to CONNECTED.</p><h3>The free-session timer — business logic that must survive process death</h3><p>Free users get a limited session (the limit comes from app settings, in minutes; 0 means unlimited). The countdown lives in the service, not a ViewModel — deliberately, because it must keep running with the app swiped away. The math is a pure object so it stays unit-testable:</p><pre>object FreeSessionLimit {<br>    fun deadlineEpochMs(connectedSinceEpochMs: Long, maxSessionMinutes: Int): Long? =<br>        if (maxSessionMinutes &lt;= 0) null<br>        else connectedSinceEpochMs + maxSessionMinutes * 60_000L<br><br>fun remainingMs(deadlineEpochMs: Long, nowEpochMs: Long): Long =<br>        (deadlineEpochMs - nowEpochMs).coerceAtLeast(0L)<br>}</pre><p>The service arms it only after the tunnel <em>actually</em> connects, and — key detail — a persisted deadline wins over computing a fresh one, so force-killing the app never extends a free session:</p><pre>private fun scheduleFreeSessionLimit() {<br>    sessionLimitJob?.cancel()<br>    sessionLimitJob = scope.launch {<br>        val settled = manager.state.first { it.status != ConnectionStatus.CONNECTING }<br>        if (settled.status != ConnectionStatus.CONNECTED) return@launch<br><br>    if (userViewModel.state.value.isPremium()) return@launch   // no limit for premium<br>            val deadline = stateStore.sessionDeadlineEpochMs() ?: run {<br>                val settings = runCatching { getAppSettings.execute() }.getOrNull() ?: return@launch<br>                val since = settled.connectedSinceEpochMs ?: System.currentTimeMillis()<br>                FreeSessionLimit.deadlineEpochMs(since, settings.freeUserMaxSessionTime)<br>                    ?: return@launch   // 0 = unlimited<br>            }<br>            stateStore.setSessionDeadline(deadline)<br>            delay(FreeSessionLimit.remainingMs(deadline, System.currentTimeMillis()).milliseconds)<br>            // Session expired: notify, drop the tunnel, and don&#39;t auto-reconnect.<br>            if (canPostNotifications()) showSessionEndedNotification()<br>            stateStore.setDesiredOn(false)<br>            teardown()<br>      }<br>}</pre><h3>The disconnect flow</h3><p>Disconnect looks symmetric on the diagram but has two traps of its own.</p><p>The path: tap disconnect → viewModel.disconnect() → vpnController.disconnect() → startForegroundService(ACTION_DISCONNECT) → handleDisconnect():</p><pre>private fun handleDisconnect() {<br>    scope.launch {<br>        sessionLimitJob?.cancel()<br>        stateStore.setDesiredOn(false)   // record intent: the user wants the VPN OFF<br>        teardown()<br>    }<br>}<br><br>/**<br> * Tears down the tunnel, then closes the server-side session. NonCancellable<br> * because the DISCONNECTED emission makes the observer stop this service,<br> * which cancels [scope] - the close call must survive that.<br> */<br>private suspend fun teardown() = withContext(NonCancellable) {<br>    sessionDeadlineEpochMs = null<br>    manager.disconnect()<br>    withContext(Dispatchers.IO) { retry { closeVpnConnection.execute() } }<br>}</pre><p><strong>Trap #1</strong>: teardown cancels itself. manager.disconnect() emits DISCONNECTED → the observer calls stopSelf() → onDestroy() cancels the service&#39;s coroutine scope → which would cancel the very coroutine still running teardown(), killing the session-end API call and leaking the session server-side. withContext(NonCancellable) is the fix: the teardown finishes even as the service dies around it.</p><p><strong>Trap #2</strong>: the DOWN callback fires for every teardown — yours or the system’s. The manager funnels all of them through one handler:</p><pre>private fun onTunnelStateChange(newState: Tunnel.State) {<br>    if (newState == Tunnel.State.DOWN &amp;&amp; !swappingConfig) {<br>        // Tunnel dropped (revoked, killed, or torn down) — preserve any error already set.<br>        pollJob?.cancel()<br>        watchdogJob?.cancel()<br>        _traffic.value = VpnTraffic()<br>        _state.update { it.copy(status = ConnectionStatus.DISCONNECTED, connectedSinceEpochMs = null) }<br>        scope.launch { stateStore.clearSession() }<br>    }<br>}</pre><p>This single path covers the clean disconnect, the handshake-timeout teardown, and the case where another VPN app steals the tunnel (Android revokes yours). Whatever the cause, state converges to DISCONNECTED, the service observer sees it, stops the service, and the UI resets — the connect button returns to its idle state, the timer stops, and the map recenters to the user&#39;s real location.</p><h3>Surviving process death: intent vs. state</h3><p>Android <em>will</em> kill your process. The design that makes this survivable is separating what the user wants from what currently is. The current state lives in memory (StateFlow); the user&#39;s <em>intent</em> and the session&#39;s timestamps are persisted in a dedicated DataStore:</p><pre>// Deliberately a separate DataStore file: TokenLocalDataSource.clear() wipes the whole<br>// &quot;token_prefs&quot; store on logout, and VPN state must survive that.<br>private val Context.vpnDataStore by preferencesDataStore(name = &quot;vpn_prefs&quot;)<br><br>@Single<br>class VpnStateStore(context: Context) {<br>    suspend fun isDesiredOn(): Boolean = ...          // &quot;I want the VPN on&quot;<br>    suspend fun connectedSinceEpochMs(): Long? = ...  // session timer survives restart<br>    suspend fun sessionDeadlineEpochMs(): Long? = ... // free-session deadline survives restart<br>    suspend fun selectedServer(): ServerEntity? = ... // the server the user picked<br>}<br></pre><p>When the system restarts the service (START_STICKY, null intent), it reconciles intent against reality:</p><pre>private fun handleRestart() {<br>    scope.launch {<br>        // If the free session expired while we were dead, don&#39;t reconnect at all.<br>        val expiredDeadline = stateStore.sessionDeadlineEpochMs()<br>            ?.let { FreeSessionLimit.remainingMs(it, System.currentTimeMillis()) == 0L } == true<br>        val desired = stateStore.isDesiredOn() &amp;&amp; !expiredDeadline<br>        when {<br>            manager.state.value.status != ConnectionStatus.DISCONNECTED -&gt; {<br>                // Tunnel/manager survived (service-only restart); just re-arm.<br>                startObserving(); scheduleFreeSessionLimit()<br>            }<br>            // Consent can be revoked while we&#39;re dead; VpnService.prepare() is the check.<br>            desired &amp;&amp; VpnService.prepare(this@VpnForegroundService) == null -&gt; {<br>                manager.markConnecting(); startObserving()<br>                connectAndScheduleLimit(freshSession = false)  // resume the old countdown<br>            }<br>            else -&gt; {<br>                stateStore.setDesiredOn(false); stateStore.clearSession()<br>                startObserving(); stopSelfSafely()<br>            }<br>        }<br>    }<br>}</pre><p>And if only the <em>UI</em> died while the tunnel lived on, the manager re-adopts it at startup — restoring the persisted session start so the Home timer doesn’t restart from zero:</p><pre>/** Re-adopt a tunnel that survived the UI/process, restoring the persisted session start. */<br>private fun restoreState() {<br>    scope.launch {<br>        if (isTunnelRunning()) {<br>            val persistedSince = stateStore.connectedSinceEpochMs()<br>            _state.update {<br>                it.copy(<br>                    status = ConnectionStatus.CONNECTED,<br>                    connectedSinceEpochMs = it.connectedSinceEpochMs<br>                        ?: persistedSince ?: System.currentTimeMillis(),<br>                )<br>            }<br>            startPolling()<br>        }<br>    }<br>}</pre><h3>Error handling: one enum, one channel</h3><p>Every failure in the whole flow funnels into a small user-facing enum, resolved to localized text only at the UI layer:</p><pre>enum class VpnError(@StringRes val messageRes: Int) {<br>    CONFIG_FETCH(R.string.vpn_error_config_fetch),        // backend unreachable / session denied<br>    CONFIG_PARSE(R.string.vpn_error_config_parse),        // malformed WireGuard config<br>    NOT_AUTHORIZED(R.string.vpn_error_not_authorized),    // user declined the consent dialog<br>    HANDSHAKE_TIMEOUT(R.string.vpn_error_handshake_timeout), // interface up, server silent (15s)<br>    DNS_FAILURE(R.string.vpn_error_dns),                  // endpoint hostname didn&#39;t resolve<br>    UNKNOWN(R.string.vpn_error_unknown),<br>}</pre><p>Backend exceptions map into it (BackendException.Reason.VPN_NOT_AUTHORIZED → NOT_AUTHORIZED, DNS_RESOLUTION_FAILURE → DNS_FAILURE), and the ViewModel consumes each error exactly once: show snackbar → clearError(). No sticky error states, no error dialogs surviving a screen rotation.</p><h3>Takeaways</h3><p>If you’re building a VPN app on Android, these are the decisions from this codebase I’d carry into any new one:</p><ol><li>One owner for the tunnel. A singleton manager publishing StateFlows; everyone else drives or observes. The moment two components can call setState(), you have races.</li><li>UP ≠ connected. Gate CONNECTED on the first WireGuard handshake, and back it with a watchdog so failure is loud and bounded (15s), not an infinite spinner.</li><li>Foreground service = process keep-alive + notification, nothing more. It fetches configs and delegates; it never touches the tunnel. And it must startForeground() synchronously.</li><li>Persist intent, not just state. isDesiredOn + persisted deadlines let START_STICKY restarts, reboots, and force-kills reconcile correctly — and prevent free users from resetting their session limit by killing the app.</li><li>Make teardown NonCancellable. Any cleanup that includes a network call (closing the server-side session) must survive the service cancelling its own scope.</li><li>Optimistic CONNECTING, suppressed intermediate DOWNs. Users judge the app by the connect button and the notification; never let internal transitions (server swap, initial snapshot) leak as visible flicker.</li></ol><p>The full sequence — every arrow in this post — lives in the interactive diagram <a href="https://hadiuzzaman524.github.io/vpn-android/index.html">VPN Connection Flow</a>, covering the connect flow, disconnect flow, the expanded service layer (VpnController → VpnForegroundService → VpnConnectionManager), and the tunnel/monitoring detail (1-second polling, 15-second watchdog).</p><p><em>Happy tunneling.</em> 🔐</p><h3>Connect with me</h3><p>If you enjoyed this deep dive, I write more about Android, iOS, and TV app development:</p><ul><li>📄 Interactive VPN flow docs: <a href="https://hadiuzzaman524.github.io/vpn-android/index.html">hadiuzzaman524.github.io/vpn</a></li><li>💼 LinkedIn: <a href="https://www.linkedin.com/pub/dir/Md/Hadiuzzaman">Md Hadiuzzaman</a> — let’s connect!</li><li>✍️ Medium: <a href="https://md-hadi.medium.com/">md-hadi.medium.com</a> — follow for more articles like this one</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee1c5d6dda01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Structural Design Patterns, Explained Through Real Flutter Code]]></title>
            <link>https://md-hadi.medium.com/the-structural-design-patterns-explained-through-real-flutter-code-cc538a003b2c?source=rss-3e2e8c53b23b------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc538a003b2c</guid>
            <category><![CDATA[clean-code-principle]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[structural-design-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Hadiuzzaman]]></dc:creator>
            <pubDate>Fri, 24 Jul 2026 04:50:05 GMT</pubDate>
            <atom:updated>2026-07-24T04:50:05.426Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 2 — a hands-on tour of Facade, Decorator, Proxy, Bridge, Adapter, and Composite, using a production-grade Clean Architecture template instead of Shape/Circle/Square</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_HSjJ1JNQEi8AoEWKQPhqg.png" /></figure><blockquote><em>TL;DR — </em><strong><em>Creational patterns answer </em>who builds this object</strong>?<em> </em><strong><em>Structural patterns answer </em>how are objects wired together into a larger whole without the pieces becoming welded to each other?<em> </em></strong><em>This is Part 2 of the series </em><a href="https://medium.com/@md-hadi/the-creational-design-patterns-explained-through-real-flutter-code-a32c3bafc5ad"><em>(Part 1 covered the creational patterns)</em></a><em>, and like Part 1 every snippet is lifted, unedited, from a real open-source </em><a href="https://github.com/hadiuzzaman524/flutter-clean-architecture"><em>Flutter Clean Architecture template</em></a><em>. This time the star is a feature that landed recently: a subscription paywall in front of the user list. It turns out to touch five structural patterns at once — and a sixth, Composite, has been hiding in plain sight in every </em><em>build() method.</em></blockquote><h3>Recap, and why structure is a different problem</h3><p>In <a href="https://medium.com/@md-hadi/the-creational-design-patterns-explained-through-real-flutter-code-a32c3bafc5ad">Part 1</a> we looked at the five creational patterns — the ones concerned with the moment an object comes into existence. <strong><em>Singleton, Factory Method, Abstract Factory, Builder, Prototype</em></strong>. Each answered a variant of <em>who builds this, and how?</em></p><p>Structural patterns are the second of the Gang of Four’s three buckets, and they answer a completely different question. Once you have objects, how do you compose them into bigger structures — and keep those structures flexible, so a change in one corner doesn’t ripple through the whole app? Structural patterns are about the <em>seams</em> between objects: converting one interface to another, wrapping an object to add behavior, hiding a messy subsystem behind a clean front door, standing a gatekeeper in front of an expensive resource, splitting one hierarchy into two that can vary independently.</p><p>The GoF list seven structural patterns. We’ll cover six: <strong><em>Facade, Decorator, Proxy, Bridge, and Adapter</em></strong> — traced through a single real feature — plus <strong><em>Composite</em></strong>, the one Flutter itself is built on, which we’ll save for the end. (The remaining one — Flyweight — genuinely doesn’t earn its keep in this codebase, and I’d rather show you six patterns that are actually <em>there</em> than manufacture an example for one that isn’t.)</p><p>If you want to follow along in your editor:</p><pre>git clone https://github.com/hadiuzzaman524/flutter-clean-architecture</pre><h3>The feature we’ll keep coming back to</h3><p>Rather than jump between unrelated examples, most of this article traces a single recently-added feature: fetching the user list is now gated behind a subscription paywall. Tap into the home screen without a subscription and you hit a paywall dialog; subscribe, and the list loads.</p><p>That one feature quietly stacks a caching layer, an access-control gate, a domain mapper, and an environment-specific wiring switch on top of each other — which makes it a near-perfect tour of the structural patterns. Here’s the chain a single getUserList() call flows through, top to bottom:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aS3_aUemge60-gsNBYE0vg.png" /></figure><p>We’ll walk the patterns roughly top-down along that chain — from the front door the UI sees all the way to the wire — then show how they compose at the end.</p><h3>1. Facade — one simple door in front of a complex subsystem</h3><p>Intent: Provide a unified, higher-level interface to a set of interfaces in a subsystem, making the subsystem easier to use.</p><p>Real-world picture: you order at a restaurant by telling the waiter “one pasta, please.” You don’t walk into the kitchen, negotiate with the chef, check the pantry, and operate the stove. The waiter is a <em>facade</em> — one simple interface in front of a complicated subsystem you never have to see.</p><p>A facade doesn’t add behavior (that’s Decorator) or control access (that’s Proxy) — we’ll meet both shortly. It just gives callers a small, purpose-shaped surface over something that’s larger or fiddlier than they should have to deal with.</p><p>The clearest example in the template is the use case. The presentation layer never talks to the repository chain directly — it calls a use case with a single execute():</p><pre>@singleton<br>class GetUserListUseCase with BaseUseCase&lt;List&lt;UserEntity&gt;&gt; {<br>  GetUserListUseCase(this._userRepository);<br><br>final UserRepository _userRepository;<br>  @override<br>  Future&lt;List&lt;UserEntity&gt;&gt; execute() =&gt; _userRepository.getUserList();<br>}</pre><p>That looks almost too thin to matter — but that’s exactly the point. Behind _userRepository sits the entire Proxy → Decorator → Bridge chain this article builds up section by section: a subscription gate, a cache-first read path, a factory-selected data source, and a domain mapper. The Cubit is completely insulated from all of it. It knows one verb, execute(), and one return type, List&lt;UserEntity&gt;. That&#39;s a facade over a subsystem that happens to be several patterns deep — and it&#39;s what lets the presentation layer stay blissfully unaware every time we add another layer underneath.</p><h3>A second facade: SecureStorageService</h3><p>The same idea shows up around token storage. SecureStorageService hides flutter_secure_storage — a generic write(key:)/read(key:)/delete(key:) key/value store backed by the Android Keystore and iOS Keychain — behind four verbs that speak the app&#39;s language, so the token key never leaks across the codebase:</p><pre>@lazySingleton<br>class SecureStorageService {<br>  SecureStorageService(this._storage);<br><br>final FlutterSecureStorage _storage;<br>  static const _accessTokenKey = &#39;access_token&#39;;<br><br>  Future&lt;void&gt; setAccessToken(String token) =&gt;<br>      _storage.write(key: _accessTokenKey, value: token);<br><br>  Future&lt;String?&gt; getAccessToken() =&gt; _storage.read(key: _accessTokenKey);<br><br>  Future&lt;bool&gt; hasAccessToken() async {<br>    final token = await _storage.read(key: _accessTokenKey);<br>    return token != null &amp;&amp; token.isNotEmpty;<br>  }<br><br>  Future&lt;void&gt; clearAccessToken() =&gt; _storage.delete(key: _accessTokenKey);<br> <br> String generateToken() { /* … */ }<br>}<br></pre><p>Callers say secureStorage.setAccessToken(token) — they never touch a raw key and never risk a typo&#39;d key string. And because the facade is injectable rather than a static wrapper, the whole thing is trivially mockable in tests (a theme we hit repeatedly in Part 1).</p><h3>The takeaway</h3><p>When callers only need a handful of operations from a subsystem that exposes dozens (or one that’s simply awkward to use correctly), put a facade in front of it. You shrink the surface area, centralize the fiddly details, and get a natural seam for mocking.</p><h3>2. Decorator — wrap an object to add behavior</h3><p>Intent: Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality — the decorator implements the <em>same interface</em> as the thing it wraps.</p><p>Real-world picture: a gift inside wrapping paper inside a ribbon inside a box. Each layer adds something (looks, protection, surprise) without changing the gift itself — and from the outside, a wrapped gift is still handed over exactly like an unwrapped one. You can add or remove layers freely; the gift never knows.</p><p>The subscription feature needed user data to be cached so a returning user doesn’t re-hit the network on every visit. The naive move is to stuff caching logic into UserRepositoryImpl. But that welds two concerns together and makes the repository harder to test and reason about.</p><p>The template does it the Decorator way instead. UserCacheRepositoryImpl implements the very same UserRepository interface as the repository it wraps, and adds a cache-first read path <em>around</em> it:</p><pre>@Named(&#39;cached&#39;)<br>@LazySingleton(as: UserRepository)<br>class UserCacheRepositoryImpl implements UserRepository {<br><br>  UserCacheRepositoryImpl(<br>    @Named(&#39;remote&#39;) this._remoteRepo,   // the object being decorated<br>    this._localDataSource,<br>  );<br><br>  final UserRepository _remoteRepo;<br>  final UserLocalDataSource _localDataSource;<br>  @override<br>  Future&lt;List&lt;UserEntity&gt;&gt; getUserList() async {<br>    // 1. Try to serve from cache first<br>    final localUsers = await _localDataSource.getUserList();<br>    if (localUsers.isNotEmpty) {<br>      return localUsers;<br>    }<br>    // 2. If cache is empty, fetch from remote<br>    final remoteUsers = await _remoteRepo.getUserList();<br>    // 3. Update cache<br>    await _localDataSource.saveUserList(remoteUsers);<br>    return remoteUsers;<br>  }<br>  // getUserById() follows the same cache-then-fallback shape.<br>}</pre><p>The two hallmarks of Decorator are both here: it is-a UserRepository, and it has-a UserRepository. That&#39;s what lets it stand in transparently anywhere a UserRepository is expected while quietly adding the caching responsibility. The @Named annotations are how the DI container tells the two implementations apart — the cached decorator asks for the &#39;remote&#39; one by name and wraps it.</p><p>Crucially, UserRepositoryImpl has no idea it&#39;s being decorated. Caching was added without touching a line of the class that does the actual fetching. Want to add logging next? Write a LoggingUserRepository decorator and slot it into the chain — still zero edits to the classes underneath.</p><h3>Decorator on the network layer</h3><p>Dio has the Decorator pattern baked into its architecture as interceptors. An Interceptor wraps every request/response passing through the client and can add behavior transparently. The template uses one to translate raw backend errors into the app&#39;s own typed ResponseError:</p><pre>class BackendErrorInterceptor extends Interceptor {<br>  @override<br>  void onError(DioException err, ErrorInterceptorHandler handler) {<br>    final data = err.response?.data;<br>    if (data is Map&lt;String, dynamic&gt;) {<br>      try {<br>        final backendError = BackendError.fromJson(data);<br>        handler.reject(<br>          DioException(<br>            requestOptions: err.requestOptions,<br>            type: err.type,<br>            response: err.response,<br>            error: ResponseError.from(backendError.message),<br>          ),<br>        );<br>        return;<br>      } catch (_) {}<br>    }<br>    handler.reject(/* fall back to a generic ResponseError */);<br>  }<br>}</pre><p>It’s registered once, while the Dio client is being built:</p><pre>Dio _createBaseDio(String baseURL) {<br>  final dio = Dio()..options.baseUrl = baseURL;<br>  dio.options.connectTimeout = const Duration(seconds: 12);<br>  dio.options.receiveTimeout = const Duration(seconds: 12);<br>  dio.options.contentType = &#39;application/json&#39;;<br>  dio.interceptors.add(BackendErrorInterceptor());   // decorate the client<br>  return dio;<br>}</pre><p>Every call through that Dio now gets error-translation behavior layered on, and no call site had to change. Stack a second interceptor (auth headers, retries, logging) and you&#39;re stacking decorators — which is exactly what dio.interceptors is, a list of decorators applied in order.</p><h3>Decorator in the widget tree</h3><p>Flutter’s entire composition model is Decorator-flavored — a Padding wraps a child to add padding, a Center wraps it to center it. The template&#39;s InternetOverlay is a purpose-built one: it takes any child widget and layers a &quot;No Internet&quot; banner on top of it, without the child knowing:</p><pre>class InternetOverlay extends StatelessWidget {<br>  const InternetOverlay({super.key, required this.child});<br><br>  final Widget child;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Material(<br>      type: MaterialType.transparency,<br>      child: BlocBuilder&lt;DeviceStatusCubit, DeviceStatusState&gt;(<br>        builder: (context, state) {<br>          return Stack(<br>            children: [<br>              child,                              // the wrapped widget<br>              // …an animated banner that slides in when offline<br>            ],<br>          );<br>        },<br>      ),<br>    );<br>  }<br>}</pre><h3>The takeaway</h3><p>When you want to add a responsibility (caching, error-handling, an overlay) to an object <em>without</em> modifying it and <em>without</em> an explosion of subclasses, wrap it in a decorator that shares its interface. The wrapped object stays oblivious, and decorators compose — you can stack as many as you like.</p><h3>3. Proxy — a gatekeeper that stands in for the real thing</h3><p>Intent: Provide a surrogate or placeholder for another object to control access to it. The proxy implements the same interface as the real subject, so callers can’t tell the difference — but it decides <em>whether</em> and <em>when</em> to forward the call.</p><p>Real-world picture: the bouncer at a members-only club. They stand at the same door you’d use anyway, and if your membership checks out you pass through as if they weren’t there. No membership? You never even see the inside. The club (the real object) doesn’t check anyone — the bouncer (the proxy) does.</p><p>This is the pattern the subscription paywall is built on, and the template makes it delightfully explicit — the class is <em>literally named</em> Proxy:</p><pre>@Environment(AppEnvironment.production)<br>@Environment(AppEnvironment.staging)<br>@LazySingleton(as: UserRepository)<br>class UserSubscriptionProxyRepositoryImpl implements UserRepository {<br>  UserSubscriptionProxyRepositoryImpl(<br>    @Named(&#39;cached&#39;) this._repository,        // the real subject<br>    this._subscriptionRepository,<br>  );<br><br>  final UserRepository _repository;<br>  final SubscriptionRepository _subscriptionRepository;<br>  @override<br>  Future&lt;List&lt;UserEntity&gt;&gt; getUserList() async {<br>    _ensureSubscribed();<br>    return _repository.getUserList();<br>  }<br>  @override<br>  Future&lt;UserEntity&gt; getUserById({required String userId}) async {<br>    _ensureSubscribed();<br>    return _repository.getUserById(userId: userId);<br>  }<br>  void _ensureSubscribed() {<br>    if (!_subscriptionRepository.isSubscribed()) {<br>      throw const SubscriptionRequiredException();<br>    }<br>  }<br>}</pre><p>This is the classic protection proxy. Structurally it looks almost identical to the Decorator from section 2 — same interface, wraps another instance of that interface. The difference is <em>intent</em>:</p><ul><li>A Decorator adds new behavior and always forwards the call (the cache still ultimately returns your users).</li><li>A Proxy controls access and may <em>refuse</em> to forward (no subscription → you get a SubscriptionRequiredException, and the real repository is never even called).</li></ul><p>The gate is one tiny method, _ensureSubscribed(), checked before every delegation. The real UserRepository — the cached decorator, and everything beneath it — stays blissfully unaware that access control exists at all.</p><h3>The keystone detail: the proxy is optional, and DI decides</h3><p>Look at the annotations. The proxy is only registered for staging and production. Development builds skip the paywall entirely, and the DI module wires UserRepository straight to the cached repository, bypassing the proxy:</p><pre>@module<br>abstract class UserRepositoryModule {<br>  // Development builds skip the subscription paywall, so `UserRepository`<br>  // resolves straight to the cached repository instead of the subscription<br>  // proxy (which is only registered for staging/production).<br>  @Environment(AppEnvironment.development)<br>  @lazySingleton<br>  UserRepository cachedUserRepository(@Named(&#39;cached&#39;) UserRepository repo) =&gt;<br>      repo;<br>}</pre><p>This is the Proxy pattern showing its best property: because the proxy shares the subject’s interface, it can be <em>slotted in or left out</em> with zero impact on any caller. Dev developers never fight a paywall; staging and production enforce it; and not one line of Cubit, use-case, or UI code knows which world it’s running in.</p><h3>Where the refusal surfaces</h3><p>Because the proxy throws instead of returning, the UserCubit gets to translate that into a paywall state — and the UI shows a subscribe dialog:</p><pre>Future&lt;void&gt; getUserList() async {<br>  try {<br>    emit(state.copyWith(status: const BaseStatus.loading(),<br>                        isSubscriptionRequired: false));<br>    final userList = await _getUserListUseCase.execute();<br>    emit(state.copyWith(userList: userList, status: const BaseStatus.success()));<br>  } on SubscriptionRequiredException {<br>    emit(state.copyWith(status: const BaseStatus.initial(),<br>                        isSubscriptionRequired: true));   // → paywall dialog<br>  } catch (e) {<br>    _logger.e(e);<br>    emit(state.copyWith(status: BaseStatus.failure(ResponseError.from(e))));<br>  }<br>}</pre><p>One custom exception, thrown deep in the data layer by a proxy, cleanly becomes a piece of UI state at the top. The layers in between just let it pass.</p><h3>The takeaway</h3><p>When you need to guard, defer, cache, or otherwise <em>mediate</em> access to an object — without callers knowing a gatekeeper is present — give the gatekeeper the same interface as the real subject and let it decide what to forward. And because it’s interface-compatible, whether it’s even in the chain can be a per-environment wiring decision.</p><h3>4. Bridge — let the abstraction and the implementation vary independently</h3><p>Intent: Decouple an abstraction from its implementation so that the two can vary independently — instead of binding them together in one rigid class hierarchy.</p><p>Real-world picture: a TV remote and a TV. The remote defines <em>what you can ask for</em> — volume up, channel down. The TV defines <em>how it actually happens</em> — Samsung does it one way, LG another. Because the two talk through a standard interface (the infrared protocol), remote designs and TV brands evolve completely independently: a new universal remote works with your old TV, and a new TV works with your old remote. Nobody manufactures a SamsungVolumeButtonRemote.</p><p>Bridge is the most abstract pattern in this article, and also the one that has been silently holding the whole template up since Part 1. Here’s the punchline up front: if you’ve ever written Clean Architecture’s classic repository → data-source split, you’ve already used Bridge — most likely without naming it.</p><p>Strip away the jargon and Bridge is about two questions that live in every data feature, and change for <em>different reasons</em>:</p><ol><li>What to do — the <em>business contract</em>. “Give me the user list.” This side is UserRepository, and it grows as features are added: plain fetch, cache-first fetch, subscription-gated fetch.</li><li>How the data comes — the <em>mechanism</em>. Over HTTP via Retrofit/Dio, or from an in-memory mock. This side is UserDataSource, and it changes with the build flavor.</li></ol><p>If you fused these into one hierarchy, you’d get a combinatorial mess: CachedRemoteUserRepo, CachedMockUserRepo, ProxiedCachedRemoteUserRepo, and so on — a new class for every <em>combination</em>. Bridge refuses that. It puts the two questions on opposite sides of an interface &quot;bridge&quot; and lets each side grow without the other noticing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sJCSWUVdj4hHoUP7lsCy2Q.png" /></figure><p>The abstraction side is UserRepository — the business contract. Notice it speaks pure domain language (UserEntity) and says nothing about where data lives:</p><pre>abstract class UserRepository {<br>  Future&lt;List&lt;UserEntity&gt;&gt; getUserList();<br>  Future&lt;UserEntity&gt; getUserById({required String userId});<br>}</pre><p>The implementation side is UserDataSource — deliberately a <em>separate</em> interface, speaking in wire-format models:</p><pre>abstract class UserDataSource {<br>  Future&lt;List&lt;UserResponseModel&gt;&gt; getUserList();<br>  Future&lt;UserResponseModel&gt; getUserById({required String userId});<br>}</pre><p>You’ve already met every class in the diagram above. The repository side grew all through this article: UserRepositoryImpl (plain), UserCacheRepositoryImpl (the Decorator from section 2), UserSubscriptionProxyRepositoryImpl (the Proxy from section 3) — three and counting. The data-source side has UserRemoteDataSource (real) and UserMockDataSource (fake). Neither side knows how many variants the other has.</p><p>The two sides meet at a single connector — the UserDataSource reference that UserRepositoryImpl holds as a field, supplied by the DataSourceFactory (the same Abstract Factory from <a href="https://markdownlivepreview.com/medium-creational-design-patterns-in-flutter.md">Part 1</a>, here deciding what sits on the far side of the bridge):</p><pre>@Named(&#39;remote&#39;)<br>@Singleton(as: UserRepository)<br>class UserRepositoryImpl extends UserRepository {<br>  UserRepositoryImpl(DataSourceFactory factory)<br>      : _userDataSource = factory.createUserDataSource();<br><br>  final UserDataSource _userDataSource;   // ← this reference IS the bridge<br>  @override<br>  Future&lt;List&lt;UserEntity&gt;&gt; getUserList() async {<br>    final response = await _userDataSource.getUserList();<br>    return response.toUserEntities();<br>  }<br>  // ...<br>}</pre><p>UserRepositoryImpl holds a UserDataSource reference, not a concrete class. It has no idea whether it&#39;s talking to the remote source or the mock — that&#39;s chosen by the factory, which is chosen by the environment.</p><p>The payoff is the independent variation:</p><ul><li>Add a GraphQL data source? Implement UserDataSource once. Every repository variant — plain, cached, proxied — works on top of it unchanged.</li><li>Add a logging repository decorator? Implement UserRepository once. It works over remote <em>or</em> mock data unchanged.</li></ul><p>Three behaviors plus two sources costs 3 + 2 = 5 classes instead of 3 × 2 = 6 fused ones — and the gap widens with every variant either side adds.</p><h3>How to spot a Bridge (and not confuse it with plain DI)</h3><p>Holding an interface as a field isn’t automatically Bridge — that’s just ordinary abstraction with dependency injection. Ask three questions:</p><ol><li>Do the two things change for different reasons? Here, repository behavior changes when <em>features</em> are added; the data source changes when the <em>environment</em> does.</li><li>Do both sides have (or expect) multiple variants? One side varying is plain DI. Both sides varying — three repositories, two data sources — is Bridge.</li><li>Would fusing them cause a class-per-combination explosion? If yes, that’s the Bridge signal.</li></ol><p>One line to remember:</p><blockquote><em>Split “what to do” (the business contract) and “how it’s done” (the mechanism) into two interfaces, hold one as a reference inside the other, and let each side evolve on its own. That’s Bridge.</em></blockquote><h3>The takeaway</h3><p>When you catch yourself about to create a class for every <em>combination</em> of two things that change — behavior × backend, shape × platform, widget × theme — stop. Split them into two interfaces, hold one as a reference inside the other, and let each side evolve on its own.</p><h3>5. Adapter — make an incompatible interface fit</h3><p>Intent: Convert the interface of a class into another interface the client expects. Adapter lets classes work together that otherwise couldn’t because of mismatched shapes.</p><p>Real-world picture: you land in London with a European plug and face a UK wall socket. You don’t rewire your laptop, and the hotel doesn’t rebuild its walls. You put a £5 travel adapter between the two, and both sides stay exactly as they are. That’s the whole pattern.</p><p>After Bridge — the most abstract pattern in the tour — comes the most down-to-earth one. Clean Architecture practically <em>demands</em> an Adapter at a specific seam: the boundary between the data layer and the domain layer. It’s the last stop in our call chain, where the wire format becomes the domain’s language.</p><p>Here’s the tension. The API speaks JSON, and its shape is not yours to control — it’s nested, nullable, and full of fields the domain doesn’t care about:</p><pre>@freezed<br>abstract class UserResponseModel with _$UserResponseModel {<br>  const factory UserResponseModel({<br>    int? id,<br>    String? name,<br>    String? username,<br>    String? email,<br>    Address? address,     // nested…<br>    String? phone,<br>    String? website,<br>    Company? company,<br>  }) = _UserResponseModel;<br><br>factory UserResponseModel.fromJson(Map&lt;String, dynamic&gt; json) =&gt;<br>      _$UserResponseModelFromJson(json);<br>}<br>@freezed<br>abstract class Address with _$Address {<br>  const factory Address({<br>    String? street,<br>    String? suite,<br>    String? city,<br>    String? zipcode,<br>    Geo? geo,             // …and nested again<br>  }) = _Address;<br>}</pre><p>The domain, meanwhile, wants a flat, non-nullable, self-describing UserEntity. It should never see Geo or a nullable street:</p><pre>@freezed<br>abstract class UserEntity with _$UserEntity {<br>  const factory UserEntity({<br>    required String name,<br>    required String email,<br>    required String address,<br>    required String city,<br>    required double latitude,<br>    required double longitude,<br>  }) = _UserEntity;<br>}</pre><p>These two interfaces are incompatible. Something has to translate. That something is the adapter, implemented here as a Dart extension method:</p><pre>extension UserResponseMapper on List&lt;UserResponseModel&gt; {<br>  List&lt;UserEntity&gt; toUserEntities() {<br>    return map((userResponse) =&gt; userResponse.toUserEntity()).toList();<br>  }<br>}<br><br>extension UserResponseItemMapper on UserResponseModel {<br>  UserEntity toUserEntity() {<br>    return UserEntity(<br>      name: name ?? &#39;&#39;,<br>      email: email ?? &#39;&#39;,<br>      address: address?.street ?? &#39;&#39;,<br>      city: address?.city ?? &#39;&#39;,<br>      latitude: double.parse(address?.geo?.lat ?? &#39;0&#39;),<br>      longitude: double.parse(address?.geo?.lng ?? &#39;0&#39;),<br>    );<br>  }<br>}</pre><p>toUserEntity() is the adapter. It takes an object shaped like the <em>network</em> wants it and returns one shaped like the <em>domain</em> wants it — flattening the nesting, supplying defaults for nulls, and parsing the stringly-typed lat/lng into real doubles. The repository consumes it in one line, and the domain never learns that a Geo object ever existed:</p><pre>@override<br>Future&lt;List&lt;UserEntity&gt;&gt; getUserList() async {<br>  final response = await _userDataSource.getUserList();<br>  return response.toUserEntities();   // adapt at the boundary<br>}</pre><p>Putting the adapter in an extension is a nice Dart touch: neither UserResponseModel nor UserEntity has to know the other exists, so there&#39;s zero coupling in either direction. The translation lives entirely in the seam.</p><blockquote><em>A second, generated adapter. The Retrofit-generated </em><em>_UserRemoteDataSource is also an adapter — it wraps Dio&#39;s raw HTTP/JSON interface and exposes it as the app&#39;s typed </em><em>UserDataSource (</em><em>getUserList(), </em><em>getUserById()). You describe the interface; the generator writes the adapter that makes Dio fit it.</em></blockquote><h3>The takeaway</h3><p>Any time an external interface (a JSON payload, a third-party SDK, a legacy class) doesn’t match the interface your code wants to program against, don’t leak the mismatch inward. Write a thin adapter at the boundary and keep both sides ignorant of each other.</p><h3>6. Composite — treat one thing and a tree of things the same way</h3><p>Intent: Compose objects into tree structures to represent part–whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.</p><p>Real-world picture: a folder on your computer. A folder can hold files <em>and other folders</em>, which hold more files and folders, to any depth. And yet “copy”, “move”, and “delete” work identically whether you point them at one file or at a folder containing ten thousand — you never write different code for the leaf and for the tree.</p><p>Here’s the fun part: this is the one pattern in the article we <em>didn’t</em> have to go looking for, because Flutter itself is a giant Composite. If you’ve written a build() method, you&#39;ve used it.</p><p>The uniform interface is Widget. Some widgets are leaves — Text, Icon, an image — they draw something and hold no children. Others are composites — Scaffold, Column, Stack, Padding — their whole job is to hold and arrange child widgets. And crucially, <em>both kinds are just </em><em>Widget</em>. Anywhere a Widget is expected you can hand over a lone Icon or an entire screen, and the framework treats them identically.</p><p>Look at the template’s real home screen — one build() method, one tree:</p><pre>class HomePortraitView extends StatelessWidget {<br>  const HomePortraitView({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(                          // composite<br>      appBar: AppBar(                         // composite<br>        title: AppText.titleLarge(&#39;Flutter Template&#39;, /* … */),   // leaf<br>        actions: [<br>          BlocBuilder&lt;UserCubit, UserState&gt;(  // composite (wraps a subtree)<br>            builder: (context, state) {<br>              return Badge(                   // composite<br>                label: const Text(&#39;PRO&#39;),     // leaf<br>                child: IconButton(/* … */),   // leaf<br>              );<br>            },<br>          ),<br>          const ThemeDropDownButton(),        // a whole custom subtree<br>          Padding(                            // composite<br>            child: IconButton(/* … */),       // leaf<br>          ),<br>        ],<br>      ),<br>      body: const UserList(),                 // a whole custom subtree<br>    );<br>  }<br>}</pre><p>As a part–whole hierarchy:</p><pre>Scaffold<br> ├── AppBar<br> │    ├── AppText (&#39;Flutter Template&#39;)          ← leaf<br> │    └── actions<br> │         ├── Badge<br> │         │    ├── Text (&#39;PRO&#39;)                ← leaf<br> │         │    └── IconButton                  ← leaf<br> │         ├── ThemeDropDownButton              ← subtree, used like a leaf<br> │         └── Padding<br> │              └── IconButton                  ← leaf<br> └── UserList                                   ← subtree, used like a leaf</pre><p>Notice ThemeDropDownButton and UserList. Each is a full custom widget with its own internal tree — UserList alone contains a BlocBuilder, a list view, loading states, and error states. But the home screen neither knows nor cares. It places const UserList() exactly the way it places a single Icon — the composition is used through the same interface as a leaf. That uniformity is the entire pattern.</p><p>It’s also what makes Flutter’s model so composable. The framework’s layout and paint passes just walk the tree, calling the same protocol on every node — RenderObjects underneath do the same. Nobody special-cases &quot;is this a simple widget or a compound one?&quot;, which is why you can refactor any subtree into its own widget class (as the template does with UserList, SubscribeDialog, InternetOverlay) without touching the parent.</p><blockquote><em>Composite and Decorator are cousins. The </em><em>InternetOverlay from section 2 is </em>both<em>: as a Decorator it wraps a child to add a banner; as a node in the Composite tree it&#39;s just one more </em><em>Widget. Wrapping composes cleanly </em>because<em> everything shares the </em><em>Widget interface — the patterns reinforce each other.</em></blockquote><h3>The takeaway</h3><p>When your data or UI is naturally a part–whole tree — menus with submenus, org charts, file systems, widget trees — give leaves and containers one shared interface, and let containers hold children of that same interface. Clients then operate on “a thing” without ever asking whether it’s one object or a thousand.</p><h3>How the patterns compose</h3><p>Just like the creational patterns in Part 1, the structural patterns don’t compete — they stack. And in this template they stack in one literal call chain. Follow a single getUserList() from the home screen all the way to the wire:</p><ol><li>The Cubit calls GetUserListUseCase.execute() — a Facade that hides the whole repository chain behind one verb.</li><li>That resolves (in staging/production) to UserSubscriptionProxyRepositoryImpl — a Proxy that checks isSubscribed() and either forwards or throws.</li><li>It forwards to UserCacheRepositoryImpl — a Decorator that adds a cache-first read path around the real repository.</li><li>Which delegates to UserRepositoryImpl — the Bridge abstraction, holding a UserDataSource reference…</li><li>…resolved by DataSourceFactory to either the remote or mock Bridge implementation, chosen by build flavor.</li><li>The UserResponseModel that comes back is run through toUserEntity() — an Adapter — before the domain ever sees it. And any Dio error along the way was already reshaped by the BackendErrorInterceptor Decorator.</li></ol><p>Six patterns, one feature, zero classes that know about more than their immediate neighbor. That’s the whole point of structural patterns: each seam is clean, so each piece can change without disturbing the others. Adding the subscription paywall didn’t require editing the cache, the fetcher, the data sources, or the UI’s data path — it slotted a proxy into a chain that was <em>built to be slotted into</em>.</p><p>That composability is the return on investment. Where creational patterns keep object <em>creation</em> flexible, structural patterns keep object <em>relationships</em> flexible — and a codebase that’s flexible in both survives change without fracturing.</p><h3>Cheat sheet</h3><p>PatternIn one phraseReal-world pictureIn this templateFacadeOne simple door in front of a complex subsystemThe waiter, not the kitchenGetUserListUseCase.execute()DecoratorSame interface, wraps to <em>add</em> behavior, always forwardsLayers of gift wrapUserCacheRepositoryImpl, Dio interceptorsProxySame interface, wraps to <em>control access</em>, may refuseThe bouncer at the club doorUserSubscriptionProxyRepositoryImplBridge&quot;What to do&quot; and &quot;how it&#39;s done&quot; split into two independent hierarchiesTV remote ↔ TV brandUserRepository ↔ UserDataSourceAdapterTranslate one interface into another at the boundaryTravel plug adaptertoUserEntity() mapperCompositeLeaves and trees behind one uniform interfaceFiles and foldersThe widget tree — HomePortraitView, UserList</p><p>And the fastest way to tell the three wrappers apart — Decorator, Proxy, and Facade all “stand in front of” something, so ask what the front thing <em>does</em>:</p><ul><li>Adds behavior and always passes the call through → Decorator</li><li>Decides whether you get through at all → Proxy</li><li>Shrinks a big surface down to a few friendly verbs → Facade</li></ul><h3>Explore (and star) the full project</h3><p>Everything in this article — and in <a href="https://medium.com/@md-hadi/the-creational-design-patterns-explained-through-real-flutter-code-a32c3bafc5ad">Part 1 on creational patterns</a> — comes from a real, MIT-licensed template you can build your own apps on. Beyond the patterns, it ships with:</p><ul><li>Clean Architecture layering (domain / data / presentation / core)</li><li>Multi-flavor builds (development / staging / production)</li><li>Dependency injection with get_it + injectable</li><li>Retrofit-based networking with a mockable data-source layer</li><li>BLoC/Cubit state management with sealed states and typed errors</li><li>A subscription paywall feature that stacks five of the six structural patterns covered here (and a widget tree that demonstrates the sixth)</li><li>Localization, code-gen scaffolding scripts, and a full test suite</li></ul><p>⭐ <a href="https://github.com/hadiuzzaman524/flutter-clean-architecture">github.com/hadiuzzaman524/flutter-clean-architecture</a></p><p>If this walkthrough made the patterns finally click, drop the repo a star — and if you spot a pattern worth adding to the tour, open an issue or a PR. Next up in the series: the behavioral patterns. The best way to learn a pattern is to read it in code that actually runs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc538a003b2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Creational Design Patterns, Explained Through Real Flutter Code]]></title>
            <link>https://md-hadi.medium.com/the-creational-design-patterns-explained-through-real-flutter-code-a32c3bafc5ad?source=rss-3e2e8c53b23b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a32c3bafc5ad</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Hadiuzzaman]]></dc:creator>
            <pubDate>Fri, 17 Jul 2026 03:19:52 GMT</pubDate>
            <atom:updated>2026-07-17T03:19:52.862Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6cXnfxderHskkkuOwZfQMA.png" /></figure><p>A hands-on tour of Singleton, Factory Method, Abstract Factory, Builder, and Prototype — using a production-grade Clean Architecture template instead of Animal/Dog/Cat</p><blockquote><em>TL;DR — Creational patterns all answer one question: </em>who builds this object, and how?<em> This article walks through all five using real code from an open-source </em><a href="https://github.com/hadiuzzaman524/flutter-clean-architecture"><em>Flutter Clean Architecture template</em></a><em>, so you see each pattern the way it actually appears in a shipping app — not as a textbook abstraction. Clone the repo and read along.</em></blockquote><h3>Why another design patterns article?</h3><p>Most design-pattern tutorials have the same problem: they teach you the <em>shape</em> of a pattern using examples you will never write. You learn Abstract Factory by manufacturing Chair and Sofa objects for a VictorianFurnitureFactory, close the tab, and then have no idea where that fits in the app you&#39;re actually building.</p><p>The patterns aren’t the problem. The examples are.</p><p>So this article takes the opposite approach. Every single snippet below is lifted, unedited, from a real open-source project — a <a href="https://github.com/hadiuzzaman524/flutter-clean-architecture">Flutter Clean Architecture template</a> that ships with dependency injection, multi-flavor builds, a networking layer, BLoC/Cubit state management, and a full test suite. We’ll look at where each of the five creational patterns naturally emerges, <em>why</em> it’s there, and what problem it quietly solves.</p><p>By the end you won’t just recognize these patterns — you’ll know the exact kind of pain that makes each one worth reaching for.</p><p>If you want to follow along in your editor:</p><pre>git clone https://github.com/hadiuzzaman524/flutter-clean-architecture</pre><h3>First, what is a “creational” pattern?</h3><p>The Gang of Four split their 23 patterns into three buckets: creational, structural, and behavioral. Creational patterns are the ones concerned with object construction — the moment a new instance comes into existence.</p><p>“Just call the constructor” is the default answer, and for simple objects it’s the right one. You don’t need a pattern to make a Point(2, 3). But construction gets complicated fast:</p><ul><li>What if the object is expensive and you only want one of it? <em>(Singleton)</em></li><li>What if the caller shouldn’t know the concrete class it’s getting? <em>(Factory Method)</em></li><li>What if several objects must be created as a consistent family? <em>(Abstract Factory)</em></li><li>What if building the object takes many configuration steps? <em>(Builder)</em></li><li>What if the cheapest way to make a new object is to copy an existing one? <em>(Prototype)</em></li></ul><p>Each pattern is a disciplined answer to one of those questions. Let’s take them in order.</p><h3>1. Singleton — one instance, shared everywhere</h3><p>Intent: Ensure a class has exactly one instance, and provide a single point of access to it.</p><p>The Singleton is the most famous creational pattern and, deservedly, the most criticized. The classic hand-rolled version looks like this:</p><pre>class Logger {<br>  Logger._();<br>  static final Logger instance = Logger._();<br>}</pre><p>It works. You call Logger.instance from anywhere and always get the same object. But it has two quiet costs that show up later:</p><ol><li>The class owns its own global access point. Logger.instance is baked in, so every call site is hard-wired to that specific static field.</li><li>It’s hostile to testing. You can’t substitute a fake logger, because the dependency is reached through a static, not passed in.</li></ol><p>This template sidesteps both problems by separating two concerns that the naive singleton conflates: <em>“what is this object?”</em> and <em>“how long does it live and who hands it out?”</em> The class stays a plain, ordinary object. Its lifetime is declared separately, in a dependency-injection container (get_it, wired up by the injectable code generator):</p><pre>@module<br>abstract class LoggerModule {<br>  @lazySingleton<br>  Logger get logger =&gt; Logger();<br>}</pre><p>Now injector&lt;Logger&gt;() returns the same instance app-wide — the Singleton guarantee is preserved — but Logger itself has no idea it&#39;s a singleton. It&#39;s just a class. In a test you register a MockLogger instead, and every consumer transparently gets the fake. You get the pattern&#39;s benefit without its usual testability tax.</p><h3>Eager vs. lazy: a choice that affects your startup time</h3><p>injectable offers two flavors of singleton, and picking the right one is a real performance decision, not a stylistic one:</p><pre>// EAGER: built the instant the DI container initialises.<br>@Singleton(as: UserRepository)<br>class UserRepositoryImpl extends UserRepository { ... }<br><br>// LAZY: built on first resolution, then cached forever after.<br>@LazySingleton()<br>abstract class UserRemoteDataSource implements UserDataSource { ... }</pre><ul><li>@Singleton constructs eagerly, during container initialisation. Use it for things you know you&#39;ll need right away — the core network layer, for instance.</li><li>@LazySingleton defers construction until the first time something asks for it, then caches it. A data source the user might never trigger in a given session costs literally nothing until it&#39;s actually used.</li></ul><p>On a large app with dozens of registered services, making everything eager can add measurable jank to your first frame. Being deliberate here matters.</p><h3>The takeaway</h3><p>Don’t hardcode static instance into your classes. Let a container own the lifetime. You keep the &quot;exactly one instance&quot; guarantee and gain the ability to swap in a mock — something the template&#39;s test suite leans on constantly.</p><h3>2. Factory Method — hide construction behind a method</h3><p>Intent: Define an interface for creating an object, but let a method — rather than a raw constructor call — decide what concrete thing comes back.</p><p>The essence of Factory Method is simple: instead of the caller writing SomeConcreteClass(...), they call a method that returns an <em>interface</em>, and that method decides which concrete implementation to build. The caller stays ignorant of the concrete type, which means you can change that type later without touching a single call site.</p><p>The template uses this idea in two complementary places.</p><h3>Factory Method in the DI wiring</h3><p>When a class has a constructor that needs specific wiring, injectable&#39;s @factoryMethod annotation marks which constructor the generator should call:</p><pre>@RestApi()<br>@LazySingleton()<br>abstract class AuthRemoteDataSource implements AuthDataSource {<br>  @factoryMethod<br>  factory AuthRemoteDataSource(@Named(DioClientType.unauthenticated) Dio dio) =<br>      _AuthRemoteDataSource;<br><br>@override<br>  @POST(&#39;/login&#39;)<br>  Future&lt;String&gt; login(@Body() LoginRequestModel inputModel);<br>}</pre><p>There’s no hand-written class body here at all. Retrofit generates the concrete _AuthRemoteDataSource, and the redirecting factory constructor (factory ... = _AuthRemoteDataSource) is itself a factory method: callers ask for an AuthRemoteDataSource and never once learn the name of the generated class. The @Named(...) argument even tells the factory <em>which</em> configured Dio client to inject — construction detail the caller is completely shielded from.</p><h3>Factory Method in the domain contract</h3><p>The second use is more classic. The data-source factory (which we’ll meet properly in the next section) exposes creator methods:</p><pre>abstract class DataSourceFactory {<br>  UserDataSource createUserDataSource();<br>  AuthDataSource createAuthDataSource();<br>}</pre><p>Each createXxx() is a factory method by the book. The repository that calls createAuthDataSource() receives an AuthDataSource <em>interface</em>. Whether the real object behind it is a live HTTP client or an in-memory mock is a decision made elsewhere — the caller neither knows nor cares.</p><h3>The takeaway</h3><p>The moment a caller would otherwise have to name a concrete class or know a wiring detail, put a method in front of it that returns the interface. That one indirection is what lets you swap implementations freely.</p><h3>3. Abstract Factory — create consistent families of objects</h3><p>Intent: Provide an interface for creating <em>families</em> of related objects without specifying their concrete classes — and guarantee the family stays internally consistent.</p><p>This is the pattern that ties the whole template together, and it’s the one most worth studying carefully, because the problem it solves is genuinely easy to get wrong.</p><p>Here’s the situation. The app builds in three flavors: development, staging, and production. In development we want mock data sources so the app runs with no backend at all. In staging and production we want real data sources that hit an actual API.</p><p>Now the subtle part. The app has more than one data source — a UserDataSource and an AuthDataSource — and they must be consistent with each other. A build must use <em>either</em> the full mock family <em>or</em> the full real family. Mixing a mock user source with a live auth source would be a nightmare: the app would half-work in a way that&#39;s maddening to debug. These data sources form a family, and keeping a family consistent is exactly what Abstract Factory exists to do.</p><h3>Step 1: Declare what a family looks like</h3><pre>abstract class DataSourceFactory {<br>  UserDataSource createUserDataSource();<br>  AuthDataSource createAuthDataSource();<br>}</pre><h3>Step 2: Provide one concrete factory per family</h3><pre>class MockDataSourceFactory implements DataSourceFactory {<br>  MockDataSourceFactory(this._userMock, this._authMock);<br><br>final UserMockDataSource _userMock;<br>  final AuthMockDataSource _authMock;<br>  @override<br>  UserDataSource createUserDataSource() =&gt; _userMock;<br>  @override<br>  AuthDataSource createAuthDataSource() =&gt; _authMock;<br>}<br><br>class RemoteDataSourceFactory implements DataSourceFactory {<br>  RemoteDataSourceFactory(this._userRemote, this._authRemote);<br>  final UserRemoteDataSource _userRemote;<br>  final AuthRemoteDataSource _authRemote;<br>  @override<br>  UserDataSource createUserDataSource() =&gt; _userRemote;<br>  @override<br>  AuthDataSource createAuthDataSource() =&gt; _authRemote;<br>}</pre><p>Each concrete factory produces one <em>coherent</em> family. There is no way for a caller holding a MockDataSourceFactory to accidentally get a real auth source — the factory only knows how to build mocks. Consistency is enforced by construction.</p><h3>Step 3 (the keystone): choose the family in exactly one place</h3><p>This is the decision that makes everything clean, and it’s worth pausing on. The choice of <em>which</em> family to build happens once, declaratively, in the DI module — not sprinkled through the data sources as if (isDev) branches:</p><pre>@module<br>abstract class DataSourceProvider {<br>  @Environment(AppEnvironment.development)<br>  @Singleton(as: DataSourceFactory)<br>  MockDataSourceFactory mockFactory(<br>    UserMockDataSource userMock,<br>    AuthMockDataSource authMock,<br>  ) =&gt; MockDataSourceFactory(userMock, authMock);<br><br>@Environment(AppEnvironment.production)<br>  @Environment(AppEnvironment.staging)<br>  @Singleton(as: DataSourceFactory)<br>  RemoteDataSourceFactory remoteFactory(<br>    UserRemoteDataSource userRemote,<br>    AuthRemoteDataSource authRemote,<br>  ) =&gt; RemoteDataSourceFactory(userRemote, authRemote);<br>}</pre><p>The @Environment(...) annotations gate registration by flavor. In development the container registers MockDataSourceFactory as <em>the</em> DataSourceFactory; in staging and production it registers RemoteDataSourceFactory. Crucially, the data sources themselves contain no environment logic whatsoever — they don&#39;t know which flavor is running, and they never ask.</p><p>Everything downstream just depends on the abstract DataSourceFactory and asks it for what it needs:</p><pre>@Singleton(as: AuthRepository)<br>class AuthRepositoryImpl extends AuthRepository {<br>  AuthRepositoryImpl(this._factory, this._secureStorage);<br><br>final DataSourceFactory _factory;<br>  final SecureStorageService _secureStorage;<br>  @override<br>  Future&lt;void&gt; login({required LoginEntity inputModel}) async {<br>    final token = await _factory<br>        .createAuthDataSource()<br>        .login(inputModel.toRequestModel());<br>    await _secureStorage.setAccessToken(token);<br>  }<br>}</pre><p>AuthRepositoryImpl has no clue whether it&#39;s talking to a mock or a real server. It just asks the factory. That&#39;s the entire point — the environment complexity is concentrated in one module and invisible everywhere else.</p><h3>A small but important detail: no magic strings</h3><p>Environment names are defined once as constants, so the @Environment(...) annotations and the flavor configs can&#39;t silently drift apart:</p><pre>abstract class AppEnvironment {<br>  const AppEnvironment._();<br>  static const String development = &#39;development&#39;;<br>  static const String staging = &#39;staging&#39;;<br>  static const String production = &#39;production&#39;;<br>}</pre><p>A typo like @Environment(&#39;developmnet&#39;) would fail silently — the factory just wouldn&#39;t register, and you&#39;d chase a null dependency at runtime. Centralizing the names as static const makes that class of bug impossible.</p><h3>The takeaway</h3><p>When several objects must vary <em>together</em> and stay mutually consistent, wrap their creation in an Abstract Factory and select the concrete factory in exactly one place. The reward shows up later: adding a fourth environment, or swapping the whole backend for tests, becomes a <em>local</em> change instead of a search-and-replace across the codebase hunting for every if (env == ...).</p><h3>4. Builder — assemble a complex object step by step</h3><p>Intent: Separate the construction of a complex object from its representation, so the same construction process can produce different configurations.</p><p>Some objects aren’t usable the moment you new them — they need several configuration steps first. A Dio HTTP client is a textbook case: it needs a base URL, connect and receive timeouts, a content type, and one or more interceptors before it&#39;s ready to make a request.</p><p>The template captures that whole assembly sequence in a single builder method and reuses it for every flavor and every client variant:</p><pre>@module<br>abstract class NetworkModule {<br>  final baseURL = Env.shared.baseUrl;<br><br>Dio _createBaseDio(String baseURL) {<br>    final dio = Dio()..options.baseUrl = baseURL;<br>    dio.options.connectTimeout = const Duration(seconds: 12);<br>    dio.options.receiveTimeout = const Duration(seconds: 12);<br>    dio.options.contentType = &#39;application/json&#39;;<br>    dio.interceptors.add(BackendErrorInterceptor());<br>    return dio;<br>  }<br><br>  @Environment(AppEnvironment.production)<br>  @Named(DioClientType.unauthenticated)<br>  @singleton<br>  Dio get unAuthenticatedProdDio =&gt; _createBaseDio(baseURL);<br>  @Named(DioClientType.authenticated)<br>  @singleton<br>  Dio get authenticatedDio =&gt; _createBaseDio(baseURL);<br>}</pre><p>_createBaseDio is the builder. It walks through the construction steps — set the base URL, configure timeouts, set the content type, attach the interceptor — and returns a finished, ready-to-use product. Every named Dio client in the app is assembled through this one method, which means a change to the timeout policy or a new global interceptor is a one-line edit that instantly applies everywhere.</p><p>Notice the cascade operator (..) on the first line. Dart&#39;s cascade is the language&#39;s built-in nod to the Builder pattern: it lets you perform a sequence of configuration operations on an object and still treat the whole thing as a single expression that yields the configured object.</p><h3>Builder, generated: freezed models</h3><p>There’s a second, generated flavor of Builder worth mentioning. Dart doesn’t give you ergonomic “construct-with-named-fields, then copy-with-changes” semantics out of the box. The freezed package generates them for you:</p><pre>@freezed<br>abstract class LoginRequestModel with _$LoginRequestModel {<br>  const factory LoginRequestModel({<br>    required String email,<br>    required String pin,<br>  }) = _LoginRequestModel;<br><br>factory LoginRequestModel.fromJson(Map&lt;String, dynamic&gt; json) =&gt;<br>      _$LoginRequestModelFromJson(json);<br>}</pre><p>You describe the shape once; the generator builds the immutable object, the fromJson/toJson plumbing, equality, and — as we&#39;ll see next — copyWith.</p><h3>The takeaway</h3><p>When construction involves several configuration steps — <em>especially</em> steps you’d otherwise repeat — extract them into a builder. Dart’s cascades and freezed give you idiomatic, low-ceremony ways to do exactly that.</p><h3>5. Prototype — build new objects by cloning existing ones</h3><p>Intent: Create new objects by copying an existing instance, rather than constructing one from scratch.</p><p>In classic OOP the Prototype pattern appears as an explicit clone() method. In modern, immutable Dart it appears as copyWith — and once you notice it, you see it everywhere in the state layer.</p><p>Application state in this template is immutable. That’s a deliberate choice: it makes state changes predictable and eliminates a whole category of “who-mutated-this” bugs. But immutability raises a question: if you can’t change the current state, how do you move from “loading” to “success”?</p><p>The answer is Prototype. You take the current state, clone it with a few fields overridden, and emit the clone as the new state:</p><pre>@freezed<br>sealed class UserState with _$UserState {<br>  const factory UserState({<br>    @Default([]) List&lt;UserEntity&gt; userList,<br>    @Default(BaseStatus.initial()) BaseStatus status,<br>  }) = _UserState;<br>}</pre><p>The Cubit produces each successive state as a prototype of the one before it:</p><pre>Future&lt;void&gt; getUserList() async {<br>  emit(state.copyWith(status: const BaseStatus.loading()));<br>  try {<br>    final userList = await _getUserListUseCase.execute();<br>    emit(state.copyWith(userList: userList, status: const BaseStatus.success()));<br>  } catch (e) {<br>    emit(state.copyWith(status: BaseStatus.failure(ResponseError.from(e))));<br>  }<br>}</pre><p>Every state.copyWith(...) clones the existing state, overriding only the fields that changed and carrying everything else forward untouched. This is Prototype applied to immutable data: it&#39;s cheaper than rebuilding the whole object by hand, and it&#39;s <em>safe</em> — you physically cannot forget to copy a field, because the generated copyWith copies them all by default.</p><p>Compare that to the manual alternative, where you’d rebuild the entire object every time:</p><pre>// Without copyWith: verbose, and easy to drop a field during a refactor.<br>emit(UserState(userList: state.userList, status: const BaseStatus.loading()));</pre><p>Add a third field to UserState and this manual version silently breaks at every call site. copyWith never does.</p><h3>The takeaway</h3><p>In an immutable, unidirectional-data-flow app, copyWith is the Prototype pattern. Reach for it any time you need &quot;the same object, but with X changed&quot; — which, in state management, is constantly.</p><h3>How the patterns compose</h3><p>Here’s the part the toy examples never show you: in real code these patterns don’t compete, they stack. Trace a single login request through the template and you touch all five:</p><ol><li>The Abstract Factory (DataSourceFactory) is registered as a Singleton in the DI container, so there&#39;s exactly one of it.</li><li><em>Which</em> concrete factory gets registered is decided by a Factory Method in a @module provider, gated by the current environment.</li><li>The Dio clients that the real data sources depend on are assembled by a Builder.</li><li>And the UI state that the whole chain ultimately feeds is evolved through the Prototype pattern, via copyWith.</li></ol><p>That’s the real lesson. Design patterns aren’t rival techniques you choose between — they’re a shared vocabulary for structuring object creation so your code stays flexible as requirements shift. Because these patterns are in place, swapping a mock backend for a real one, adding a new build flavor, or changing a network timeout each become a <em>local</em> edit instead of a codebase-wide refactor.</p><p>That flexibility is the whole return on investment. Patterns aren’t decoration; they’re what lets a codebase absorb change without fracturing.</p><h3>Explore (and star) the full project</h3><p>Everything in this article comes from a real, MIT-licensed template you can use as the foundation for your own apps. Beyond the patterns covered here, it ships with:</p><ul><li>Clean Architecture layering (domain / data / presentation / core)</li><li>Multi-flavor builds (development / staging / production)</li><li>Dependency injection with get_it + injectable</li><li>Retrofit-based networking with a mockable data-source layer</li><li>BLoC/Cubit state management with sealed states and typed errors</li><li>Localization, code-gen scaffolding scripts, and a full test suite</li></ul><p>⭐ <a href="https://github.com/hadiuzzaman524/flutter-clean-architecture">github.com/hadiuzzaman524/flutter-clean-architecture</a></p><p>If this walkthrough made the patterns finally click, drop the repo a star — and if you spot a pattern worth adding to the tour, open an issue or a PR. The best way to learn a pattern is to read it in code that actually runs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a32c3bafc5ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Client-Side Rate Limiting in Mobile Apps: Throttling & Debouncing in Flutter and Kotlin]]></title>
            <link>https://md-hadi.medium.com/mastering-client-side-rate-limiting-in-mobile-apps-throttling-debouncing-in-flutter-and-kotlin-42bc15ef079d?source=rss-3e2e8c53b23b------2</link>
            <guid isPermaLink="false">https://medium.com/p/42bc15ef079d</guid>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[mobile-engineering]]></category>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Hadiuzzaman]]></dc:creator>
            <pubDate>Thu, 09 Jul 2026 04:14:53 GMT</pubDate>
            <atom:updated>2026-07-09T04:14:53.837Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WvdFaY4PpZ7h2R8i8hxDTw.png" /></figure><p>Every mobile developer loves a fast, responsive app. We spend days optimizing our backend APIs and database queries. But what happens when the issue isn’t the backend? What if the app itself is spamming the server with unnecessary requests?</p><p>Imagine a user furiously tapping a “Submit” button on a slow network, or a search bar that hits your API on <em>every single keystroke</em>. Your backend gets overwhelmed, resources spike, and eventually, the server throws a <strong>429 Too Many Requests</strong> error.</p><p>While server-side rate limiting is crucial, <strong>Client-Side Rate Limiting</strong> is your first line of defense. By making decisions right on the mobile end before firing an API call, you save server resources, reduce user data consumption, and prevent UI jank.</p><p>In this post, we’ll explore two powerful techniques to handle this in <strong>Flutter</strong> and <strong>Native Android (Kotlin)</strong>: <strong>Throttling</strong> and <strong>Debouncing</strong>.</p><h3>1. Debouncing vs. Throttling: What’s the Difference?</h3><p>Before jumping into the code, let’s clear up the confusion between these two terms. They both control execution frequency, but their behaviors are fundamentally different.</p><ul><li><strong>Debouncing:</strong> Waits for a pause. It delays the API execution until the user <em>stops</em> doing an action for a specific period. If a new event occurs before the timer finishes, the timer resets.</li><li><em>Best Use Case:</em> Search auto-suggestions.</li><li><strong>Throttling:</strong> Enforces a maximum frequency. It allows the first API call immediately but blocks subsequent calls for a fixed time window, regardless of how many times the user interacts.</li><li><em>Best Use Case:</em> “Like” buttons, “Refresh” buttons, or form submissions.</li></ul><h3>2. Implementing Debouncing (The Search Box Savior)</h3><h3>💙 In Flutter (Dart)</h3><p>In Flutter, we can create a lightweight, reusable Debouncer class using standard Timer APIs.</p><p>Dart</p><pre>import &#39;dart:async&#39;;<br><br>class Debouncer {<br>  final Duration delay;<br>  Timer? _timer;<br>  Debouncer({required this.delay});<br>  void run(void Function() action) {<br>    // Cancel the ongoing timer if the user acts again<br>    _timer?.cancel(); <br>    <br>    // Restart the countdown<br>    _timer = Timer(delay, action);<br>  }<br>}<br>// How to use it inside a Search TextField:<br>final _debouncer = Debouncer(delay: Duration(milliseconds: 500));<br>void onSearchTextChanged(String text) {<br>  _debouncer.run(() {<br>    // This executes ONLY when the user stops typing for 500ms<br>    apiService.searchProducts(text);<br>  });<br>}</pre><h3>💜 In Native Android (Kotlin)</h3><p>For Kotlin, utilizing <strong>Coroutines</strong> and <strong>Jobs</strong> is the cleanest way to implement a structured debouncer that ties nicely into your UI lifecycle.</p><p>Kotlin</p><pre>import kotlinx.coroutines.*<br><br>class Debouncer(private val delayMillis: Long) {<br>    private var debounceJob: Job? = null<br>    private val coroutineScope = CoroutineScope(Dispatchers.Main)<br>    fun run(action: () -&gt; Unit) {<br>        // Cancel the previous job before starting a new countdown<br>        debounceJob?.cancel()<br>        <br>        debounceJob = coroutineScope.launch {<br>            delay(delayMillis)<br>            action()<br>        }<br>    }<br>}<br>// How to use it in your Fragment/Activity:<br>val searchDebouncer = Debouncer(delayMillis = 500)<br>searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {<br>    override fun onQueryTextChange(newText: String?): Boolean {<br>        newText?.let { query -&gt;<br>            searchDebouncer.run { apiService.fetchResults(query) }<br>        }<br>        return true<br>    }<br>    // ...<br>})</pre><h3>3. Implementing Throttling (The Double-Tap Preventer)</h3><h3>💙 In Flutter (Dart)</h3><p>Throttling keeps track of the exact time an action was last executed. If the elapsed time is less than the specified duration, it gracefully discards the execution request.</p><p>Dart</p><pre>class Throttler {<br>  final Duration delay;<br>  DateTime? _lastRun;<br><br>Throttler({required this.delay});<br>  void run(void Function() action) {<br>    final now = DateTime.now();<br>    <br>    if (_lastRun == null || now.difference(_lastRun!) &gt; delay) {<br>      _lastRun = now;<br>      action();<br>    } else {<br>      print(&quot;Request throttled! Please wait.&quot;);<br>    }<br>  }<br>}<br>// Usage on a Submit/Refresh Button:<br>final Throttler _throttler = Throttler(delay: Duration(seconds: 3));<br>void onSaveButtonPressed() {<br>  _throttler.run(() {<br>    apiService.uploadData();<br>  });<br>}</pre><h3>💜 In Native Android (Kotlin)</h3><p>In Native Android, we can track the system uptime using SystemClock.elapsedRealtime() to prevent intervals shorter than our threshold.</p><p>Kotlin</p><pre>import android.os.SystemClock<br><br>object ApiThrottler {<br>    private var lastClickTime: Long = 0<br>    private const val MIN_INTERVAL = 3000 // 3 seconds<br>    fun shouldAllowApiCall(): Boolean {<br>        val currentTime = SystemClock.elapsedRealtime()<br>        if (currentTime - lastClickTime &lt; MIN_INTERVAL) {<br>            return false // Reject the call<br>        }<br>        lastClickTime = currentTime<br>        return true // Allow the call<br>    }<br>}<br>// Usage inside an OnClickListener:<br>btnSubmit.setOnClickListener {<br>    if (ApiThrottler.shouldAllowApiCall()) {<br>        viewModel.submitForm()<br>    } else {<br>        showToast(&quot;You&#39;re clicking too fast! Please wait.&quot;)<br>    }<br>}</pre><h3>Going Advanced: Client-Side Token Bucket</h3><p>If you have a complex scenario where you want to allow a burst of requests (e.g., <em>max 5 API calls per minute in any order, blocking the 6th</em>), you can implement a local <strong>Token Bucket algorithm</strong>.</p><p>By storing a rolling list of timestamps in your local key-value store (SharedPreferences for Android / Hive or Shared Preferences for Flutter), you can clear out timestamps older than 60 seconds, check the list size, and decide right away if the app should fire the next API call or show a countdown timer to the user.</p><h3>Conclusion</h3><p>Handling rate limits entirely on the backend is reactive; handling it on the mobile client is <strong>proactive</strong>. By leveraging Debouncing and Throttling, you drastically cut down redundant network overhead, gracefully manage API quotas, and protect your architecture from unintentional self-inflicted DOS attacks.</p><p>How do you handle rapid user interactions in your mobile apps? Do you prefer a custom wrapper or Reactive Extensions (RxDart / Flow)? Let’s discuss in the comments below! 🚀</p><h3>Explore more and contact me</h3><p>Thank you for reading! If you found this guide useful, consider exploring more of my content or connecting with me online:</p><ul><li><strong>Connect on LinkedIn</strong><br>🔗 <a href="https://www.linkedin.com/in/md-hadi/">LinkedIn Profile</a></li><li><strong>Explore My Projects on GitHub</strong><br>🔗 <a href="https://github.com/hadiuzzaman524">GitHub Profile</a></li><li>💼 <strong>Available for Freelance Work</strong><br>I’m open to freelance projects in <strong>mobile app development, TV app development </strong>and <strong>machine learning &amp; AI</strong>. Feel free to reach out!</li></ul><p>Feel free to reach out or follow me for more content on AI, software development, and tech insights! Happy coding! 🚀</p><p>#MobileDevelopment #Flutter #Kotlin #AndroidDev #SoftwareArchitecture #CleanCode</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42bc15ef079d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Applying SOLID Principles in Python: A Practical ETL Project Walkthrough]]></title>
            <link>https://md-hadi.medium.com/applying-solid-principles-in-python-a-practical-etl-project-walkthrough-f6b99193ace5?source=rss-3e2e8c53b23b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6b99193ace5</guid>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Hadiuzzaman]]></dc:creator>
            <pubDate>Tue, 22 Jul 2025 03:25:24 GMT</pubDate>
            <atom:updated>2025-07-22T03:25:24.681Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pufjf35Ul3x6OBvO8-qGxg.png" /></figure><blockquote><em>💬 </em>“Code is like a city. Build without rules, and one day it’ll collapse.”</blockquote><p>Imagine you’re working on a data engineering team at a mid-size tech company. Your team is responsible for handling a large number of CSV reports from multiple vendors daily. These reports need to be extracted, transformed, and loaded (ETL) into your analytics database so that business analysts can generate insights. One day, you get a task: “Make our ETL system cleaner, more extensible, and easier to maintain.”</p><p>You glance at the existing codebase and sigh. It’s a monolith. Let’s walk through how we refactor this system using <strong>SOLID principles</strong>, and how each principle helps us untangle the mess — one step at a time.</p><h3>🧩 S — Single Responsibility Principle (SRP)</h3><blockquote><strong><em>Each class should have one, and only one, reason to change.</em></strong></blockquote><h3>❌ The Problem</h3><p>Your current ETL class looks something like this:</p><pre>class ETLProcessor:<br>    def extract(self):<br>        # Connect to S3, read CSV<br>        pass<br>    def transform(self, data):<br>        # Clean, filter, enrich<br>        pass<br>    def load(self, data):<br>        # Insert into database<br>        pass</pre><p>These are three different responsibilities:</p><ul><li>Connecting to data sources (<strong>extract</strong>)</li><li>Cleaning and transforming data (<strong>transform</strong>)</li><li>Inserting into the database (<strong>load</strong>)</li></ul><p>Sure, your current code might look simple. But tomorrow your boss asks you to support XML files. The next day, it’s Google Sheets. You quickly realize that any change to any part of the process means modifying this one big class — even if the transform and load logic are untouched.</p><p>If the extraction logic changes, the whole ETL class has to be modified, violating the idea of separation of concerns.</p><h3>✅ The SRP Solution</h3><p>Let’s break responsibilities apart.</p><pre>class Extractor:<br>    def extract(self, file_path):<br>        print(f&quot;Extracting data from {file_path}&quot;)<br>        return [{&quot;name&quot;: &quot;Alice&quot;, &quot;age&quot;: 30}, {&quot;name&quot;: &quot;Bob&quot;, &quot;age&quot;: 25}]<br><br>class Transformer:<br>    def transform(self, data):<br>        print(&quot;Transforming data&quot;)<br>        return [d for d in data if d[&quot;age&quot;] &gt; 26]<br><br>class Loader:<br>    def load(self, data):<br>        print(f&quot;Loading data: {data}&quot;)<br><br></pre><p>Then use a coordinator class:</p><pre>class ETLProcessor:<br>    def __init__(self, extractor, transformer, loader):<br>        self.extractor = extractor<br>        self.transformer = transformer<br>        self.loader = loader<br><br>    def run(self, file_path):<br>        data = self.extractor.extract(file_path)<br>        transformed = self.transformer.transform(data)<br>        self.loader.load(transformed)</pre><p><strong>Now:</strong></p><ul><li>Changing the file type? Modify or create another extractor.</li><li>Updating transformation logic? Just update Transformer.</li><li>Switching DBs? Update DatabaseLoader.</li></ul><p>Our original ETLProcessor was like a Swiss Army knife. Useful, but clunky. With SRP, we turned it into a precision toolkit.</p><h3>🧭 O — Open/Closed Principle (OCP)</h3><blockquote><strong><em>Software entities should be open for extension, but closed for modification.</em></strong></blockquote><h3>❌ The Problem</h3><p>Let’s say you now support both CSV and XML files. You added logic in the same method:</p><pre>class Extractor:<br>    def extract(self, file_path):<br>        if file_path.endswith(&#39;.csv&#39;):<br>            return self._read_csv(file_path)<br>        elif file_path.endswith(&#39;.xml&#39;):<br>            return self._read_xml(file_path)<br>        # more elifs coming</pre><p>This is brittle. Every new format breaks the old code and adds more branches.</p><h3>✅ The OCP Solution</h3><p>Use inheritance or composition to make the base class extendable.</p><pre>class Extractor:<br>    def extract(self, file_path):<br>        raise NotImplementedError<br><br>class CSVExtractor(Extractor):<br>    def extract(self, file_path):<br>        # parse CSV<br>        pass<br><br>class XMLExtractor(Extractor):<br>    def extract(self, file_path):<br>        # parse XML<br>        pass<br><br># Usage<br>extractors = [CSVExtractor(), XMLExtractor()]<br>for extractor in extractors:<br>    if extractor.can_handle(file_path):<br>        data = extractor.extract(file_path)</pre><p>Now, adding support for Google Sheets? Just implement a new GoogleSheetExtractor.</p><p>We once had a gatekeeper class that judged all file types. Now we have a welcoming committee of experts, each handling their specialty.</p><h3>🤝 L — Liskov Substitution Principle (LSP)</h3><blockquote><strong><em>Objects of a superclass should be replaceable with objects of its subclasses without breaking the application.</em></strong></blockquote><p>We want to test our ETLProcessor class without actually hitting the disk or fetching real data. That means we want to use a mock version of our extractor.</p><p>Suppose we had something like this:</p><pre>class CSVExtractor:<br>    def extract(self, file_path):<br>        with open(file_path, &#39;r&#39;) as f:<br>            return f.read()</pre><p>Here’s our ETL runner:</p><pre>class ETLProcessor:<br>    def run(self, extractor):<br>        data = extractor.extract(&#39;data.csv&#39;)<br>        print(&quot;Extracted data:&quot;, data)</pre><p>Now let’s try to test this:</p><pre>class MockExtractor:<br>    def extract(self, file_path):<br>        return { &#39;data&#39;: &#39;test&#39; }<br><br>etl = ETLProcessor()<br>etl.run(MockExtractor())</pre><p>Looks okay, right? But what if our real extractor used an interface like this:</p><pre>class Extractor:<br>    def extract(self, file_path: str) -&gt; dict:<br>        raise NotImplementedError</pre><p>And suddenly our MockExtractor doesn’t inherit from it? Then it&#39;s not a valid substitute, and the design breaks.</p><h4>✅ The Solution: Enforce LSP with Abstract Base Classes</h4><p>We fix this by ensuring that all extractors, including mocks, inherit from the same interface. Here’s how we refactor it properly:</p><pre>from abc import ABC, abstractmethod<br><br>class Extractor(ABC):<br>    @abstractmethod<br>    def extract(self, file_path: str) -&gt; dict:<br>        pass</pre><p>Real extractor:</p><pre>class CSVExtractor(Extractor):<br>    def extract(self, file_path: str) -&gt; dict:<br>        with open(file_path, &#39;r&#39;) as f:<br>            data = f.read()<br>        return { &#39;data&#39;: data }</pre><p>Mock extractor:</p><pre>class MockExtractor(Extractor):<br>    def extract(self, file_path: str) -&gt; dict:<br>        return { &#39;data&#39;: &#39;test&#39; }</pre><p>And now the ETL processor, implemented with the interface in mind:</p><pre>class ETLProcessor:<br>    def __init__(self):<br>        pass<br>  <br>    def run(self, extractor: Extractor):<br>        data = extractor.extract(&#39;data.csv&#39;)<br>        print(&quot;Extracted data:&quot;, data)</pre><p>Now both the CSVExtractor and MockExtractor are true subclasses of Extractor, and they can be used interchangeably without breaking the ETLProcessor. This is LSP in action!</p><p>Think of your ETL system as a plug-and-play machine. If the new plug doesn’t fit the socket, it’s a violation of LSP. Fixing the contract makes all plugs compatible.</p><h3>🔌 I — Interface Segregation Principle (ISP)</h3><blockquote><strong><em>Clients should not be forced to depend on interfaces they do not use.</em></strong></blockquote><h3>❌ The Problem: A Bloated ETL Interface</h3><p>Let’s say your ETL system is growing. You started with a small interface like this:</p><pre>class ETLInterface:<br>    def extract(self): pass<br>    def transform(self): pass<br>    def load(self): pass<br>    def notify(self): pass  # newly added</pre><p>Now imagine you have two types of ETL tasks:</p><ul><li>A regular FileETLJob that extracts, transforms, and loads CSV data.</li><li>A RealTimeETLJob that does extract, transform, and notify a dashboard (but doesn’t load into a DB).</li></ul><p>Let’s implement both using this fat interface:</p><pre>class FileETLJob(ETLInterface):<br>    def extract(self):<br>        print(&quot;Extracting data from CSV&quot;)<br>    <br>    def transform(self):<br>            print(&quot;Transforming CSV data&quot;)<br><br>    def load(self):<br>        print(&quot;Loading data into DB&quot;)<br><br>    def notify(self):<br>        pass  # not needed, but required</pre><pre>class RealTimeETLJob(ETLInterface):<br>    def extract(self):<br>        print(&quot;Extracting data from Kafka&quot;)<br><br>    def transform(self):<br>            print(&quot;Transforming real-time data&quot;)<br><br>    def load(self):<br>        pass  # not needed<br><br>    def notify(self):<br>        print(&quot;Notifying dashboard&quot;)</pre><h3>😫 The Issue</h3><p>Both classes are now forced to implement <strong>methods they don’t need</strong>. FileETLJob has to stub notify(), and RealTimeETLJob has to stub load(). This bloats your codebase, confuses intent, and increases maintenance cost. This is a classic <strong>violation of ISP</strong>.</p><h3>✅ The Solution: Segregate Interfaces</h3><p>Break down the ETLInterface into <strong>smaller, more specific interfaces</strong>:</p><pre>class Extractable:<br>    def extract(self): pass<br><br>class Transformable:<br>    def transform(self): pass<br><br>class Loadable:<br>    def load(self): pass<br><br>class Notifiable:<br>    def notify(self): pass<br></pre><p>Now, each job implements <strong>only what it needs</strong>:</p><pre>class FileETLJob(Extractable, Transformable, Loadable):<br>    def extract(self):<br>        print(&quot;Extracting data from CSV&quot;)<br><br>    def transform(self):<br>            print(&quot;Transforming CSV data&quot;)<br><br>    def load(self):<br>        print(&quot;Loading data into DB&quot;)<br></pre><pre>class RealTimeETLJob(Extractable, Transformable, Notifiable):<br>    def extract(self):<br>        print(&quot;Extracting data from Kafka&quot;)<br><br>    def transform(self):<br>            print(&quot;Transforming real-time data&quot;)<br><br>    def notify(self):<br>        print(&quot;Notifying dashboard&quot;)</pre><p>Your ETLProcessor can now be more flexible:</p><pre>class ETLProcessor:<br><br>    def run(self, job):<br>        job.extract()<br>        job.transform()<br><br>        if isinstance(job, Loadable):<br>            job.load()<br><br>        if isinstance(job, Notifiable):<br>            job.notify()</pre><h3>✅ Now You’re ISP-Compliant!</h3><p>You can plug in any new job type — maybe a DataArchivalJob that only extracts and loads — without having to fake unused behavior. This structure also helps your testing.</p><pre>class MockKafkaJob(Extractable, Transformable, Notifiable):<br>    def extract(self): print(&quot;Mock extract&quot;)<br>    def transform(self): print(&quot;Mock transform&quot;)<br>    def notify(self): print(&quot;Mock notify&quot;)<br><br>etl = ETLProcessor()<br>etl.run(MockKafkaJob())</pre><p>No test stubs. No fake methods. Just clean responsibilities.</p><p>Imagine asking your chef to also clean the bathrooms and manage accounts. ISP helps everyone stick to their strengths.</p><h3>🧱 D — Dependency Inversion Principle (DIP)</h3><blockquote><em>High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details. Details should depend on abstractions.</em></blockquote><p>Your ETL pipeline is growing, and now management wants an email notification whenever the job finishes — either success or failure.</p><p>So you hastily wire an email system inside the ETL class:</p><pre>class ETLProcessor:<br>    def __init__(self):<br>        self.extractor = CSVExtractor()<br>        self.transformer = BasicTransformer()<br>        self.loader = DatabaseLoader()<br>        self.notifier = EmailNotifier()  # 💥 Hard dependency!<br><br>    def run(self, file_path):<br>        data = self.extractor.extract(file_path)<br>        transformed = self.transformer.transform(data)<br>        self.loader.load(transformed)<br>        self.notifier.notify(&quot;ETL job completed.&quot;)  # Directly used</pre><p>This works… until one day you need to switch from email to Slack notifications — or worse, send <strong>both</strong>. The tight coupling of EmailNotifier into your ETLProcessor means:</p><ul><li>You must change and retest ETLProcessor for every notifier change.</li><li>You violate the <strong>Open/Closed Principle</strong> too.</li><li>Your system is fragile, hard to scale, and harder to test.</li></ul><h3>✅ The DIP Solution: Depend on Abstractions</h3><p>Let’s fix this by inverting the dependency: ETLProcessor should rely on a <strong>Notifier interface</strong>, not a specific implementation.</p><p>Define the abstraction:</p><pre>class Notifier:<br>    def notify(self, message: str):<br>        pass</pre><p>Implement concrete classes:</p><pre>class EmailNotifier(Notifier):<br>    def notify(self, message: str):<br>        print(f&quot;Sending Email: {message}&quot;)<br><br>class SlackNotifier(Notifier):<br>    def notify(self, message: str):<br>        print(f&quot;Sending Slack Message: {message}&quot;)</pre><p>Update the ETLProcessor to depend on abstraction:</p><pre>class ETLProcessor:<br>    def __init__(self, extractor, transformer, loader, notifier: Notifier):<br>        self.extractor = extractor<br>        self.transformer = transformer<br>        self.loader = loader<br>        self.notifier = notifier<br><br>    def run(self, file_path):<br>        data = self.extractor.extract(file_path)<br>        transformed = self.transformer.transform(data)<br>        self.loader.load(transformed)<br>        self.notifier.notify(&quot;ETL job completed.&quot;)</pre><p>Use it like this:</p><pre>etl = ETLProcessor(<br>    extractor=CSVExtractor(),<br>    transformer=BasicTransformer(),<br>    loader=DatabaseLoader(),<br>    notifier=EmailNotifier()  # You can switch to SlackNotifier anytime!<br>)<br>etl.run(&quot;data.csv&quot;)</pre><ul><li>Want to switch to SMSNotifier? Just pass it in, no code change in ETLProcessor.</li><li>Writing unit tests? Use MockNotifier to verify calls without sending real messages.</li><li>Need multiple notifications? Inject a CompositeNotifier that calls many. Example:</li></ul><pre>class CompositeNotifier(Notifier):<br>    def __init__(self, notifiers):<br>        self.notifiers = notifiers<br><br>    def notify(self, message: str):<br>        for notifier in self.notifiers:<br>            notifier.notify(message)<br><br>etl = ETLProcessor(<br>    extractor=CSVExtractor(),<br>    transformer=BasicTransformer(),<br>    loader=DatabaseLoader(),<br>    notifier=CompositeNotifier([EmailNotifier(), SlackNotifier()])<br>)<br>etl.run(&quot;data.csv&quot;)</pre><p>The <strong>Dependency Inversion Principle</strong> helps you <strong>decouple policy from implementation</strong>, making your ETL engine:</p><ul><li>Highly modular</li><li>Swappable in behavior</li><li>Test-friendly</li><li>Future-proof</li></ul><p>Rather than hardcoding your team members into your calendar, DIP lets you invite whoever is best for the job.</p><h3>🧠 SOLID ETL, Solid Mind</h3><p>Before SOLID, your ETL looked like a single spaghetti file that needed editing every time something changed. After SOLID:</p><ul><li>You can test in isolation.</li><li>You can add support for new formats without touching core logic.</li><li>You can maintain and scale with confidence.</li></ul><p>Like a master chef setting up stations in the kitchen, each part of your ETL does one thing well and plays nicely with others.</p><p><strong>Next Steps:</strong></p><ul><li>Add logging and monitoring.</li><li>Add unit tests for each module.</li><li>Use a DI framework (like dependency_injector) for even more flexibility.</li></ul><h3>Explore more and contact me</h3><p>Thank you for reading! If you found this guide useful, consider exploring more of my content or connecting with me online:</p><ul><li><strong>Connect on LinkedIn</strong><br>🔗 <a href="https://www.linkedin.com/in/md-hadi/">LinkedIn Profile</a></li><li><strong>Explore My Projects on GitHub</strong><br>🔗 <a href="https://github.com/hadiuzzaman524">GitHub Profile</a></li><li>💼 <strong>Available for Freelance Work</strong><br>I’m open to freelance projects in <strong>mobile app development</strong> and <strong>machine learning &amp; AI</strong>. Feel free to reach out!</li></ul><p>Feel free to reach out or follow me for more content on AI, software development, and tech insights! Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6b99193ace5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Software Is Changing (Again): What Andrej Karpathy’s Keynote Means for the Future of Programming]]></title>
            <link>https://md-hadi.medium.com/software-is-changing-again-what-andrej-karpathys-keynote-means-for-the-future-of-programming-46a834d913cb?source=rss-3e2e8c53b23b------2</link>
            <guid isPermaLink="false">https://medium.com/p/46a834d913cb</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-3]]></category>
            <category><![CDATA[llm-applications]]></category>
            <dc:creator><![CDATA[Hadiuzzaman]]></dc:creator>
            <pubDate>Sat, 28 Jun 2025 17:37:03 GMT</pubDate>
            <atom:updated>2025-06-28T17:37:03.949Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Owsj1cEyB94HDBznpRxgvg.png" /></figure><blockquote><em>“The hottest new programming language is English.” — Andrej Karpathy</em></blockquote><p>At Y Combinator’s AI Startup School on June 17, 2025, <strong>Andrej Karpathy</strong> (founding member of OpenAI, ex-Director of AI at Tesla) took the stage to deliver a keynote that wasn’t just insightful — it was a reality check for everyone building in tech today.</p><p>His message? <strong>Software is evolving again</strong>. And we’re at the very beginning of a new era he calls <strong>Software 3.0</strong>.</p><p>The full episode: <a href="https://www.youtube.com/watch?v=LCEmiRjPEtQ">https://www.youtube.com/watch?v=LCEmiRjPEtQ</a></p><p>Let’s unpack what that means and why it matters to builders like you.</p><h3>🧬 From Code to Prompts: The Evolution of Software</h3><p>Karpathy frames the history of software in three major epochs:</p><h3>Software 1.0</h3><p>This is the traditional way we’ve written code — think C++, Java, Python. Humans explicitly wrote logic line by line. Everything was deterministic and rule-based. Still, most of the world’s software runs on this model today.</p><h3>Software 2.0</h3><p>Enter machine learning. With Software 2.0, we began programming with <strong>data</strong> instead of code. Neural networks became the new engines, learning patterns instead of being hand-coded.</p><h3>Software 3.0 (Today)</h3><p>Here’s where it gets interesting. We now write software using <strong>natural language</strong> prompts. Thanks to powerful LLMs (like GPT-4 or Claude 3), we describe what we want, and the AI translates that into working programs.</p><p>This is more than just a Copilot plugin or an autocomplete tool — it’s a fundamental rethinking of what programming is.</p><h3>🖥️ LLMs Are the New Operating Systems</h3><p>Karpathy uses an analogy to explain the infrastructure shift:</p><ul><li><strong>LLMs are like shared compute utilities</strong>, similar to electricity.</li><li><strong>Model labs (like OpenAI or Anthropic)</strong> are the new “fabs” producing state-of-the-art models.</li><li><strong>Prompt-driven systems</strong> are becoming the new operating layers — your OS is now a language model.</li></ul><p>This mirrors the 1960s mainframe era: shared compute, centralized intelligence, and batch jobs — except now it’s all happening via natural language and scale is global.</p><h3>🎯 Intelligence Is Jagged (And That’s Okay)</h3><p>A central idea in the talk is that today’s LLMs are not general-purpose AGI. They’re <strong>incredibly capable in some areas and bafflingly poor in others</strong>. Karpathy calls this <strong>“jagged intelligence.”</strong></p><p>For example:</p><ul><li>An LLM might write a parser for a file format with perfect syntax…</li><li>…but still get a basic math equation wrong.</li></ul><p>As builders, we must accept and <strong>design around the imperfections</strong>. That means:</p><ul><li>Keeping humans in the loop</li><li>Validating outputs</li><li>Creating tight feedback cycles</li></ul><p>In other words, <strong>treat LLMs as semi-autonomous assistants</strong>, not infallible agents.</p><h3>✨ Vibe Coding: The New Paradigm</h3><p>Karpathy shows a demo of a project called <strong>MenuGen</strong>, where an entire app UI is created through prompts. This is what he calls <strong>“vibe coding”</strong> — you describe what you want, and the AI takes a stab at generating it.</p><p>It’s powerful. But it’s also a reminder that:</p><blockquote><strong><em>Demos are not products.</em></strong></blockquote><p>Real-world apps need:</p><ul><li>Robust edge-case handling</li><li>Clean architecture</li><li>Repeatable behavior</li></ul><p>The takeaway? Use LLMs to <strong>accelerate prototyping</strong>, not skip engineering discipline.</p><h3>🤖 Designing for Agents, Not Just Users</h3><p>This is where the future gets even more interesting.</p><p>Just as we used to design interfaces for humans (GUIs), and later for developers (APIs), <strong>the next wave will involve designing interfaces for AI agents</strong>.</p><p>Karpathy points out the rise of:</p><ul><li>llms.txt — machine-readable docs tailored for agents</li><li>Tools like GitIngest and DeepWiki — giving agents structured, explorable knowledge</li></ul><p>We’re not just building for users anymore. We’re <strong>building for bots</strong>, too.</p><h3>🚀 What Should You Do Now?</h3><p>If you’re a developer, founder, or product lead, here’s your Software 3.0 playbook:</p><p>✅ <strong>Start prompt-designing</strong>: Learn how to “talk” to LLMs effectively.</p><p>✅ <strong>Instrument your code</strong>: Add guardrails, validations, and feedback loops for LLM outputs.</p><p>✅ <strong>Build agent-first systems</strong>: Design your APIs and docs to be friendly to both humans and AI.</p><p>✅ <strong>Rethink architecture</strong>: LLMs are not just plugins — they might be part of your core stack in the next few years.</p><h3>💡 Final Thoughts: The Interface Has Changed</h3><p>The biggest shift Karpathy highlights isn’t the model size, or even the performance — it’s the <strong>interface</strong>.</p><p>We’re no longer telling machines <em>how</em> to do things.</p><p>We’re telling them <em>what</em> we want done.</p><p>This new paradigm of software development opens massive opportunities — but only for those who understand and adapt.</p><p>So if you’re still thinking like a Software 1.0 or 2.0 engineer, it’s time to evolve.</p><blockquote><em>Because in Software 3.0, English is the new Python.</em></blockquote><p><strong>What’s next?</strong><br> Want a breakdown of how to integrate LLMs into your product pipeline or set up agent-aware design systems?</p><h3>Explore more and contact me</h3><p>Thank you for reading! If you found this guide useful, consider exploring more of my content or connecting with me online:</p><ul><li><strong>Connect on LinkedIn</strong><br>🔗 <a href="https://www.linkedin.com/in/md-hadi/">LinkedIn Profile</a></li><li><strong>Explore My Projects on GitHub</strong><br>🔗 <a href="https://github.com/hadiuzzaman524">GitHub Profile</a></li><li>💼 <strong>Available for Freelance Work</strong><br>I’m open to freelance projects in <strong>mobile app development</strong> and <strong>machine learning &amp; AI</strong>. Feel free to reach out!</li></ul><p>Feel free to reach out or follow me for more content on AI, software development, and tech insights! Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46a834d913cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering RAG: Build Smarter AI with LangChain and LangGraph in 2025]]></title>
            <link>https://md-hadi.medium.com/mastering-rag-build-smarter-ai-with-langchain-and-langgraph-in-2025-cc126fb8a552?source=rss-3e2e8c53b23b------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc126fb8a552</guid>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Hadiuzzaman]]></dc:creator>
            <pubDate>Wed, 02 Apr 2025 05:13:36 GMT</pubDate>
            <atom:updated>2025-04-02T23:11:13.791Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qy6lhQKG-jl1d_5qos0j2w.png" /></figure><h3>Introduction</h3><p>Have you ever asked an AI a question only to get an outdated or vague response? I’ve been there — frustrated with chatbots that can’t keep up with 2025’s fast-paced world. That’s when I discovered Retrieval-Augmented Generation (RAG), a game-changing approach that blends real-time data retrieval with advanced language generation. In this guide, I’ll walk you through how I built a RAG system using LangChain and LangGraph, transforming my AI from clueless to cutting-edge. Whether you’re a developer or simply curious about AI, you’ll learn why RAG is a must-know technique in 2025 — and how you can build one yourself.</p><p>RAG isn’t just a buzzword; it’s a lifeline for achieving accuracy in AI. Traditional language models rely on static, pre-trained knowledge, but RAG fetches fresh information from external sources, making it perfect for today’s dynamic information landscape. Let’s dive into what makes it tick and how you can harness its power with tools like LangChain and LangGraph.</p><h3>What is RAG?</h3><p>Imagine asking a company’s HR chatbot, “How many vacation days do I have left?” With RAG, the chatbot doesn’t simply guess — it retrieves your organization’s latest leave policy and crafts a precise answer. That’s the essence of Retrieval-Augmented Generation: pairing a <strong>Retriever</strong> (which searches a knowledge base) with a <strong>Generator</strong> (an LLM that crafts responses). The result? Answers that are accurate, up-to-date, and rich in context.</p><p>Of course, RAG isn’t without its challenges. For example, if an AI misinterprets a document or retrieves outdated information, it might generate inaccurate responses. However, the benefits generally outweigh these risks:</p><ul><li><strong>Accuracy:</strong> Fresh, domain-specific data is far superior to relying solely on static training sets.</li><li><strong>Flexibility:</strong> There’s no need for retraining — simply update your knowledge base.</li><li><strong>Relevance:</strong> Perfect for niche topics, real-time updates, or breaking news.</li></ul><p>In 2025, RAG is evolving rapidly. Innovations like <strong>Long RAG</strong> (capable of handling 25,000+ tokens) and <strong>Adaptive RAG</strong> (which learns from user feedback) are pushing the boundaries, making it a hot topic among AI practitioners.</p><h3>Why LangChain and LangGraph?</h3><p>So why choose LangChain and LangGraph over alternatives like Haystack? LangChain simplifies the integration of LLMs with external data — be it documents, APIs, or databases — using an intuitive framework. LangGraph, on the other hand, orchestrates complex workflows (think cyclic agent behaviors) that modern AI demands. I chose these tools because they’re both beginner-friendly and powerful enough for seasoned developers, offering a gentler learning curve compared to some alternatives.</p><p>LangChain handles the heavy lifting of data retrieval, while LangGraph structures the process — much like a conductor guiding an orchestra. Together, they form a robust foundation for building reliable and scalable RAG systems. They’re also keeping pace with 2025’s trends by integrating with debugging tools like LangSmith.</p><h3>Choosing the Right LLM</h3><p>The heart of your RAG system is its language model. In 2025, while GPT-4 feels a bit dated, newer options are already making waves. Here are my top picks (inspired by Fuel Your Digital, 2025):</p><ul><li><strong>OpenAI’s GPT-5 with RAG Mode:</strong> Exceptionally accurate and customizable, albeit at a premium price.</li><li><strong>Google’s Gemini AI:</strong> Offers real-time web access for fresh context, though privacy remains a concern.</li><li><strong>Anthropic’s Claude 3.5:</strong> Known for its simplicity and collaborative nature, but less adept at real-time data integration.</li></ul><p>For my build, I opted for GPT-5 because its RAG Mode significantly boosts retrieval precision — just keep in mind that it comes with a higher price tag. Your choice should be guided by your budget and specific use case, so testing multiple models might be the best approach.</p><h3>Step-by-Step Guide: Building Your RAG System</h3><p>Let’s get hands-on with a step-by-step walkthrough of how to build a RAG system in 2025.</p><h3>Prerequisites</h3><p>Before you start, ensure you have the following:</p><ul><li>Python 3.8 or later</li><li>Libraries: langchain, langgraph, chromadb, openai</li><li>(Optional) langsmith for tracing and debugging</li></ul><p>Install them using:</p><pre>pip install --quiet --upgrade langchain-text-splitters langchain-community langgraph<br>pip install -qU langchain-openai<br>pip install -qU langchain-chroma</pre><h3>Step 1: Set Up the Environment</h3><p>Begin by importing necessary libraries and configuring your API key. Also, enable LangSmith tracing if you plan to debug your process.</p><pre>import getpass<br>import os<br>from langchain_openai import OpenAIEmbeddings<br>from langchain.chat_models import init_chat_model<br>from langchain_chroma import Chroma<br>import bs4<br>from langchain import hub<br>from langchain_community.document_loaders import WebBaseLoader<br>from langchain_core.documents import Document<br>from langchain_text_splitters import RecursiveCharacterTextSplitter<br>from langgraph.graph import START, StateGraph<br>from typing_extensions import List, TypedDict<br><br><br>if not os.environ.get(&quot;OPENAI_API_KEY&quot;):<br>  os.environ[&quot;OPENAI_API_KEY&quot;] = getpass.getpass(&quot;Enter API key for OpenAI: &quot;)<br><br>llm = init_chat_model(&quot;gpt-4o-mini&quot;, model_provider=&quot;openai&quot;)<br>embeddings = OpenAIEmbeddings(model=&quot;text-embedding-3-large&quot;)<br><br>vector_store = Chroma(<br>    collection_name=&quot;example_collection&quot;,<br>    embedding_function=embeddings,<br>    persist_directory=&quot;./chroma_langchain_db&quot;,  <br>)</pre><blockquote><strong><em>Security Note:</em></strong><em> Always ensure your API keys are stored securely and never hard-code them in public repositories.</em></blockquote><h3>Step 2: Load and Index Documents</h3><p>Next, load your documents, split them into manageable chunks, and store them in a vector database for efficient retrieval.</p><pre># Load and chunk contents of the blog<br>loader = WebBaseLoader(<br>    web_paths=(&quot;https://lilianweng.github.io/posts/2023-06-23-agent/&quot;,),<br>    bs_kwargs=dict(<br>        parse_only=bs4.SoupStrainer(<br>            class_=(&quot;post-content&quot;, &quot;post-title&quot;, &quot;post-header&quot;)<br>        )<br>    ),<br>)<br>docs = loader.load()<br></pre><pre>text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)<br>all_splits = text_splitter.split_documents(docs)<br><br># Index chunks<br>vector_store.add_documents(documents=all_splits)</pre><p><strong>Vector Store Options:</strong></p><blockquote><strong>ChromaDB:</strong> Easy, open-source Limited scalability</blockquote><blockquote><strong>Pinecone:</strong> High performance, managed Higher cost and setup required</blockquote><blockquote><strong>Weaviate:</strong> Scalable, open-source Steeper learning curve</blockquote><p>For simplicity, I used <strong>ChromaDB</strong>. However, for larger projects, you might consider Pinecone or Weaviate.</p><h3>Step 3: Define the RAG Workflow with LangGraph</h3><p>LangGraph helps you structure the RAG process by connecting document retrieval to response generation.</p><pre><br># Define prompt for question-answering<br>prompt = hub.pull(&quot;rlm/rag-prompt&quot;)<br><br><br># Define state for application<br>class State(TypedDict):<br>    question: str<br>    context: List[Document]<br>    answer: str<br><br><br># Define application steps<br>def retrieve(state: State):<br>    retrieved_docs = vector_store.similarity_search(state[&quot;question&quot;])<br>    return {&quot;context&quot;: retrieved_docs}<br><br><br>def generate(state: State):<br>    docs_content = &quot;\n\n&quot;.join(doc.page_content for doc in state[&quot;context&quot;])<br>    messages = prompt.invoke({&quot;question&quot;: state[&quot;question&quot;], &quot;context&quot;: docs_content})<br>    response = llm.invoke(messages)<br>    return {&quot;answer&quot;: response.content}<br><br><br># Compile application and test<br>graph_builder = StateGraph(State).add_sequence([retrieve, generate])<br>graph_builder.add_edge(START, &quot;retrieve&quot;)<br>graph = graph_builder.compile()</pre><h3>Step 4: Test It Out</h3><p>Now, let’s test the system with a simple query:</p><pre>response = graph.invoke({&quot;question&quot;: &quot;What is Task Decomposition?&quot;})<br>print(response[&quot;answer&quot;])</pre><p>When I ran this test, the system delivered accurate, context-rich answers quickly — far surpassing the performance of a standalone LLM.</p><h3>Real-World Use Case</h3><p>RAG is not just theoretical. Consider Grab, a leading tech giant in Southeast Asia: they use RAG to automatically summarize lengthy reports, cutting down task time by 3–4 hours and boosting efficiency by 20% (Evidently AI, 2025). Imagine a customer support bot that instantly pulls up relevant customer data to resolve issues — that’s RAG in action. It’s no wonder businesses are adopting this approach, and why I’m so passionate about it.</p><h3>Tips for Scaling</h3><p>To transition your prototype into a production-ready system, consider these strategies:</p><ul><li><strong>Caching:</strong> Store retrieved documents to reduce latency for repeat queries.</li><li><strong>Hybrid Search:</strong> Combine semantic search with traditional keyword search for more precise results (Databricks, 2025).</li><li><strong>Monitoring &amp; Evaluation:</strong> Track metrics such as response relevance and latency to continuously fine-tune performance.</li><li><strong>Security Enhancements:</strong> Ensure your system secures sensitive data and API keys through best practices.</li></ul><p>These adjustments can transform your initial prototype into a scalable, high-performance AI solution.</p><h3>Conclusion</h3><p>My journey from grappling with outdated AI responses to mastering RAG with LangChain and LangGraph has been transformative. We’ve built a system that is accurate, adaptable, and ready to meet the challenges of 2025. Looking ahead, innovations like <strong>long-context RAG</strong> (handling 25,000+ tokens) and web-integrated models like Gemini are set to redefine the landscape even further (Galileo AI, 2025).</p><p>Are you ready to try it? Build your RAG system today, experiment with these cutting-edge tools, and share your experience on Medium. Have you already implemented RAG in your projects? Drop a comment below — I’d love to hear your story. 🚀</p><h3>Further Reading</h3><ul><li><strong>LangChain Documentation:</strong> Get started with the fundamentals and advanced techniques.</li><li><strong>LangGraph Tutorials:</strong> Explore more complex workflow orchestration with hands-on examples.</li><li><strong>RAG Best Practices:</strong> Learn from case studies and industry insights on scaling AI systems.</li></ul><h3>Explore more and contact me</h3><p>Thank you for reading! If you found this guide useful, consider exploring more of my content or connecting with me online:</p><ul><li><strong>Connect on LinkedIn</strong><br>🔗 <a href="https://www.linkedin.com/in/md-hadi/">LinkedIn Profile</a></li><li><strong>Explore My Projects on GitHub</strong><br>🔗 <a href="https://github.com/hadiuzzaman524">GitHub Profile</a></li><li>💼 <strong>Available for Freelance Work</strong><br> I’m open to freelance projects in <strong>mobile app development</strong> and <strong>machine learning &amp; AI</strong>. Feel free to reach out!</li></ul><p>Feel free to reach out or follow me for more content on AI, software development, and tech insights! Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc126fb8a552" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Bag of Words (BoW) and How It Compares to TF-IDF]]></title>
            <link>https://md-hadi.medium.com/understanding-bag-of-words-bow-and-how-it-compares-to-tf-idf-f7d5d45be914?source=rss-3e2e8c53b23b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7d5d45be914</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Hadiuzzaman]]></dc:creator>
            <pubDate>Sat, 22 Feb 2025 04:55:39 GMT</pubDate>
            <atom:updated>2025-02-22T04:55:39.850Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SmxmWlqtdhMK98rPHAoAMw.jpeg" /></figure><p>Large Language Models (LLMs) like GPT-4 process vast amounts of textual data, requiring efficient feature extraction techniques. One of the foundational text preprocessing methods is <strong>Bag of Words (BoW)</strong>, which helps convert raw text into numerical representations. While BoW is simple and widely used, it has limitations that are addressed by more advanced techniques like <strong>TF-IDF (Term Frequency-Inverse Document Frequency)</strong>. This blog post explores BoW, its strengths and weaknesses, and how it compares to TF-IDF. For more details about TF-IDF, refer to <a href="https://medium.com/@md-hadi/mastering-tf-idf-preprocessing-text-data-for-large-language-models-6a5878aecda8">my other blog.</a></p><h3>What is Bag of Words (BoW)?</h3><p>BoW is a straightforward method for text vectorization that represents documents as word frequency vectors. It disregards grammar and word order, focusing solely on word occurrence.</p><h4>How BoW Works</h4><ol><li><strong>Tokenization</strong> — Split the text into individual words (tokens).</li><li><strong>Vocabulary Creation</strong> — List all unique words from the dataset (corpus).</li><li><strong>Vector Representation</strong> — Represent each document as a vector, where each entry corresponds to the count of a word in that document.</li></ol><h4>Step-by-Step Example of BoW</h4><p>Let’s walk through a <strong>real example</strong> to understand how BoW transforms raw text into numerical form.</p><p><strong>Step 1: Define the Corpus</strong></p><p>Imagine we have three short sentences:</p><ol><li><strong>“I love machine learning.”</strong></li><li><strong>“Machine learning is amazing.”</strong></li><li><strong>“Deep learning and machine learning are related.”</strong></li></ol><p><strong>Step 2: Tokenization &amp; Vocabulary Creation</strong></p><p>Extract all unique words (ignoring punctuation and case):</p><p><strong>Vocabulary:</strong> [&quot;I&quot;, &quot;love&quot;, &quot;machine&quot;, &quot;learning&quot;, &quot;is&quot;, &quot;amazing&quot;, &quot;deep&quot;, &quot;and&quot;, &quot;are&quot;, &quot;related&quot;]</p><p><strong>Step 3: Convert Sentences into Vectors</strong></p><p>Now, we count how many times each word appears in each sentence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RxHcqMGG_WOJ2fxkqK279A.png" /></figure><p>Each sentence is now represented as a <strong>numerical vector</strong>:</p><ul><li><strong>Sentence 1:</strong> [1, 1, 1, 1, 0, 0, 0, 0, 0, 0]</li><li><strong>Sentence 2:</strong> [0, 0, 1, 1, 1, 1, 0, 0, 0, 0]</li><li><strong>Sentence 3:</strong> [0, 0, 1, 1, 0, 0, 1, 1, 1, 1]</li></ul><p><strong>Step 4: Python Implementation</strong></p><p>We can implement BoW using Scikit-learn’s CountVectorizer:</p><pre>from sklearn.feature_extraction.text import CountVectorizer</pre><pre># Define the corpus<br>corpus = [<br>    &quot;I love machine learning.&quot;,<br>    &quot;Machine learning is amazing.&quot;,<br>    &quot;Deep learning and machine learning are related.&quot;<br>]</pre><pre># Initialize CountVectorizer<br>vectorizer = CountVectorizer()<br>bow_matrix = vectorizer.fit_transform(corpus)</pre><pre># Display the vocabulary<br>print(&quot;Vocabulary:&quot;, vectorizer.get_feature_names_out())</pre><pre># Display the BoW matrix<br>print(&quot;BoW Matrix:\n&quot;, bow_matrix.toarray())</pre><h3>How BoW Helps Predict the Next Word</h3><p>BoW itself does not predict the next word directly, but it can be used with probabilistic models like <strong>n-grams</strong> or <strong>Hidden Markov Models (HMMs)</strong> to calculate word probabilities. Let’s analyze how BoW handles <strong>“I love AI”</strong></p><ol><li><strong>Corpus</strong>:</li></ol><ul><li>“I love AI”</li><li>“AI is powerful”</li><li>“I love machine learning”</li></ul><p><strong>2. Vocabulary</strong>: [&quot;I&quot;, &quot;love&quot;, &quot;AI&quot;, &quot;is&quot;, &quot;powerful&quot;, &quot;machine&quot;, &quot;learning&quot;]</p><p><strong>3. BoW Representation</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*juMu61JWfelEXcg_amCuuQ.png" /></figure><p>Using word frequency, we calculate the probability of the next word:</p><p><strong>P(next word | “I love”) = Frequency(word after “I love”) / Total occurrences of “I love”</strong></p><ul><li>“AI” follows “I love” once</li><li>“machine” follows “I love” once</li></ul><p>Thus, <strong>P(AI | “I love”) = 1/2 = 0.5</strong> and <strong>P(machine | “I love”) = 1/2 = 0.5</strong>.</p><h3>Using BoW for Vector Search</h3><p>BoW vectors can be used for <strong>text similarity search</strong> using distance metrics like <strong>cosine similarity</strong>:</p><pre>from sklearn.metrics.pairwise import cosine_similarity</pre><pre># Compute similarity between sentences<br>similarity_matrix = cosine_similarity(bow_matrix)<br>print(&quot;Cosine Similarity Matrix:\n&quot;, similarity_matrix)</pre><p>This matrix helps identify similar documents based on word overlap. Higher similarity values indicate closer matches.</p><p>Complete code: <a href="https://github.com/hadiuzzaman524/deep-dive-on-machine-learning/blob/main/Bag_of_Word.ipynb">https://github.com/hadiuzzaman524/deep-dive-on-machine-learning/blob/main/Bag_of_Word.ipynb</a></p><h3>Conclusion</h3><p>BoW is an essential text preprocessing method, especially for beginner NLP tasks. However, it suffers from limitations that make TF-IDF a better choice in many cases. While both techniques are valuable, modern LLMs primarily rely on word embeddings (e.g., Word2Vec, BERT) to capture deeper semantic meanings. For more details about TF-IDF, refer to <a href="https://medium.com/@md-hadi/mastering-tf-idf-preprocessing-text-data-for-large-language-models-6a5878aecda8">my other blog.</a></p><h3>Explore More &amp; Connect with Me</h3><p>Thank you for reading! If you found this guide useful, consider exploring more of my content or connecting with me online:</p><ul><li><strong>Connect on LinkedIn</strong><br>🔗 <a href="https://www.linkedin.com/in/md-hadi/">LinkedIn Profile</a></li><li><strong>Explore My Projects on GitHub</strong><br>🔗 <a href="https://github.com/hadiuzzaman524">GitHub Profile</a></li></ul><p>Feel free to reach out or follow me for more content on AI, software development, and tech insights! Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7d5d45be914" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vector Databases for AI/ML: A Comprehensive Guide]]></title>
            <link>https://md-hadi.medium.com/vector-databases-for-ai-ml-a-comprehensive-guide-ea9bedab0190?source=rss-3e2e8c53b23b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea9bedab0190</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[vector-search]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Hadiuzzaman]]></dc:creator>
            <pubDate>Mon, 27 Jan 2025 17:01:10 GMT</pubDate>
            <atom:updated>2025-01-27T17:02:28.100Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*da57uuUvNAr2eWXKhRV1Dg.jpeg" /></figure><p>Vector databases are a pivotal technology in the AI/ML landscape, especially for applications that rely on similarity search, recommendation systems, and semantic understanding. In this guide, we will dive deep into the world of vector databases, covering what they are, why they matter, and how they are transforming artificial intelligence and machine learning applications.</p><h3>What is a Vector Database?</h3><p>A <strong>vector database</strong> is a specialized database designed to store, index, and retrieve high-dimensional vector embeddings efficiently. These embeddings are numerical representations of data (text, images, audio, etc.) that encode the semantic or structural meaning of the input data.</p><p>For instance:</p><ul><li>Text embeddings might encode the meaning of words or sentences.</li><li>Image embeddings could capture features like shapes or colors.</li><li>Audio embeddings might encode rhythm, tone, or frequency features.</li></ul><h3>Key Features of Vector Databases</h3><ol><li><strong>Efficient Similarity Search</strong>: Find vectors closest to a query vector using distance metrics (e.g., cosine similarity, Euclidean distance).</li><li><strong>Scalability</strong>: Handle millions or billions of high-dimensional vectors.</li><li><strong>Real-Time Queries</strong>: Support low-latency search for applications like recommendations or anomaly detection.</li><li><strong>Integration with AI/ML Pipelines</strong>: Seamlessly work with embedding models and frameworks.</li></ol><h3>Why Do We Need Vector Databases?</h3><p>In AI/ML applications, many tasks require comparing data points in terms of their similarity rather than their exact matches. Vector databases provide a robust solution for these tasks, solving challenges that traditional relational databases cannot efficiently address.</p><h3>Key Use Cases</h3><ol><li><strong>Semantic Search</strong>: Retrieve documents or images that are semantically similar to a query.</li><li><strong>Recommendation Systems</strong>: Suggest similar items (e.g., products, music, movies).</li><li><strong>Fraud Detection</strong>: Identify anomalous patterns by comparing vectors.</li><li><strong>Personalization</strong>: Tailor user experiences by analyzing their behavior in the embedding space.</li><li><strong>Image/Video Search</strong>: Find similar visual content based on features extracted by AI models.</li></ol><h3>How Vector Databases Work</h3><p>At the core of vector databases is the ability to perform <strong>nearest neighbor search</strong> (NNS) over high-dimensional spaces. Here’s how the process works:</p><h3>1. Data Preparation</h3><p>The input data (text, images, audio) is processed through an embedding model, such as:</p><ul><li>Text: Word2Vec, BERT, or Sentence Transformers.</li><li>Images: ResNet, CLIP, or Vision Transformers.</li><li>Audio: OpenL3, VGGish.</li></ul><p>These models convert the data into fixed-size vectors (e.g., a 512-dimensional vector for text).</p><h3>2. Indexing</h3><p>To enable fast similarity search, vector databases use specialized indexing techniques such as:</p><ul><li><strong>FAISS (Facebook AI Similarity Search)</strong>: An open-source library for vector indexing and search.</li><li><strong>HNSW (Hierarchical Navigable Small World)</strong>: A graph-based algorithm for approximate nearest neighbor search.</li><li><strong>Annoy</strong>: Tree-based indexing optimized for in-memory search.</li></ul><h3>3. Storage</h3><p>Vectors and their associated metadata (e.g., labels, file paths) are stored in the database.</p><h3>4. Querying</h3><p>When a query vector is provided, the database retrieves the most similar vectors using metrics like:</p><ul><li><strong>Cosine Similarity</strong>: Measures the angle between two vectors.</li><li><strong>Euclidean Distance</strong>: Measures the straight-line distance in vector space.</li></ul><h3>Popular Vector Databases</h3><p>Several vector databases have emerged, each with unique strengths:</p><h3>1. ChromaDB</h3><ul><li><strong>Focus</strong>: Optimized for AI/ML workflows.</li><li><strong>Integration</strong>: Works seamlessly with LLMs and embeddings.</li><li><strong>Key Features</strong>: Real-time updates, filtering, and scalability.</li></ul><h3>2. Pinecone</h3><ul><li><strong>Focus</strong>: Fully managed vector database.</li><li><strong>Strengths</strong>: Scalability and low-latency search.</li><li><strong>Key Use Cases</strong>: Recommendations, personalization.</li></ul><h3>3. Weaviate</h3><ul><li><strong>Focus</strong>: Open-source database with modular architecture.</li><li><strong>Strengths</strong>: Extensible with plugins for text, image, and audio embeddings.</li><li><strong>Key Features</strong>: GraphQL support and hybrid search.</li></ul><h3>4. Milvus</h3><ul><li><strong>Focus</strong>: Open-source vector database for large-scale AI applications.</li><li><strong>Strengths</strong>: High performance with distributed architecture.</li><li><strong>Key Features</strong>: Supports HNSW, IVF, and PQ indexing.</li></ul><h3>Example: Using ChromaDB for Text Search</h3><p>Here’s how you can use <strong>ChromaDB</strong> to store and search text embeddings:</p><h3>Step 1: Install ChromaDB</h3><pre>pip install chromadb</pre><h3>Step 2: Generate Text Embeddings</h3><p>Use a pre-trained embedding model (e.g., Sentence Transformers):</p><pre>from sentence_transformers import SentenceTransformer<br><br># Load pre-trained model<br>model = SentenceTransformer(&#39;all-MiniLM-L6-v2&#39;)<br><br># Sample texts<br>texts = [&quot;What is a vector database?&quot;, &quot;How do embeddings work?&quot;, &quot;AI and ML applications&quot;]<br><br># Generate embeddings<br>embeddings = model.encode(texts)</pre><h3>Step 3: Store Embeddings in ChromaDB</h3><pre>import chromadb<br><br># Initialize ChromaDB client<br>client = chromadb.PersistentClient(path=&quot;./chroma_data&quot;)<br><br># Create a collection<br>collection = client.create_collection(name=&quot;text_search_ex&quot;)<br><br># Add embeddings to the collection<br>collection.add(<br>    documents=texts,<br>    metadatas=[{&quot;source&quot;: &quot;doc1&quot;}, {&quot;source&quot;: &quot;doc2&quot;}, {&quot;source&quot;: &quot;doc3&quot;}],<br>    ids=[&quot;1&quot;, &quot;2&quot;, &quot;3&quot;],<br>    embeddings=embeddings<br>)</pre><h3>Step 4: Query for Similar Texts</h3><pre># Query with a new text<br>query_text = &quot;Explain vector databases.&quot;<br>query_embedding = model.encode([query_text])<br><br># Search in the collection<br>results = collection.query(query_embeddings=query_embedding, n_results=2)<br>print(&quot;Results:&quot;, results)Benefits of Vector Databases in AI/ML</pre><ol><li><strong>Scalability</strong>: Handle billions of high-dimensional vectors with ease.</li><li><strong>Performance</strong>: Low-latency retrieval enables real-time applications.</li><li><strong>Flexibility</strong>: Support for multimodal data (text, image, audio).</li><li><strong>Integration</strong>: Works seamlessly with AI/ML pipelines.</li></ol><h3>Challenges and Considerations</h3><ol><li><strong>Indexing Trade-Offs</strong>: Balancing accuracy vs. query speed with approximate nearest neighbor (ANN) methods.</li><li><strong>Storage Requirements</strong>: High-dimensional vectors can require significant storage.</li><li><strong>Embedding Quality</strong>: Poor embeddings lead to suboptimal search results.</li></ol><h3>Conclusion</h3><p>Vector databases are a cornerstone technology for AI/ML applications that rely on similarity search and semantic understanding. By leveraging embeddings and specialized indexing methods, they unlock the potential of unstructured data and enable a wide range of innovative solutions.</p><p>Whether you’re building a recommendation system, implementing semantic search, or creating personalized experiences, vector databases like ChromaDB, Pinecone, and Weaviate can help you achieve your goals efficiently.</p><p>Ready to get started? Explore the power of vector databases and transform your AI/ML projects today!</p><p>Complete code: <a href="https://github.com/hadiuzzaman524/deep-dive-on-machine-learning/blob/main/VectorDB.ipynb">https://github.com/hadiuzzaman524/deep-dive-on-machine-learning/blob/main/VectorDB.ipynb</a></p><h3>Explore More &amp; Connect with Me</h3><p>Thank you for reading! If you found this guide useful, consider exploring more of my content or connecting with me online:</p><ul><li><strong>Connect on LinkedIn</strong><br>🔗 <a href="https://www.linkedin.com/in/md-hadi/">LinkedIn Profile</a></li><li><strong>Explore My Projects on GitHub</strong><br>🔗 <a href="https://github.com/hadiuzzaman524">GitHub Profile</a></li></ul><p>Feel free to reach out or follow me for more content on AI, software development, and tech insights! Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea9bedab0190" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>