<?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 Kosal Pen on Medium]]></title>
        <description><![CDATA[Stories by Kosal Pen on Medium]]></description>
        <link>https://medium.com/@kosalpen99?source=rss-4124e0738090------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZAW-JuY_J7Yt4nB1rbtBHg@2x.jpeg</url>
            <title>Stories by Kosal Pen on Medium</title>
            <link>https://medium.com/@kosalpen99?source=rss-4124e0738090------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 21:03:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kosalpen99/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[Stop Writing Git Commit Messages Manually: Build a Free AI Commit Generator in Your Terminal]]></title>
            <link>https://medium.com/@kosalpen99/stop-writing-git-commit-messages-manually-build-a-free-ai-commit-generator-in-your-terminal-b48cf571acda?source=rss-4124e0738090------2</link>
            <guid isPermaLink="false">https://medium.com/p/b48cf571acda</guid>
            <dc:creator><![CDATA[Kosal Pen]]></dc:creator>
            <pubDate>Thu, 12 Mar 2026 01:30:21 GMT</pubDate>
            <atom:updated>2026-03-12T01:30:21.832Z</atom:updated>
            <content:encoded><![CDATA[<p>As developers, we all know <strong>good commit messages matter</strong>.</p><p>But in reality, many commits end up looking like:</p><pre>fix<br>update<br>wip<br>change logic</pre><p>Not because we don’t care — but because we’re in the middle of coding and writing a clean commit message interrupts our flow.</p><p>So I built a small tool that automatically:</p><ul><li>analyzes staged Git changes</li><li>generates commit message suggestions with AI</li><li>lets you choose one</li><li>optionally adds a ticket number (like MBA-2644)</li><li>commits instantly</li></ul><p>All from the <strong>terminal</strong>.</p><p>No IDE plugin required.</p><h3>What This Tool Does</h3><p>The workflow looks like this:</p><pre>git add .<br>gcm-ai</pre><p>Output:</p><pre>✔ Commit suggestions:</pre><pre>1) refactor transfer purpose validation logic<br>2) add purposeOrRemarkIdentifier helper<br>3) update forex rate rounding behavior</pre><pre>Choose message (1–3): 1<br>Add ticket/suffix: MBA-2644</pre><pre>Final commit:<br>refactor transfer purpose validation logic [MBA-2644]</pre><pre>Commit now? Y</pre><p>Then Git runs:</p><pre>git commit -m &quot;refactor transfer purpose validation logic [MBA-2644]&quot;</pre><p>Clean, structured commits with <strong>almost zero effort</strong>.</p><h3>Why Use OpenRouter</h3><p>Instead of calling a single AI provider, this tool uses <strong>OpenRouter</strong>.</p><p>OpenRouter allows you to access many models through a single API.</p><p>For example:</p><ul><li>Claude</li><li>GPT</li><li>DeepSeek</li><li>Mistral</li><li>OpenRouter free models</li></ul><p>So you can switch models easily.</p><p>Example:</p><pre>commit-msg-openrouter --model anthropic/claude-3-haiku</pre><p>or</p><pre>commit-msg-openrouter --model openrouter/free</pre><h3>Step 1 — Install Dependencies</h3><p>You need:</p><ul><li>git</li><li>curl</li><li>jq</li></ul><p>Install jq on macOS:</p><pre>brew install jq</pre><h3>Step 2 — Get an OpenRouter API Key</h3><p>Create an account:</p><pre>https://openrouter.ai</pre><p>Then export the key:</p><pre>export OPENROUTER_API_KEY=&quot;your-api-key&quot;</pre><p>You can add it permanently to ~/.zshrc.</p><h3>Step 3 — Create the Script</h3><p>Create a folder for personal CLI tools:</p><pre>mkdir -p ~/bin</pre><p>Create the script:</p><pre>~/bin/commit-msg-openrouter</pre><p>Make it executable:</p><pre>chmod +x ~/bin/commit-msg-openrouter</pre><h3>The Script</h3><p>Here is a simplified but production-ready version.</p><pre>#!/usr/bin/env bash<br>set -euo pipefail</pre><pre>MODEL=&quot;${OPENROUTER_MODEL:-openrouter/free}&quot;</pre><pre>if ! git rev-parse --is-inside-work-tree &gt;/dev/null 2&gt;&amp;1; then<br>  echo &quot;✖ Not inside a git repository&quot;<br>  exit 1<br>fi</pre><pre>if git diff --cached --quiet; then<br>  echo &quot;⚠ No staged changes found&quot;<br>  exit 1<br>fi</pre><pre>INPUT=&quot;$(<br>  {<br>    git status --short<br>    echo<br>    git diff --cached<br>  }<br>)&quot;</pre><pre>PROMPT=&quot;<br>Analyze the staged git changes below and generate 3 commit message options.</pre><pre>Rules:<br>- imperative mood<br>- under 72 characters<br>- conventional commit style when possible<br>- output exactly 3 numbered lines</pre><pre>${INPUT}<br>&quot;</pre><pre>JSON=$(jq -n \<br>  --arg model &quot;$MODEL&quot; \<br>  --arg prompt &quot;$PROMPT&quot; \<br>  &#39;{<br>    model: $model,<br>    messages: [{role:&quot;user&quot;,content:$prompt}],<br>    temperature: 0.3<br>  }&#39;)</pre><pre>RESPONSE=$(curl -sS <a href="https://openrouter.ai/api/v1/chat/completions">https://openrouter.ai/api/v1/chat/completions</a> \<br>  -H &quot;Authorization: Bearer ${OPENROUTER_API_KEY}&quot; \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &quot;$JSON&quot;)</pre><pre>CONTENT=$(echo &quot;$RESPONSE&quot; | jq -r &#39;.choices[0].message.content&#39;)</pre><pre>echo<br>echo &quot;✔ Commit suggestions:&quot;<br>echo &quot;$CONTENT&quot;<br>echo</pre><pre>printf &quot;Choose 1-3: &quot;<br>read -r CHOICE</pre><pre>MSG=$(echo &quot;$CONTENT&quot; | sed -n &quot;${CHOICE}p&quot; | sed &#39;s/^[0-9]\. //&#39;)</pre><pre>printf &quot;Add ticket (optional): &quot;<br>read -r SUFFIX</pre><pre>if [[ -n &quot;$SUFFIX&quot; ]]; then<br>  MSG=&quot;$MSG [$SUFFIX]&quot;<br>fi</pre><pre>echo<br>echo &quot;Commit message:&quot;<br>echo &quot;$MSG&quot;<br>echo</pre><pre>git commit -m &quot;$MSG&quot;</pre><h3>Step 4 — Add a Shell Alias</h3><p>Add this to your ~/.zshrc.</p><pre>export PATH=&quot;$HOME/bin:$PATH&quot;</pre><pre>alias gcm-ai=&#39;commit-msg-openrouter&#39;</pre><p>Reload the shell:</p><pre>source ~/.zshrc</pre><p>Now run:</p><pre>gcm-ai</pre><h3>Real Example</h3><p>Suppose you changed logic for transfer validation.</p><p>Run:</p><pre>git add .<br>gcm-ai</pre><p>Output:</p><pre>✔ Commit suggestions:</pre><pre>1) refactor transfer purpose validation logic<br>2) add purposeOrRemarkIdentifier helper<br>3) improve forex rate rounding logic</pre><p>Choose:</p><p>Add ticket:</p><pre>TK-2644</pre><p>Final commit:</p><pre>refactor transfer purpose validation logic [TK-2644]</pre><h3>Why This Improves Git History</h3><p>Without automation:</p><pre>update<br>fix<br>change logic</pre><p>With AI assistance:</p><pre>refactor transfer purpose validation logic<br>fix incorrect forex rounding for KHR rates<br>add support for purpose or remark field detection</pre><p>This makes your Git history:</p><ul><li>easier to read</li><li>easier to review</li><li>easier to debug later</li></ul><h3>Advanced Ideas</h3><p>You can improve this tool further.</p><p>For example:</p><h3>Auto-detect Jira ticket</h3><pre>TK-2644</pre><p>from branch names like:</p><pre>feature/MBA-2644-transfer-logic</pre><h3>Support amend</h3><pre>gcm-ai --amend</pre><h3>Interactive arrow key menu</h3><p>Use fzf to select commit messages.</p><h3>Train commit style per repository</h3><p>For example:</p><pre>fix(scope):<br>refactor(scope):<br>feat(scope):</pre><h3>Final Thoughts</h3><p>AI tools don’t replace developer judgment.</p><p>But they can remove <strong>small friction from daily workflows</strong>.</p><p>Generating commit messages automatically is one of the simplest ways to improve:</p><ul><li>Git hygiene</li><li>developer productivity</li><li>code history quality</li></ul><p>All from a <strong>20-line terminal script</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b48cf571acda" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding RunLoop, Timer, CADisplayLink, and CoreAnimation in iOS]]></title>
            <link>https://medium.com/@kosalpen99/understanding-runloop-timer-cadisplaylink-and-coreanimation-in-ios-eaaa15b55301?source=rss-4124e0738090------2</link>
            <guid isPermaLink="false">https://medium.com/p/eaaa15b55301</guid>
            <dc:creator><![CDATA[Kosal Pen]]></dc:creator>
            <pubDate>Tue, 03 Mar 2026 04:25:00 GMT</pubDate>
            <atom:updated>2026-03-03T04:25:00.356Z</atom:updated>
            <content:encoded><![CDATA[<p>When building iOS apps, especially interactive UIs, developers often encounter Timer, CADisplayLink, CoreAnimation, and sometimes even RunLoop.Mode.</p><p>Many developers know how to use them — but not <strong>when</strong> or <strong>why</strong> to choose one over another.</p><p>Let’s break it down clearly.</p><h3>What is RunLoop?</h3><p>A <strong>RunLoop</strong> is the event-processing loop of a thread.</p><p>It:</p><ol><li>Waits for events</li><li>Wakes up when work arrives</li><li>Executes the event</li><li>Goes back to sleep</li><li>On the main thread, the RunLoop handles:</li></ol><ul><li>Touch events</li><li>Scroll events</li><li>Timer events</li><li>Delegate callbacks</li><li>Display updates</li></ul><p>You rarely need to manually control it — but understanding it helps avoid subtle UI bugs.</p><h3>RunLoop Modes (Why Your Timer Stops While Scrolling)</h3><p>RunLoop runs in different <strong>modes</strong>.</p><p>Common ones:</p><ul><li>.default → normal app state</li><li>.tracking → while scrolling / dragging</li><li>.common → includes both default + tracking</li></ul><p>If you schedule a Timer in .default, it may pause during scrolling because the run loop switches to tracking mode.</p><p>Fix:</p><pre>RunLoop.main.add(timer, forMode: .common)</pre><p>Now your timer continues during scroll.</p><h3>1️⃣ Timer — For Low Frequency Updates</h3><h3>Best for:</h3><ul><li>Countdown labels</li><li>Polling every few seconds</li><li>Delayed UI actions</li></ul><p>Example: Countdown label</p><pre>let timer = Timer(timeInterval: 1.0, repeats: true) { _ in<br>    print(&quot;tick&quot;)<br>}<br>RunLoop.main.add(timer, forMode: .common)</pre><h3>Pros</h3><ul><li>Simple</li><li>Easy to use</li><li>Good for 1s+ updates</li></ul><h3>Cons</h3><ul><li>Not frame-accurate</li><li>Can drift</li><li>Pauses if main thread is busy</li><li>Stops when app is backgrounded</li></ul><p>Use Timer when you update something occasionally, not every frame.</p><h3>2️⃣ CADisplayLink — Frame-Synced Updates</h3><p>CADisplayLink fires once per screen refresh (60Hz or 120Hz).</p><h3>Best for:</h3><ul><li>Progress rings</li><li>Custom drawing</li><li>Interactive animations</li><li>Smooth time-based transitions</li></ul><p>Example:</p><pre>var link: CADisplayLink?</pre><pre>link = CADisplayLink(target: self, selector: #selector(update))<br>link?.add(to: .main, forMode: .common)</pre><pre>@objc func update() {<br>    // update UI per frame<br>}</pre><h3>Pros</h3><ul><li>Perfect timing for animations</li><li>Frame-synced</li><li>Smooth</li></ul><h3>Cons</h3><ul><li>Higher CPU usage</li><li>Overkill for simple countdowns</li></ul><p>Use DisplayLink when you need smooth animation that depends on time progression.</p><h3>3️⃣ CoreAnimation — The Best Choice for Most Animations</h3><p>CoreAnimation works differently.</p><p>When you start an animation (like rotation, fade, move), it gets handed to the system’s rendering engine (GPU-backed).</p><p>Your code doesn’t need to update every frame.</p><p>Example: Spinner rotation</p><pre>let anim = CABasicAnimation(keyPath: &quot;transform.rotation.z&quot;)<br>anim.fromValue = 0<br>anim.toValue = Double.pi * 2<br>anim.duration = 1<br>anim.repeatCount = .infinity<br>view.layer.add(anim, forKey: &quot;spin&quot;)</pre><h3>Pros</h3><ul><li>Very smooth</li><li>GPU optimized</li><li>Efficient</li><li>Doesn’t rely on Timer</li></ul><h3>Cons</h3><ul><li>Not ideal for logic-based animation</li><li>Less flexible for complex state-driven updates</li></ul><p>Use CoreAnimation whenever possible for UI effects.</p><h3>What Happens in Background?</h3><p>Important:</p><ul><li>Timer stops when the app is suspended.</li><li>CADisplayLink stops.</li><li>CoreAnimation pauses.</li><li>RunLoop does not keep running.</li></ul><p>RunLoop does NOT keep your app alive.</p><p>If you need background work:</p><ul><li>Use BGTaskScheduler</li><li>Use location background mode</li><li>Use push notifications</li></ul><h3>When to Choose What?</h3><p>Use CaseBest ToolCountdown text (1s)TimerSmooth progress ringCADisplayLinkSpinner / Fade / Move animationCoreAnimationHeavy background logicNot RunLoop</p><h3>Final Mental Model</h3><ul><li><strong>RunLoop</strong> = event pump of a thread</li><li><strong>Timer</strong> = low-frequency event trigger</li><li><strong>CADisplayLink</strong> = per-frame trigger</li><li><strong>CoreAnimation</strong> = GPU-driven animation engine</li></ul><p>If you can animate using <strong>CoreAnimation</strong> → do that first.<br>If you need per-frame logic → use Understanding RunLoop, Timer, CADisplayLink, and CoreAnimation in iOS</p><p>When building iOS apps, especially interactive UIs, developers often encounter Timer, CADisplayLink, CoreAnimation, and sometimes even RunLoop.Mode.</p><p>Many developers know how to use them — but not <strong>when</strong> or <strong>why</strong> to choose one over another.</p><p>Let’s break it down clearly.</p><h3>What is RunLoop?</h3><p>A <strong>RunLoop</strong> is the event-processing loop of a thread.</p><p>It:</p><ol><li>Waits for events</li><li>Wakes up when work arrives</li><li>Executes the event</li><li>Goes back to sleep</li></ol><p>On the main thread, the RunLoop handles:</p><ul><li>Touch events</li><li>Scroll events</li><li>Timer events</li><li>Delegate callbacks</li><li>Display updates</li></ul><p>You rarely need to manually control it — but understanding it helps avoid subtle UI bugs.</p><h3>RunLoop Modes (Why Your Timer Stops While Scrolling)</h3><p>RunLoop runs in different <strong>modes</strong>.</p><p>Common ones:</p><ul><li>.default → normal app state</li><li>.tracking → while scrolling / dragging</li><li>.common → includes both default + tracking</li></ul><p>If you schedule a Timer in .default, it may pause during scrolling because the run loop switches to tracking mode.</p><p>Fix:</p><pre>RunLoop.main.add(timer, forMode: .common)</pre><p>Now your timer continues during scroll.</p><h3>1️⃣ Timer — For Low Frequency Updates</h3><h3>Best for:</h3><ul><li>Countdown labels</li><li>Polling every few seconds</li><li>Delayed UI actions</li></ul><p>Example: Countdown label</p><pre>let timer = Timer(timeInterval: 1.0, repeats: true) { _ in<br>    print(&quot;tick&quot;)<br>}<br>RunLoop.main.add(timer, forMode: .common)</pre><h3>Pros</h3><ul><li>Simple</li><li>Easy to use</li><li>Good for 1s+ updates</li></ul><h3>Cons</h3><ul><li>Not frame-accurate</li><li>Can drift</li><li>Pauses if main thread is busy</li><li>Stops when app is backgrounded</li></ul><p>Use Timer when you update something occasionally, not every frame.</p><h3>2️⃣ CADisplayLink — Frame-Synced Updates</h3><p>CADisplayLink fires once per screen refresh (60Hz or 120Hz).</p><h3>Best for:</h3><ul><li>Progress rings</li><li>Custom drawing</li><li>Interactive animations</li><li>Smooth time-based transitions</li></ul><p>Example:</p><pre>var link: CADisplayLink?<br><br>link = CADisplayLink(target: self, selector: #selector(update))<br>link?.add(to: .main, forMode: .common)<br><br>@objc func update() {<br>    // update UI per frame<br>}</pre><pre>link = CADisplayLink(target: self, selector: #selector(update))<br>link?.add(to: .main, forMode: .common)</pre><pre>@objc func update() {<br>    // update UI per frame<br>}</pre><h3>Pros</h3><ul><li>Perfect timing for animations</li><li>Frame-synced</li><li>Smooth</li></ul><h3>Cons</h3><ul><li>Higher CPU usage</li><li>Overkill for simple countdowns</li></ul><p>Use DisplayLink when you need smooth animation that depends on time progression.</p><h3>3️⃣ CoreAnimation — The Best Choice for Most Animations</h3><p>CoreAnimation works differently.</p><p>When you start an animation (like rotation, fade, move), it gets handed to the system’s rendering engine (GPU-backed).</p><pre>let anim = CABasicAnimation(keyPath: &quot;transform.rotation.z&quot;)<br>anim.fromValue = 0<br>anim.toValue = Double.pi * 2<br>anim.duration = 1<br>anim.repeatCount = .infinity<br>view.layer.add(anim, forKey: &quot;spin&quot;)</pre><p>Example: Spinner rotation</p><pre>let anim = CABasicAnimation(keyPath: &quot;transform.rotation.z&quot;)<br>anim.fromValue = 0<br>anim.toValue = Double.pi * 2<br>anim.duration = 1<br>anim.repeatCount = .infinity<br>view.layer.add(anim, forKey: &quot;spin&quot;)</pre><p>If you can animate using CoreAnimation → do that first.<br> If you need per-frame logic → use DisplayLink.<br> If you need occasional updates → use Timer.</p><p>Understanding these tools helps you write smoother, more efficient, and more predictable iOS UI..<br>If you need occasional updates → use Timer.</p><p>Understanding these tools helps you write smoother, more efficient, and more predictable iOS UI.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eaaa15b55301" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vibe Coding: What’s Safe vs Risky]]></title>
            <link>https://medium.com/@kosalpen99/vibe-coding-whats-safe-vs-risky-aed435de5b2e?source=rss-4124e0738090------2</link>
            <guid isPermaLink="false">https://medium.com/p/aed435de5b2e</guid>
            <dc:creator><![CDATA[Kosal Pen]]></dc:creator>
            <pubDate>Thu, 22 Jan 2026 16:25:54 GMT</pubDate>
            <atom:updated>2026-01-22T16:25:54.337Z</atom:updated>
            <content:encoded><![CDATA[<p>Vibe coding means using an AI assistant to move fast — generating code, refactoring, or exploring solutions — often with less upfront design than traditional development. It can be a huge productivity boost, but it can also introduce subtle bugs that “look correct” and still fail in edge cases. The trick is to choose the right areas and apply simple guardrails.</p><h3>Why vibe coding can be risky</h3><p>AI is very good at producing plausible code. But “plausible” isn’t always correct, especially when:</p><ul><li>The system has many edge cases.</li><li>Timing/order matters (concurrency).</li><li>Small changes can affect correctness.</li><li>Security and privacy requirements exist.</li><li>Failures are expensive or hard to detect.</li></ul><p>So the problem isn’t “AI writes bad code.” The problem is <strong>silent mistakes</strong> in places where correctness matters most.</p><h3>The Safety Map</h3><h3>Green Zone: Safe to vibe code (high confidence)</h3><p>These are areas where mistakes are easy to see, easy to test, or low impact.</p><p><strong>1) UI and usability</strong></p><ul><li>Layouts, styling, responsiveness</li><li>Animations and transitions</li><li>Copy text, empty states, error messages</li><li>Localization key generation and wording cleanup</li></ul><p><strong>Why safe:</strong> visual regressions are obvious and usually don’t affect core correctness.</p><p><strong>2) Boilerplate and scaffolding</strong></p><ul><li>Setting up folders/modules</li><li>Wiring dependencies/config in a predictable way</li><li>Creating DTOs/models and basic mapping (when rules are clear)</li></ul><p><strong>Why safe:</strong> mostly structure; compile-time checks catch many issues.</p><p><strong>3) Documentation and tooling</strong></p><ul><li>README, usage guides, architecture notes</li><li>Debug toggles and developer settings screens</li><li>Logging helpers and metrics dashboards</li></ul><p><strong>Why safe:</strong> improves visibility and doesn’t change critical logic.</p><p><strong>4) Tests</strong></p><ul><li>Unit tests for pure functions</li><li>Mock generators, fixtures, snapshot tests</li></ul><p><strong>Why safe:</strong> tests reduce risk instead of increasing it.</p><h3>Yellow Zone: Vibe with guardrails (medium risk)</h3><p>These areas can benefit from AI, but you should lock behavior with rules and regression checks.</p><p><strong>1) Concurrency “micro-features” around a pipeline</strong></p><ul><li>Throttling work (run expensive steps every N events)</li><li>“Latest wins” backpressure (keep newest item, drop old)</li><li>Cancellation of in-flight tasks</li><li>Ensuring only one job runs at a time</li><li>Moving heavy work off the main thread</li></ul><p><strong>Why yellow:</strong> concurrency changes can reorder events or create rare race conditions.</p><p><strong>Guardrails</strong></p><ul><li>One behavior change per PR</li><li>Add instrumentation (duration, queue length, dropped count)</li><li>Add unit tests for scheduler logic</li><li>Verify under load / stress</li></ul><p><strong>2) Refactors in complex modules (no behavior change)</strong></p><ul><li>Extract helpers, rename, move code</li><li>Simplify large functions without changing outputs</li></ul><p><strong>Why yellow:</strong> even “harmless” refactors can change edge behavior.</p><p><strong>Guardrails</strong></p><ul><li>Add tests first</li><li>Keep diffs small</li><li>Compare outputs before/after (golden tests if possible)</li></ul><p><strong>3) Performance improvements</strong></p><ul><li>Reduce allocations</li><li>Cache computed values</li><li>Batch work</li></ul><p><strong>Why yellow:</strong> easy to “optimize” the wrong thing or break subtle behavior.</p><p><strong>Guardrails</strong></p><ul><li>Measure first (baseline)</li><li>Add metrics to prove improvement</li><li>Keep a rollback path</li></ul><h3>Red Zone: Don’t vibe code (high risk)</h3><p>Avoid vibe coding for anything where small mistakes are expensive, security-sensitive, or hard to detect.</p><p><strong>1) Money movement / billing / reconciliation</strong></p><ul><li>State transitions (pending → success/fail)</li><li>Idempotency and retry rules</li><li>Totals, fees, exchange-rate math</li></ul><p><strong>2) Authentication and security</strong></p><ul><li>Token/session handling, refresh logic</li><li>Cryptography/signatures, secure storage</li><li>Permission enforcement, access control</li></ul><p><strong>3) Privacy-sensitive core processing</strong></p><ul><li>Any logic that transforms or stores sensitive data</li><li>Matching/verification rules that affect acceptance/rejection</li><li>The “correctness path” that must be deterministic</li></ul><p><strong>Why red:</strong> the blast radius is high and failures may only appear in production.</p><h3>A simple decision rule</h3><p>Ask one question:</p><p><strong>“If this fails, do we lose money, expose data, or break security/compliance?”</strong></p><ul><li>If <strong>yes</strong> → Red zone (avoid vibe coding)</li><li>If <strong>no</strong>, but timing/order/perf matters → Yellow zone (guardrails)</li><li>If mostly UI/tooling/structure/tests → Green zone (vibe freely)</li></ul><h3>Guardrails that make vibe coding safe</h3><p>These work in almost any project:</p><p><strong>1) Write invariants (non-negotiable rules)</strong><br> Example invariants:</p><ul><li>Outputs must not change for the same inputs</li><li>Event ordering must remain the same</li><li>No new blocking on the main thread</li><li>No unbounded memory growth</li></ul><p><strong>2) Use micro tasks</strong></p><ul><li>Keep PRs small (≤ 200 lines diff when possible)</li><li>Change one thing at a time</li></ul><p><strong>3) Add regression protection</strong></p><ul><li>Unit tests for pure logic</li><li>Golden tests for outputs (when applicable)</li><li>Instrumentation for performance and behavior</li></ul><p><strong>4) Require an “Impact Summary”</strong><br> Every AI-assisted change should include:</p><ul><li>What changed</li><li>What didn’t change</li><li>Risks</li><li>How it was verified (tests/metrics/manual checks)</li></ul><h3>Summary</h3><p>Vibe coding is not automatically good or bad — it’s a speed multiplier. Use it heavily in the Green zone, carefully in the Yellow zone with guardrails, and avoid it in the Red zone where correctness/security/privacy is critical.</p><p>If you want, tell me your module type (UI, concurrency scheduler, payment flow, auth, data processing) and I’ll label it <strong>Green/Yellow/Red</strong> and propose safe micro tasks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aed435de5b2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Caching Done Right: Why CachePolicy Is Essential — Even If Your API Already Caches]]></title>
            <link>https://medium.com/@kosalpen99/swift-caching-done-right-why-cachepolicy-is-essential-even-if-your-api-already-caches-aac49c45b358?source=rss-4124e0738090------2</link>
            <guid isPermaLink="false">https://medium.com/p/aac49c45b358</guid>
            <dc:creator><![CDATA[Kosal Pen]]></dc:creator>
            <pubDate>Wed, 20 Aug 2025 07:54:26 GMT</pubDate>
            <atom:updated>2025-08-20T07:54:26.204Z</atom:updated>
            <content:encoded><![CDATA[<h3>Swift Caching Done Right: Why CachePolicy Is Essential — Even If Your API Already Caches</h3><blockquote>Spoiler: HTTP caching saves bandwidth. App-level caching saves your UX. You need both.</blockquote><p><strong>You’ve set up your API with:</strong></p><p>✅ Cache-Control: max-age=60<br>✅ ETag headers<br>✅ URLSession automatic caching</p><p>So when your teammate suggests adding a CachePolicy enum and a custom HybridCache, you pause.</p><blockquote><em>“Wait… aren’t we double-caching?”</em></blockquote><p>Short answer: No.<br>Long answer: You’re solving two different problems.</p><p>Let me show you why app-level caching is non-negotiable — and how to implement it the right way in Swift.</p><h3>🧠 The Hard Truth: Fast Network ≠ Great UX</h3><p>Imagine this:</p><ul><li>User opens the app</li><li>Spinner appears</li><li>1.2 seconds later, data loads</li></ul><p>Even if that data came from URLSession’s HTTP cache, the user waited.</p><p>But what if you could:</p><ul><li>Show data instantly</li><li>Refresh in the background</li><li>Work offline</li><li>Control per-screen behavior</li></ul><p>That’s where your own CachePolicy comes in.</p><h3>🔁 Two Types of Caching — And Why You Need Both</h3><h4>HTTP / Network Caching</h4><ul><li>Reduce bandwidth, avoid re-downloading by server (Cache-Control,ETag)</li></ul><h4>App-Level Caching</h4><ul><li>Improve UX, support offline, control flow</li></ul><p><strong>They’re not redundant — they’re complementary.</strong></p><p>Think of it like a relay race: <strong>App Cache → HTTP Cache → Network</strong></p><h3>🛠 The CachePolicy You Need</h3><p>Here’s a flexible, UX-driven enum:</p><pre>enum CachePolicy {<br>    case cacheOnly<br>    case cacheElseNetwork<br>    case networkOnly<br>    case cacheFirstThenRefresh(ttl: TimeInterval)<br>}</pre><p>Now use it based on user intent, not just tech.</p><h3>✅ When to Use Each Policy</h3><ul><li>.cacheFirstThenRefresh(ttl: 30)<br>→ App launch, feed screens<br>→ Show cached data instantly, refresh in the background</li><li>.networkOnly<br>→ Pull-to-refresh<br>→ Force fresh data, update cache</li><li>.cacheElseNetwork<br>→ Profile, settings<br>→ Use cache if available, fallback to network</li><li>.cacheOnly<br>→ Offline mode<br>→ Never hit the network</li></ul><p>This is UX-aware caching — something raw HTTP headers can’t express.</p><h3>🧩 Build a HybridCache That Survives Restarts</h3><p>Most tutorials stop at in-memory caching. Real apps need persistence and thread safety.</p><p>Here’s a production-ready actor-based cache:</p><pre>actor HybridCache&lt;T: Codable&gt; {<br>    private var memory: [String: (value: T, date: Date)] = [:]<br>    private let directory: URL<br><br>    init(name: String = &quot;app-cache&quot;) {<br>        let cacheDir = FileManager.default<br>            .urls(for: .cachesDirectory, in: .userDomainMask)<br>            .first!<br>        self.directory = cacheDir.appendingPathComponent(name)<br>        try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)<br>    }<br><br>    func object(forKey key: String) async -&gt; T? { ... }<br>    func set(object: T, forKey key: String) async { ... }<br>    func isExpired(forKey key: String, ttl: TimeInterval) async -&gt; Bool { ... }<br>}</pre><h3>✅ Why This Works</h3><ul><li>actor → Thread-safe by default</li><li>Disk + memory → Survives app restarts</li><li>TTL-aware → Control freshness per use case</li></ul><h3>🔗 How the Layers Work Together</h3><pre>func fetchEvents(page: Int, policy: CachePolicy) async throws -&gt; [Event] {<br>    let key = &quot;events-page-$page)&quot;<br><br>    switch policy {<br>    case .cacheFirstThenRefresh(let ttl):<br>        // 1. Show cached data instantly<br>        if let cached = await cache.object(forKey: key),<br>           !await cache.isExpired(forKey: key, ttl: ttl) {<br>            return cached<br>        }<br><br>        // 2. Refresh in background (uses HTTP cache too!)<br>        Task {<br>            do {<br>                let fresh = try await service.fetchEvents(page: page)<br>                await cache.set(object: fresh, forKey: key)<br>            } catch { }<br>        }<br><br>        // 3. Return cached data (even if stale)<br>        return await cache.object(forKey: key)<br>            ?? try await service.fetchEvents(page: page)<br>    }<br>}</pre><h3>🔍 What Happens Behind the Scenes?</h3><ul><li>Your HybridCache → handles instant UI</li><li>URLSession → uses ETag and Cache-Control → saves bandwidth</li><li>Server → only hit when truly needed</li></ul><p>✅ Best of both worlds.</p><h3>✅ When Should You Use App-Level Caching?</h3><p>Use it if any of these are true:</p><ul><li>You want instant data on screen</li><li>You support offline mode</li><li>You need custom TTLs per screen</li><li>You have pull-to-refresh</li><li>You care about perceived performance</li></ul><blockquote><em>💡 Rule of thumb:<br>If your user would see a spinner or blank screen — you need app-level caching.</em></blockquote><h3>🚫 Common Myths — Busted</h3><p>❌ <em>“If the server sets </em><em>max-age=60, I don’t need my own cache.”</em><br>→ But at second 61, the user waits. Your app cache can still show stale data and refresh silently.</p><p>❌ <em>“Caching is just about speed.”</em><br>→ No. It’s about resilience, UX, and user trust.</p><p>❌ <em>“I’ll just use </em><em>UserDefaults.”</em><br>→ Fine for small data. But for complex models, use a proper actor-based cache.</p><h3>🏆 The Best Approach: Layered Caching</h3><pre>┌─────────────────┐<br>│  App Cache      │ ← Fast, controlled, persistent<br>│  (HybridCache)  │ ← Your `CachePolicy`<br>└─────────────────┘<br>         ↓<br>┌─────────────────┐<br>│  HTTP Cache     │ ← Automatic, URLSession-managed<br>│  (ETag, etc.)   │ ← Saves bandwidth<br>└─────────────────┘<br>         ↓<br>┌─────────────────┐<br>│  Network Fetch  │ ← Last resort<br>└─────────────────┘</pre><p><strong>This layered strategy gives you:</strong></p><ul><li>✅ Instant UI</li><li>✅ Offline support</li><li>✅ Bandwidth savings</li><li>✅ Full control over refresh logic</li></ul><h3>💡 Pro Tips</h3><ul><li>✅ Mark your repository as Sendable — critical for Swift concurrency</li><li>✅ Clear cache on logout: await cache.clear()</li><li>✅ Add debug logs: print(&quot;Cache HIT: $key)&quot;)</li><li>✅ Test offline flows — they’ll impress your PM</li><li>✅ Version your cache if models change</li></ul><h3>🎯 Final Thought</h3><blockquote><em>The network is slow. The server is busy. But your app? It should feel instant.</em></blockquote><p>App-level caching with CachePolicy isn’t redundant — it’s essential for modern iOS apps.</p><p><strong>Use it to:</strong></p><ul><li>Deliver instant UI</li><li>Handle offline scenarios</li><li>Give users control (via pull-to-refresh)</li><li>Reduce perceived latency</li></ul><p>And let HTTP caching do what it does best: save bandwidth.</p><p>Together, they make your app fast, smart, and resilient.</p><h3>📣 Let’s Discuss</h3><p>How do you handle caching in your app?</p><ul><li>Do you use actor, NSCache, or a database?</li><li>Have you tried AsyncStorage or SQLite?</li><li>What’s your favorite CachePolicy pattern?</li></ul><p>Let’s chat in the comments 👇</p><p>And if you found this helpful:</p><p>👏 Clap<br>🔁 Share<br>🔔 Follow for more Swift &amp; iOS architecture deep dives</p><p><em>Check out my other posts on Swift Concurrency, Clean Architecture, and SwiftUI performance.</em></p><p>#iOS #Swift #SwiftUI #Architecture #Caching #Performance #MobileDevelopment #Apple #Concurrency #CleanCode</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aac49c45b358" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Concurrency vs RxSwift: The Future of iOS Development in 2025]]></title>
            <link>https://medium.com/@kosalpen99/swift-concurrency-vs-rxswift-the-future-of-ios-development-in-2025-149d9c3b1959?source=rss-4124e0738090------2</link>
            <guid isPermaLink="false">https://medium.com/p/149d9c3b1959</guid>
            <dc:creator><![CDATA[Kosal Pen]]></dc:creator>
            <pubDate>Mon, 18 Aug 2025 10:01:15 GMT</pubDate>
            <atom:updated>2025-08-18T10:01:15.357Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why async/await is replacing RxSwift — and how to make the switch</h4><blockquote>Spoiler: You don’t need RxSwift anymore for most apps.</blockquote><h4>The Shift Is Here</h4><p>For years, RxSwift was the gold standard for reactive programming in iOS.</p><p>It brought:</p><ul><li>Clean data flows</li><li>Elegant UI bindings</li><li>Powerful operators like flatMapLatest, debounce, and combineLatest</li></ul><p>But in 2021, Apple changed the game with Swift Concurrency — a native, modern, and simpler way to handle async code.</p><p>Now, in 2025, the question isn’t <em>“Should I use RxSwift?”</em><br>It’s <em>“Do I still need RxSwift?”</em></p><p>The answer, for most teams: <strong>No</strong>.</p><h4>RxSwift vs. Swift Concurrency:</h4><ul><li>✅ RxSwift requires manual management of subscriptions, schedulers, and memory (e.g., DisposeBag, observeOn), leading to complexity and potential leaks if not handled carefully.</li><li>✅ Swift Concurrency uses native async/await, @MainActor, and structured tasks to simplify asynchronous code, eliminate boilerplate, and provide built-in safety and readability.</li></ul><h4>Side-by-Side: Real-World Examples</h4><h4>1. Network Request</h4><p>RxSwift</p><pre>api.fetchUser()<br>  .observeOn(MainScheduler.instance)<br>  .subscribe(onSuccess: { [weak self] user in<br>      self?.updateUI(with: user)<br>    }, onError: { [weak self] error in<br>      self?.showError(error)<br>    }<br>  )</pre><p>Swift Concurrency</p><pre>do {<br>  let user = try await api.fetchUser()<br>  updateUI(with: user)<br>} catch {<br>  showError(error)<br>}</pre><p>✅ Fewer lines. No subscriptions. No memory leaks.</p><h4>2. Parallel API Calls</h4><p>RxSwift</p><pre>Observable.combineLatest(fetchUser(), fetchPosts())<br>  .observeOn(MainScheduler.instance)<br>  .subscribe(onSuccess: { user, posts in<br>    self.show(user, posts)<br>})</pre><p>Swift Concurrency</p><pre>async let user = fetchUser()<br>async let posts = fetchPosts()<br>let (user, posts) = await (user, posts)<br>show(user, posts)</pre><p>✅ No extra operators. No boilerplate. Just works.</p><h4>3. Debounce Search Input</h4><p>RxSwift</p><pre>searchTextField.rx.text.orEmpty<br>  .debounce(.milliseconds(300), scheduler: MainScheduler.instance)<br>  .distinctUntilChanged()<br>  .flatMapLatest { query in<br>    api.search(query).asObservable()<br>  }<br>  .subscribe(onNext: { results in<br>    self.update(results)<br>  })</pre><p>Swift Concurrency (with extension)</p><pre>for await query in searchTextField.values.debounce(for: 0.3) {<br>  do {<br>      let results = try await api.search(query)<br>      await MainActor.run { self.update(results) }<br>  } catch { }<br>}</pre><p>You’ll need a small debounce() extension on AsyncSequence, but it’s reusable:</p><pre>extension AsyncSequence {<br>  func debounce(for seconds: TimeInterval) -&gt; AsyncStream&lt;Element&gt; {<br>    AsyncStream { continuation in<br>      var lastTask: Task&lt;Void, Never&gt;?<br>      Task {<br>        for await element in self {<br>        lastTask?.cancel()<br>        lastTask = Task {<br>          try? await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000))<br>          continuation.yield(element)<br>         }<br>        }<br>        continuation.finish()<br>      }<br>    }<br>  }<br>}</pre><h4>4. Shared State (Like BehaviorSubject)</h4><p>RxSwift</p><pre>class UserManager {<br>  static let shared = UserManager()<br>  private let _user = BehaviorSubject&lt;User?&gt;(value: nil)<br>  var user: Observable&lt;User?&gt; { _user.asObservable() }<br>  func login(_ user: User) {<br>    _user.onNext(user)<br>  }<br>}</pre><p>Swift Concurrency</p><pre>@MainActor<br>actor UserManager {<br>  static let shared = UserManager()<br>  private var user: User?<br>  private init() {}<br>  func login(_ newUser: User) {<br>    self.user = newUser<br>  }<br>  func getUser() -&gt; User? {<br>    return user<br>  }<br>}</pre><p>Or with @Published (MVVM):</p><pre>@MainActor<br>class ViewModel: ObservableObject {<br>  @Published var user: User?<br>}</pre><p>✅ Thread-safe, simple, no extra dependencies.</p><h4>✅ When to Keep RxSwift</h4><p>You might still need RxSwift if:</p><ul><li>🔁 You have a large existing codebase (migration takes time)</li><li>📱 You support iOS &lt; 13 (Swift Concurrency requires iOS 13+)</li><li>🛠️ You rely heavily on advanced operators (scan, window, buffer)</li><li>🧪 You use Driver or Signal for UI binding safety</li><li>🏗️ Your team isn’t ready to retrain</li></ul><p>But for new projects, the choice is clear.</p><h4>🔄 Migration Strategy</h4><h4>Step 1: Use Both Together</h4><p>Bridge RxSwift to async:</p><pre>extension Publisher {<br>  func values(first: Int = 1) async throws -&gt; [Output] {<br>    var values: [Output] = []<br>    for try await value in self.values {<br>    values.append(value)<br>    if values.count &gt;= first { break }<br>  }<br>  return values<br>  }<br>}</pre><p>Now:</p><pre>let user = try await api.fetchUser().values().first</pre><h4>Step 2: Replace Feature by Feature</h4><ul><li>Start with network layers</li><li>Then view models</li><li>Finally UI bindings</li></ul><h4>Step 3: Remove RxSwift</h4><p>Once all code uses async, remove the dependency.</p><h4>💡 Why This Matters</h4><p>Swift Concurrency is:</p><ul><li>Built-in — no CocoaPods, SPM, or version conflicts</li><li>Safer — structured concurrency, actors, cancellation</li><li>Faster — optimized by Apple, no abstraction overhead</li><li>Easier to learn — async/await reads like sync code</li></ul><p>RxSwift was revolutionary in 2016.<br>But in 2025, Swift Concurrency is the better choice.</p><h4>🏁 Final Verdict</h4><blockquote><em>RxSwift had its moment. Now, it’s time to move on.</em></blockquote><p>You don’t need a third-party library to write clean, reactive, concurrent code.</p><p>Swift has it built in.</p><p>So ask yourself:</p><blockquote><em>“Am I using RxSwift because it’s the best tool — or because it’s the one I learned?”</em></blockquote><p>If it’s the latter, it’s time to upgrade.</p><ul><li>Follow for more iOS, Swift, and architecture deep dives.</li><li>Comment: Are you still using RxSwift? Why or why not?</li><li>Follow for more iOS, Swift, and architecture deep dives.</li><li>Comment: Are you still using RxSwift? Why or why not?</li></ul><h4>📎 Bonus: Resources</h4><ul><li><a href="https://developer.apple.com/wwdc21/10134">Swift Concurrency: Behind the Scenes (WWDC)</a></li><li><a href="https://developer.apple.com/documentation/swift/asyncsequence">AsyncSequence Documentation</a></li><li><a href="https://forums.developer.apple.com/">Migrating from RxSwift (Apple Forums)</a></li></ul><p>✅ Clap if this helped you decide.<br>✅ Share with your team.<br>✅ Start writing simpler, safer code today.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=149d9c3b1959" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git Cheat Sheet: Your Ultimate Guide to Mastering Git Workflows]]></title>
            <link>https://medium.com/@kosalpen99/git-cheat-sheet-your-ultimate-guide-to-mastering-git-workflows-df72b0d1f13a?source=rss-4124e0738090------2</link>
            <guid isPermaLink="false">https://medium.com/p/df72b0d1f13a</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[cheatsheet]]></category>
            <category><![CDATA[source-control]]></category>
            <dc:creator><![CDATA[Kosal Pen]]></dc:creator>
            <pubDate>Sat, 24 May 2025 08:05:05 GMT</pubDate>
            <atom:updated>2025-05-24T08:05:05.064Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="The chart outlines steps in fixing a production typo using Git: creating a branch, switching to it, making a fix, committing, switching back to main, and merging the fix." src="https://cdn-images-1.medium.com/max/1024/0*uDVg61JEDTC2s-qE" /></figure><p>Ever feel overwhelmed by the myriad of Git commands and unsure which to reach for when things go wrong? Whether you’re starting a new project or debugging a tricky merge, having a concise reference that not only lists commands but also explains <em>why</em> and <em>when</em> to use them is a game-changer. Below, you’ll find all the essential Git commands — grouped by category — with real-world problems they solve and example scenarios to guide you.</p><h3>1. Basic Workflow</h3><p><strong>Problem:</strong> You’re starting work or picking up a teammate’s code and need to initialize, check status, or share your changes without accidentally missing something important.</p><blockquote><strong><em>Scenario:</em></strong><em> You’ve cloned the UI library and want to add a login screen, but first need to see what’s changed locally and ensure your commits are clean.</em></blockquote><pre>git clone https://github.com/org/ui-library.git     # Copy remote repo locally<br>cd ui-library                                       # Enter project folder<br>git status                                          # Show what’s untracked/modified<br>git add src/LoginScreen.js                          # Stage your new login component<br>git commit -m &quot;feat: add LoginScreen component&quot;     # Commit staged changes<br>git push                                            # Push commits to remote branch</pre><h3>2. Branching &amp; Merging</h3><p><strong>Problem:</strong> You need to isolate new features or hot-fixes without affecting main, and later integrate them cleanly—avoiding “it works on my machine” headaches.</p><blockquote><strong><em>Scenario:</em></strong><em> Mid-feature, a critical typo is found in production. You need to switch context, fix it, then merge back safely.</em></blockquote><pre>| Command                             | Use Case                                      |<br>|-------------------------------------|-----------------------------------------------|<br>| `git branch hotfix/typo`            | Create a bug-fix branch separate from `main`  |<br>| `git switch hotfix/typo`            | Move into the hotfix branch                   |<br>| *Make your fix…*                    | Edit files to correct the typo/bug            |<br>| `git add .`                         | Stage the typo correction                     |<br>| `git commit -m &quot;fix: correct typo&quot;` | Commit the fix                                |<br>| `git switch main`                   | Return to the `main` branch                   |<br>| `git merge hotfix/typo`             | Integrate hotfix into `main`                  |<br>| `git push origin main`              | Push updated `main` to remote (deploy fix)    |</pre><h3>3. Viewing History &amp; Diffs</h3><p><strong>Problem:</strong> You’re about to push code but aren’t 100% sure what you’ve changed, or you need to audit someone else’s last edits.</p><blockquote><strong><em>Scenario:</em></strong><em> Before a release, inspect exactly what changed in </em><em>App.js and see the last few commits for context.</em></blockquote><pre>git diff App.js                       # Show unstaged edits in App.js<br>git add App.js                        # Stage the file<br>git diff --staged App.js              # Verify staged diff before commit<br>git log --oneline --graph            # Quick visual of commit history<br>git show 8f3c2b                       # Inspect commit 8f3c2b in detail</pre><h3>4. Undo &amp; Reset</h3><p><strong>Problem:</strong> You staged or committed something prematurely, made local edits you want to discard, or need to back out of a bad merge — without wrecking your repo.</p><blockquote><strong><em>Scenario:</em></strong><em> You accidentally staged unfinished work in </em><em>src/feature.js and need to remove it from staging without touching other files.</em></blockquote><pre>| Command                           | Use Case                                                            |<br>| --------------------------------- | ------------------------------------------------------------------- |<br>| `git reset HEAD src/feature.js`   | Unstage a specific file you added by mistake                        |<br>| `git checkout -- src/legacy.html` | Discard local edits and revert `src/legacy.html` to last commit     |<br>| `git revert 5a1d2c`               | Safely undo the effects of commit `5a1d2c` by creating a new commit |<br>| `git reset --hard origin/main`    | Destroy all local changes and sync exactly with remote `main`       |</pre><blockquote><strong><em>Warning:</em></strong><em> </em><em>--hard resets permanently discard uncommitted work—use with caution.</em></blockquote><h3>5. Stashing</h3><p><strong>Problem:</strong> You’re midway through a feature but must urgently switch branches for a quick fix — without committing half-baked code.</p><blockquote><strong><em>Scenario:</em></strong><em> A production bug pops up while you’re refactoring. Save your WIP, handle the bug, then restore your work.</em></blockquote><pre>git stash                     # Save current dirty state<br>git switch main               # Switch to main branch to fix bug<br># …apply and commit hotfix…<br>git switch feature/refactor   # Return to your feature branch<br>git stash pop                 # Restore saved changes and drop the stash</pre><h3>6. Remote Repositories</h3><p><strong>Problem:</strong> You need to coordinate work with teammates across forks, add or remove remotes, and ensure your branches track properly — avoiding “I pushed but no one sees my branch” frustration.</p><blockquote><strong><em>Scenario:</em></strong><em> You’ve finished a feature and want to push it to a new remote branch for review, then clean up stale branches later.</em></blockquote><pre>git remote -v                                  # List configured remotes<br>git remote add origin git@github.com:you/proj.git  # Add a new remote URL<br>git push -u origin feature/new-widget          # Push branch and set it to track upstream<br>git pull origin release/v1.2                   # Fetch &amp; merge a specific remote branch<br>git push origin --delete old-branch            # Delete a branch on the server</pre><h3>7. Tagging &amp; Releases</h3><p><strong>Problem:</strong> You need to mark specific points in history as releases or versions — so CI/CD pipelines and package managers pick up the right code.</p><blockquote><strong><em>Scenario:</em></strong><em> You’re ready to ship version 2.0.0, complete with release notes.</em></blockquote><pre>git tag -a v2.0.0 -m &quot;Release v2.0.0: major refactor and new API&quot;  # Annotated tag<br>git push origin v2.0.0                                             # Push single tag<br>git push --tags                                                    # Push all tags</pre><h3>8. File-Specific Utilities</h3><p><strong>Problem:</strong> You only want to examine or restore a single file from another branch or commit — without disturbing the rest of your working tree.</p><blockquote><strong><em>Scenario:</em></strong><em> Your local </em><em>config.yml got corrupted. You need the stable version from </em><em>prod without switching branches entirely.</em></blockquote><pre>git diff dev..prod -- config.yml    # Compare config.yml between branches<br>git log -- config/migrations/       # Audit changes in migrations folder<br>git checkout prod -- config.yml     # Overwrite local config.yml with version from prod</pre><h3>Final Thoughts</h3><p>By pairing each command with the <em>problem</em> it solves and a concrete scenario, this cheat sheet becomes more than a reference — it’s a decision-making guide. Bookmark it, print it out, or add it to your editor’s snippets. As you gain experience, you’ll build on these foundations with aliases, hooks, and advanced workflows, but this core set will carry you through daily Git challenges with confidence.</p><p>Happy coding guys !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df72b0d1f13a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Pre-request and Post-request Scripts in Postman for Enhanced API Testing]]></title>
            <link>https://medium.com/@kosalpen99/mastering-pre-request-and-post-request-scripts-in-postman-for-enhanced-api-testing-9a41a5de6eec?source=rss-4124e0738090------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a41a5de6eec</guid>
            <dc:creator><![CDATA[Kosal Pen]]></dc:creator>
            <pubDate>Fri, 03 Jan 2025 03:50:28 GMT</pubDate>
            <atom:updated>2025-01-03T03:50:28.546Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*-NePfdpFE2xOLQeL.png" /></figure><blockquote>In API testing, automating tasks before sending a request and after receiving a response can significantly enhance efficiency and accuracy. Postman, a popular API testing tool, supports both Pre-request and Post-request Scripts, allowing you to automate these tasks using JavaScript. In this article, I will guide you through using both types of scripts to optimize your API testing workflow.</blockquote><h3>Pre-request Scripts: Setting Up Your API Requests</h3><p>Pre-request Scripts in Postman are executed just before a request is sent. This allows you to dynamically modify the request parameters, headers, and body or set variables based on custom logic.</p><h4>Step 1: Setup Your Request</h4><p>Prepare your API request by configuring the endpoint, method, and any headers or body data you might initially need.</p><h4>Step 2: Write the Pre-request Script</h4><p>Navigate to the Pre-request Script tab next to the request settings. Here, you can write JavaScript to execute before the request is sent. For example, you might want to set a timestamp:</p><pre>// Set a variable &#39;timestamp&#39; with the current time<br>pm.environment.set(&quot;timestamp&quot;, new Date().toISOString());</pre><h4>Step 3: Use the Variable in Your Request</h4><p>Incorporate the variable into your request headers, URL, or body. For instance, add a header:</p><pre>X-Timestamp: {{timestamp}}</pre><h3>Post-request Scripts: Processing API Responses</h3><p>Post-request Scripts are used to handle tasks after a response is received. These scripts are ideal for validating response data, setting variables based on the response, or conditionally triggering other requests.</p><h4>Step 1: Write Your Post-request Script</h4><p>In the Tests tab of the same request, write scripts that will process the received response. For instance, validate the response status and extract data:</p><pre>// Validate the response status<br>pm.test(&quot;Status test&quot;, function () {<br>    pm.response.to.have.status(200);<br>    console.log(&quot;Response is 200 OK&quot;);<br>});<br><br>// Extract and log data<br>pm.test(&quot;Extract Data&quot;, function() {<br>    var jsonData = pm.response.json();<br>    pm.environment.set(&quot;extractedData&quot;, jsonData.key);<br>});</pre><h4>Step 2: Execute and Validate</h4><p>Run your API request and check the “Test Results” tab to view the outcomes of your scripts and any console logs.</p><h3>Best Practices and Tips</h3><ul><li><strong>Reuse Variables</strong>: Use environment and global variables to reuse data across multiple requests.</li><li><strong>Modular Testing</strong>: Break your tests into small, modular scripts for easier maintenance.</li><li><strong>Debugging</strong>: Use console.log to debug and track script executions in Postman’s console.</li></ul><h3>Conclusion</h3><p>Pre-request and Post-request Scripts in Postman provide a robust way to automate and streamline your API testing processes. By mastering these scripts, you can preconfigure requests dynamically and validate responses effectively, ensuring a comprehensive testing workflow that adapts to complex API scenarios.</p><p>Enhance your API testing with these scripting capabilities in Postman and notice significant improvements in your testing efficiency and accuracy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a41a5de6eec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamlining User Experience with Swift and Lottie Animations]]></title>
            <link>https://medium.com/@kosalpen99/streamlining-user-experience-with-swift-and-lottie-animations-b5f90be307f1?source=rss-4124e0738090------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5f90be307f1</guid>
            <dc:creator><![CDATA[Kosal Pen]]></dc:creator>
            <pubDate>Tue, 17 Dec 2024 02:43:24 GMT</pubDate>
            <atom:updated>2024-12-17T02:45:39.590Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*M0wbmJVY0SmwKvtMKisy6A.png" /></figure><h3>Introduction</h3><p>Incorporating smooth animations can significantly enhance user interaction in mobile apps. Using Swift and Lottie, developers can create rich, dynamic interfaces. The “ticket-queue-animation” project is an excellent example of this integration.</p><h3>Exploring the Code</h3><p>The TicketQueueViewController in Swift uses Lottie animations to display a queue animation system. The controller manages the animation views and updates the UI based on a timer to show the progress in a queue system visually.</p><h3>Key Implementation</h3><pre>import UIKit<br>import Lottie<br><br>final class TicketQueueViewController: UIViewController {<br>    @IBOutlet private weak var animationView: LottieAnimationView!<br>    private var widthConstraint: NSLayoutConstraint!<br>    private let updateInterval = 0.1<br>    private var elapsedTime: Double = 0<br>    private var totalDuration: Double = .zero<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        configureLottie()<br>    }<br><br>    private func configureLottie() {<br>        animationView.animation = LottieAnimation.named(&quot;queue-animation&quot;)<br>        animationView.loopMode = .loop<br>        animationView.play()<br>    }<br>}</pre><p>This snippet initializes and configures a Lottie animation within a view controller, ensuring the animation plays in a loop.</p><h3>Conclusion</h3><p>Integrating Lottie with Swift allows for implementing complex animations efficiently and effectively, enhancing both the aesthetic appeal and functionality of iOS applications.</p><p>This article provides insights into the integration of animations in Swift applications, emphasizing the ease of use provided by Lottie. You can find more detailed implementation details on the GitHub repository: <a href="https://github.com/kosalpen11/ticket-queue-animation/blob/main/TicketQueueAnimation/ViewController/TicketQueue/TicketQueueViewController.swift">ticket-queue-animation</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5f90be307f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift UI Development: Choosing Between Interface Builder and Programmatic Approaches]]></title>
            <link>https://medium.com/@kosalpen99/swift-ui-development-choosing-between-interface-builder-and-programmatic-approaches-ffc147b7beb1?source=rss-4124e0738090------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffc147b7beb1</guid>
            <dc:creator><![CDATA[Kosal Pen]]></dc:creator>
            <pubDate>Fri, 06 Dec 2024 15:18:48 GMT</pubDate>
            <atom:updated>2024-12-06T15:18:48.047Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In the vibrant world of iOS development, creating an intuitive and visually appealing interface is pivotal for the success of any application. Swift developers are often faced with a crucial decision early in the development process: Should they opt for Interface Builder with its convenient visual tools like Storyboards and XIBs, or should they dive into creating UI elements purely through code? This decision influences not only the development time and effort but also impacts the app’s flexibility and scalability. This article delves into the pros and cons of each approach, guiding you on when to choose one over the other based on various app types and providing real-world case studies to anchor these concepts in practical scenarios.</p><h3>What is Interface Builder?</h3><p>Interface Builder is a graphical tool that allows developers to craft their app’s user interfaces visually. Integrated within Xcode, it supports the use of Storyboards and XIB files which are XML-based interface files. These tools enable developers to layout screens and define the flow between them without writing extensive UI code.</p><pre>import UIKit<br><br>class InterfaceBuilderViewController: UIViewController {<br><br>    @IBOutlet weak var label: UILabel!<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        // Additional setup after loading the view.<br>    }<br><br>    @IBAction func buttonTapped(_ sender: UIButton) {<br>        label.text = &quot;Hello from Interface Builder!&quot;<br>    }<br>}</pre><h3>Pros:</h3><ul><li><strong>Visual Layout</strong>: Quickly assemble and visualize screens without running the app.</li><li><strong>Ease of Use</strong>: More accessible for teams with designers or developers less comfortable with Swift syntax.</li><li><strong>Speed</strong>: Accelerate UI development, especially for straightforward designs.</li></ul><h3>Cons:</h3><ul><li><strong>Merge Conflicts</strong>: Can lead to cumbersome merge conflicts in version control systems when used in larger teams.</li><li><strong>Limited Flexibility</strong>: Complex dynamic behaviors can be hard to implement and manage.</li></ul><h3>What is Programmatic UI?</h3><p>A programmatic approach involves manually coding every UI element and constraint. This method gives developers complete control over behaviors and styles, often leading to more dynamic and flexible user interfaces.</p><pre>import UIKit<br><br>class ProgrammaticUIViewController: UIViewController {<br><br>    let label = UILabel()<br>    let button = UIButton()<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        setupUI()<br>    }<br><br>    func setupUI() {<br>        // Label setup<br>        label.frame = CGRect(x: 20, y: 100, width: 300, height: 40)<br>        label.text = &quot;Hello, World!&quot;<br>        view.addSubview(label)<br><br>        // Button setup<br>        button.frame = CGRect(x: 20, y: 150, width: 300, height: 40)<br>        button.backgroundColor = .blue<br>        button.setTitle(&quot;Tap Me!&quot;, for: .normal)<br>        button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)<br>        view.addSubview(button)<br>    }<br><br>    @objc func buttonTapped() {<br>        label.text = &quot;Hello from Code!&quot;<br>    }<br>}</pre><h3>Pros:</h3><ul><li><strong>Complete Control</strong>: Fine-grained control over UI elements and interactions.</li><li><strong>Scalability</strong>: Easier to manage for large scale applications with complex interactions.</li><li><strong>Version Control Friendly</strong>: Simplifies dealing with version control systems like Git.</li></ul><h3>Cons:</h3><ul><li><strong>Steep Learning Curve</strong>: Requires a deep understanding of Swift and UI frameworks.</li><li><strong>Time-Consuming</strong>: Generally takes longer to set up and adjust complex layouts.</li></ul><h3>Choosing the Right Approach</h3><p>Deciding between Interface Builder and programmatic UI depends on several factors such as the project’s scale, the team’s expertise, the complexity of the UI, and the app’s maintenance needs. Here’s how different app types might influence your choice:</p><h3>Content-Driven Apps</h3><p><strong>Example</strong>: News platforms, blogs. <strong>Approach</strong>: Interface Builder is often suitable here due to static content layouts that benefit from quick drag-and-drop design.</p><h3>Highly Dynamic Apps</h3><p><strong>Example</strong>: Social media, interactive games. <strong>Approach</strong>: Programmatic UI shines as it accommodates complex, frequently changing interfaces that respond to user interactions or data.</p><h3>Enterprise Apps</h3><p><strong>Example</strong>: Internal business systems, customer relationship management tools. <strong>Approach</strong>: A hybrid approach can be effective, using Storyboards for generic layouts and code for customized interactions.</p><h3>Case Studies</h3><ul><li><strong>A social media app</strong>: Used a programmatic approach to handle custom gestures and dynamic layouts efficiently.</li><li><strong>An e-commerce platform</strong>: Employed Interface Builder to speed up the creation of multiple product screens with similar layouts.</li></ul><h3>Conclusion</h3><p>The decision between using Interface Builder and crafting UIs programmatically in Swift isn’t straightforward and depends heavily on specific project requirements and team dynamics. While Interface Builder can offer speed and simplicity for static content, programmatic UI provides unparalleled flexibility for managing dynamic and complex interfaces. Understanding the strengths and limitations of each method enables developers to make choices that align best with their strategic goals, ultimately leading to the development of superior iOS applications.</p><h3>Further Reading</h3><ul><li><a href="https://developer.apple.com/documentation">Apple’s Interface Builder Documentation</a></li><li>Swift Documentation on Programmatic UI</li></ul><p>By considering these insights and examples, iOS developers can navigate the decision-making process more effectively, ensuring their development approach aligns well with their project’s needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffc147b7beb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding print vs NSLog in Swift]]></title>
            <link>https://medium.com/@kosalpen99/understanding-print-vs-nslog-in-swift-416dc7fddd89?source=rss-4124e0738090------2</link>
            <guid isPermaLink="false">https://medium.com/p/416dc7fddd89</guid>
            <dc:creator><![CDATA[Kosal Pen]]></dc:creator>
            <pubDate>Tue, 03 Dec 2024 04:56:07 GMT</pubDate>
            <atom:updated>2024-12-03T04:56:07.406Z</atom:updated>
            <content:encoded><![CDATA[<h4>Logging is an essential tool for debugging and monitoring applications. In Swift, two commonly used methods for logging are print and NSLog. Let’s explore their differences and when to use each.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UQe4wyR4wdrIWILD" /></figure><h3>What is print in Swift?</h3><p>The print function is a simple way to log messages to the Xcode console. It is lightweight and perfect for temporary debugging during development.</p><h3>Features of print</h3><ul><li><strong>Debug Only</strong>: Messages appear only in the Xcode console during development and are not stored or visible in system logs.</li><li><strong>Lightweight</strong>: Faster than NSLog, but lacks timestamps and thread information.</li><li><strong>String Interpolation</strong>: Easily include variables in log messages using Swift string interpolation.</li></ul><h3>Example of print</h3><pre>let userName = &quot;John&quot;<br>print(&quot;User logged in: \(userName)&quot;)</pre><h3>When to Use print</h3><ul><li>For quick debugging during development.</li><li>When you don’t need persistent or detailed logs.</li></ul><h3>What is NSLog in Swift?</h3><p>NSLog is a more robust logging method inherited from Objective-C. It logs messages to both the Xcode console and the system log, making it suitable for production use.</p><h3>Features of NSLog</h3><ul><li><strong>Timestamps and Thread Info</strong>: Automatically adds timestamps and thread details to log messages.</li><li><strong>System Log Persistence</strong>: Messages are stored in system logs and can be accessed via the Console app or crash reports.</li><li><strong>Objective-C Style Formatting</strong>: Uses formatting like %@ instead of Swift’s string interpolation.</li></ul><h3>Example of NSLog</h3><pre>let userName = &quot;John&quot;<br>NSLog(&quot;User logged in: %@&quot;, userName)</pre><h3>When to Use NSLog</h3><ul><li>For logging critical events or errors in production.</li><li>When you need persistent logs accessible outside of Xcode.</li></ul><h3>Comparison Table</h3><pre>| **Feature**           | **print**                       | **NSLog**                           |<br>|-----------------------|---------------------------------|-------------------------------------|<br>| **Output Location**   | Xcode console only              | Xcode console + system logs         |<br>| **Timestamps**        | No                              | Yes                                 |<br>| **Thread Info**       | No                              | Yes                                 |<br>| **Performance**       | Faster (lightweight)            | Slower (writes to system logs)      |<br>| **Production Logs**   | No                              | Yes                                 |<br>| **Formatting Style**  | Swift string interpolation      | Objective-C formatting (`%@`, `%d`) |</pre><h3>Modern Alternative: OSLog</h3><p>For better performance and structured logging, Apple introduced OSLog in iOS 10 and macOS 10.12. It’s optimized for both development and production.</p><h3>Using OSLog</h3><pre>import os<br>let logger = Logger(subsystem: &quot;com.example.myapp&quot;, category: &quot;network&quot;)<br>logger.info(&quot;Network request started&quot;)</pre><h3>Benefits of OSLog</h3><ul><li>Optimized for performance.</li><li>Logs can be filtered by subsystem or category.</li><li>Structured for better diagnostics.</li></ul><h3>Best Practices</h3><ol><li><strong>Use </strong><strong>print</strong>:</li></ol><ul><li>For quick, temporary debugging during development.</li></ul><ol><li><strong>Use </strong><strong>NSLog</strong>:</li></ol><ul><li>For persistent logs or critical events in production.</li></ul><ol><li><strong>Use </strong><strong>OSLog</strong>:</li></ol><ul><li>For structured, performance-optimized logging in modern Swift applications.</li></ul><h3>Conclusion</h3><p>Both print and NSLog are valuable tools, but they serve different purposes. Use print for simple debugging during development and NSLog or OSLog for more detailed logging in production. Choosing the right tool for the job ensures better debugging and monitoring for your applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=416dc7fddd89" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>