<?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 Mahendran K on Medium]]></title>
        <description><![CDATA[Stories by Mahendran K on Medium]]></description>
        <link>https://medium.com/@mahendrank75?source=rss-2d070e80357f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EUrhWKGhq5bi89Yho10Urw.jpeg</url>
            <title>Stories by Mahendran K on Medium</title>
            <link>https://medium.com/@mahendrank75?source=rss-2d070e80357f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 21:57:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mahendrank75/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[Decompose Conditional in Dart: Simplify Long If Statements]]></title>
            <link>https://medium.com/@mahendrank75/decompose-conditional-in-dart-simplify-long-if-statements-bb52ecd39662?source=rss-2d070e80357f------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb52ecd39662</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[programming-tips]]></category>
            <dc:creator><![CDATA[Mahendran K]]></dc:creator>
            <pubDate>Wed, 14 May 2025 04:31:37 GMT</pubDate>
            <atom:updated>2025-05-14T04:31:37.280Z</atom:updated>
            <content:encoded><![CDATA[<h3>Decompose Conditional in Dart: Make Your Code Speak Clearly</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FPKMrq5qEaxKyj38fR4meA.png" /></figure><p>In Dart, just like any other language, we often come across long `if-else` blocks that try to handle too much at once. They work fine… until they don’t.</p><p>In this blog, let’s talk about the clean code principle called <strong>“Decompose Conditional” </strong>— and how applying it in Dart makes your code easier to read, debug, and maintain.</p><blockquote><strong>“If your condition can’t be explained in one breath, it’s time to name it.”</strong><br> — Clean Code Mindset 🧠</blockquote><h4>The Problem: Complex Conditional Logic</h4><p>Imagine you’re checking user access inside a Flutter app:</p><pre>if (user.isActive &amp;&amp; user.age &gt; 18 &amp;&amp; user.subscription != null &amp;&amp; user.subscription!.isValid) {<br>  allowAccess();<br>} else {<br>  denyAccess();<br>}</pre><p>It works, but it’s doing too much in one go. What if this condition fails? Which part failed? It’s not obvious.</p><h4>The Solution: Decompose It!</h4><p>Break down the condition into smaller, named functions or variables that explain <strong>what</strong> the code is checking.</p><pre>bool isAdult(User user) =&gt; user.age &gt; 18;<br>bool hasValidSubscription(User user) =&gt;<br>    user.subscription != null &amp;&amp; user.subscription!.isValid;<br><br>bool canAccess(User user) =&gt;<br>    user.isActive &amp;&amp; isAdult(user) &amp;&amp; hasValidSubscription(user);<br><br>void handleAccess(User user) {<br>  if (canAccess(user)) {<br>    allowAccess();<br>  } else {<br>    denyAccess();<br>  }<br>}</pre><p>Now, even without comments, the code <strong>speaks for itself</strong>.</p><h4>Why Decomposing Helps</h4><ul><li>Easier to understand at a glance</li><li>Isolates logic each function can be tested independently</li><li>Simplifies debugging log or break at smaller checkpoints</li><li>Reusable use canAccess() wherever needed</li></ul><h4>Pros and Cons</h4><p>Pros:</p><ul><li>Improves code readability</li><li>Encourages function reuse</li><li>Supports clean architecture</li><li>Easier unit testing</li><li>Reduces duplication of logic</li></ul><p>Cons:</p><ul><li>May feel “too verbose” for tiny checks</li><li>Slight increase in number of functions</li><li>Needs discipline to name things meaningfully</li></ul><h4>💡Pro Tip</h4><p>Don’t blindly decompose everything. Use it when:</p><ul><li>Conditions are long, unreadable</li><li>You repeat similar logic in multiple places</li><li>You want better logging or test coverage</li><li>You follow <strong>clean code</strong> or <strong>TDD</strong> practices</li></ul><h3>Real Usage in Flutter</h3><p>In a real-world Flutter app, this pattern works well with:</p><ul><li>Form validation</li><li>Access control</li><li>Feature flags or A/B logic</li><li>Business rule evaluation</li><li>Navigation decisions (like onboarding flow checks)</li></ul><h3>Final Thoughts</h3><p>The next time you’re about to write a big if block, pause and ask:</p><blockquote><strong>“Can I split this into meaningful parts?”</strong><br> That one step can make your Dart code way more maintainable.</blockquote><p>Thanks for reading, let your functions speak for your logic!</p><p>✍️ <em>Written by a Flutter dev who avoids ‘if’ headaches by naming his conditions smartly.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb52ecd39662" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing Safer Functions in Dart with Guard-Style Early Returns]]></title>
            <link>https://medium.com/@mahendrank75/writing-safer-functions-in-dart-with-guard-style-early-returns-0832aaaa308f?source=rss-2d070e80357f------2</link>
            <guid isPermaLink="false">https://medium.com/p/0832aaaa308f</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[programming-tips]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Mahendran K]]></dc:creator>
            <pubDate>Tue, 13 May 2025 04:32:43 GMT</pubDate>
            <atom:updated>2025-05-13T04:32:43.217Z</atom:updated>
            <content:encoded><![CDATA[<p>When writing Dart functions, we often wrap everything in `if` statements and end up with deeply nested code. It works, but it’s not fun to read or debug.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-1Pr30fvX8_ZD1I9-4PZug.png" /></figure><p>In other languages like Swift, developers use `guard` statements to exit early when something isn’t right. Dart doesn’t have a `guard` keyword, but you can still write <strong><em>guard-style logic</em></strong> that’s safe, readable, and less error-prone.</p><p>Here’s how I use that pattern in my Dart projects, especially in production-level Flutter apps.</p><h4>Why Guard-Style Matters:</h4><p>Let’s say we’re validating user input in a function:</p><pre>void processUser(Map&lt;String, dynamic&gt;? user) {<br>  if (user != null) {<br>    if (user[&#39;name&#39;] != null) {<br>      if (user[&#39;email&#39;] != null) {<br>        print(&#39;Name: ${user[&#39;name&#39;]}&#39;);<br>        print(&#39;Email: ${user[&#39;email&#39;]}&#39;);<br>      }<br>    }<br>  }<br>}</pre><p>It works, but this nesting goes deep fast. Imagine having 3–4 more conditions, your code becomes hard to follow.</p><h4>The Guard-Style Fix (Early Return Pattern):</h4><p>Let’s flip the logic: check for invalid cases first, and return early. It’s like saying, <strong>“get out if this is broken”</strong>.</p><pre>void processUser(Map&lt;String, dynamic&gt;? user) {<br>  if (user == null) return; // Exit if user null<br>  if (user[&#39;name&#39;] == null) return; // Exit if name key have null value<br>  if (user[&#39;email&#39;] == null) return; // Exit if email key have null value<br><br>  print(&#39;Name: ${user[&#39;name&#39;]}&#39;);<br>  print(&#39;Email: ${user[&#39;email&#39;]}&#39;);<br>}</pre><p>Now that’s clean.</p><h4>Custom Helpers for Reusability:</h4><p>Sometimes I wrap common checks inside functions:</p><pre>bool isInvalidString(dynamic value) =&gt; value is! String || value.isEmpty;<br><br>void processUser(Map&lt;String, dynamic&gt;? user) {<br>  if (user == null) return;<br>  if (isInvalidString(user[&#39;name&#39;])) return;<br>  if (isInvalidString(user[&#39;email&#39;])) return;<br><br>  print(&#39;Name: ${user[&#39;name&#39;]}&#39;);<br>  print(&#39;Email: ${user[&#39;email&#39;]}&#39;);<br>}</pre><p>This works well in larger apps where validation patterns repeat.</p><h4>Pros and Cons of Guard-Style Coding in Dart:</h4><p>Pros:</p><ul><li><strong>Reduces nesting</strong> → improves readability</li><li><strong>Safer code</strong> → You exit before doing something risky</li><li><strong>Better debugging</strong> → you know where it failed</li><li><strong>Cleaner diffs</strong> → code changes are easier to track in version control</li><li><strong>Fits naturally in validation, parsing, async logic, etc.</strong></li></ul><p>Cons:</p><ul><li>Too many return statements in a row might look abrupt</li><li>If overused without naming intent clearly, it may reduce clarity</li><li>Doesn’t work well when you need to collect multiple errors at once (e.g., form validation that should show <em>all</em> issues)</li></ul><h4>Where I Use It the Most:</h4><ul><li>Form field validation</li><li>JSON parsing from API’s</li><li>Handling nullables from shared prefs / secure storage</li><li>Defensive UI logic (like “if user not logged in, return early”)</li><li>Filtering invalid data before business logic</li></ul><h4>Final Thoughts:</h4><p>You don’t need a guard keyword to write guard-style code. In Dart, returning early from a function is both legal and powerful. It’s helped me reduce bugs, avoid deeply nested logic, and make my functions much easier to read and reason about.</p><p>Try this pattern in your own Flutter code — start with validation or response handling — and you’ll quickly see the difference.</p><p>Thanks for reading!</p><p>✍️ Written by a Flutter developer who loves clean code and early exits more than nested if blocks</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0832aaaa308f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Structuring MQTT Data Streams in Flutter — A Clean and Scalable Approach]]></title>
            <link>https://medium.com/@mahendrank75/structuring-mqtt-data-streams-in-flutter-a-clean-and-scalable-approach-53defc01037e?source=rss-2d070e80357f------2</link>
            <guid isPermaLink="false">https://medium.com/p/53defc01037e</guid>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mqtt]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Mahendran K]]></dc:creator>
            <pubDate>Mon, 12 May 2025 04:41:53 GMT</pubDate>
            <atom:updated>2025-05-12T04:41:53.610Z</atom:updated>
            <content:encoded><![CDATA[<h3>Structuring MQTT Data Streams in Flutter — A Clean and Scalable Approach</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pUrsGzUf4r_k_eRUNusWKQ.png" /></figure><p>I recently worked on a Flutter project that involved real-time data using MQTT — think IoT sensors pushing updates constantly. At first, everything felt easy: connect to the broker, subscribe to a topic, get the payload, boom. But as things scaled up, handling the data started getting messy.</p><p>So I decided to properly structure the way MQTT data is handled. In this post, I’ll walk you through how I approached the problem and how I solved it with a clean, reusable architecture that works really well in Flutter.</p><h4>Why MQTT?</h4><p>MQTT (Message Queuing Telemetry Transport) is a lightweight protocol perfect for devices that send small, frequent data packets, like temperature sensors, motion detectors, or any real-time telemetry.</p><p>Flutter + MQTT is a great combo for mobile apps in IoT. I used the popular mqtt_client package to handle the connection.</p><h4>The Basic MQTT Setup</h4><p>Here’s how I connect and subscribe to a topic:</p><pre>final client = MqttServerClient(&#39;broker.xyz.com&#39;, &#39;PASSWORD&#39;);<br>client.port = 1883;<br>await client.connect();<br>client.subscribe(&#39;sensor/data&#39;, MqttQos.atLeastOnce);</pre><h4>The Problem: Raw Payload Handling</h4><p>When data arrives, it usually looks like this:</p><pre>{&quot;temp&quot;: 25.5, &quot;humidity&quot;: 80}</pre><p>I initially just parsed this inline in the UI and used it directly. It worked… until the data structure changed slightly. Then things started breaking. Debugging was hard, testing was worse, and the whole thing felt fragile.</p><p>So I decided to do what I should’ve done from the start: <strong>structure it cleanly</strong>.</p><h4>The Clean Solution</h4><p>Define a Strong Data Model</p><pre>class SensorData {<br>  final double temp;<br>  final int humidity;<br><br>  SensorData({required this.temp, required this.humidity});<br><br>  factory SensorData.fromJson(Map&lt;String, dynamic&gt; json) {<br>    return SensorData(<br>      temp: json[&#39;temp&#39;].toDouble(),<br>      humidity: json[&#39;humidity&#39;].toInt(),<br>    );<br>  }<br>}</pre><h4>Use a Service Class to Handle Streams</h4><pre>class MQTTService {<br>  final _controller = StreamController&lt;SensorData&gt;.broadcast();<br>  Stream&lt;SensorData&gt; get stream =&gt; _controller.stream;<br><br>  void handleMessage(String payload) {<br>    final data = SensorData.fromJson(jsonDecode(payload));<br>    _controller.add(data);<br>  }<br><br>  void listenToTopic() {<br>    client.updates!.listen((List&lt;MqttReceivedMessage&lt;MqttMessage?&gt;&gt; messages) {<br>      if(messages.isEmpty) return;<br>      final recMess = messages.first.payload as MqttPublishMessage;<br>      final payload =<br>          MqttPublishPayload.bytesToStringAsString(recMess.payload.message);<br><br>      handleMessage(payload);<br>    });<br>  }<br>}</pre><p>Now the service takes care of parsing, mapping, and exposing a clean stream to the rest of the app.</p><p>Bind It to UI Using StreamBuilder</p><pre>StreamBuilder&lt;SensorData&gt;(<br>  stream: mqttService.stream,<br>  builder: (context, snapshot) {<br>    if (!snapshot.hasData) return CircularProgressIndicator();<br>    final data = snapshot.data!;<br>    return Text(&quot;Temp: ${data.temp}°C, Humidity: ${data.humidity}%&quot;);<br>  },<br>)</pre><h4>Clean Architecture Wins</h4><p>What I loved about this structure:</p><ul><li>Clear separation of concerns</li><li>No JSON logic in the UI</li><li>Easy to reuse across screens or projects</li><li>Simple to write unit tests</li><li>Scales well when adding more message types or topics</li></ul><h4>Final Thoughts</h4><p>If you’re using MQTT in Flutter, take the time to structure your data pipeline. It’ll save you from debugging nightmares later.</p><p>This setup helped me make the codebase more maintainable, easier to test, and ready to scale. You can take this further by adding:</p><ul><li>Secure MQTT over TLS</li><li>Multiple topic handling</li><li>Message acknowledgment</li><li>Offline queuing and reconnection logic</li></ul><p>Thanks for reading! If you liked this or found it useful, follow me for more real-world Flutter + backend integration tips.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53defc01037e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>