<?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 Essam Fahmy on Medium]]></title>
        <description><![CDATA[Stories by Essam Fahmy on Medium]]></description>
        <link>https://medium.com/@essammohamedomran?source=rss-f97cf1a05be4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jd1vpXriqb7Fmz5gRZa7Ng.jpeg</url>
            <title>Stories by Essam Fahmy on Medium</title>
            <link>https://medium.com/@essammohamedomran?source=rss-f97cf1a05be4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 10:07:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@essammohamedomran/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[How to Make Your Mobile App Faster]]></title>
            <link>https://medium.com/deloitte-uk-cloud-blog/how-to-make-your-mobile-app-faster-2fd1be7f503a?source=rss-f97cf1a05be4------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fd1be7f503a</guid>
            <category><![CDATA[mobile-app-performance]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[mobile-and-front-end]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Essam Fahmy]]></dc:creator>
            <pubDate>Mon, 16 Mar 2026 13:01:02 GMT</pubDate>
            <atom:updated>2026-05-07T17:44:10.991Z</atom:updated>
            <content:encoded><![CDATA[<p>From instant performance gains to behind-the-scenes engineering tricks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e9bWwdSkQZNgCUzjBeXiVA.png" /><figcaption>How to Make Your Mobile App Faster. <em>Image generated by ChatGPT (OpenAI).</em></figcaption></figure><blockquote>We usually don’t think about app performance when everything works smoothly. But the moment an app takes a few seconds too long to load, frustration kicks in, and users leave.</blockquote><p>And honestly, it’s not just users; even during development, performance is rarely at the top of people’s minds. In most teams, the mindset is “get it working first, optimise later <em>if</em> we need to”. Performance becomes an afterthought… until it’s suddenly the thing everyone panics about.</p><p><strong><em>Some quick facts:</em><br>• <em>According to a 2025 snapshot, the two major stores now list ≈ 2.12 million apps on Google Play Store and ≈ 2.05 million apps on Apple App Store </em></strong><a href="https://42matters.com/stats"><strong><em>(42matters, 2025).</em></strong></a><strong><em><br>• 70% of users quit an app if it takes too long to load </em></strong><a href="https://www.outerboxdesign.com/articles/digital-marketing/progressive-web-apps-pwas/"><strong><em>(OuterBox Design, 2024).</em></strong></a><strong><em><br>• 40% move to competitors after a bad mobile experience </em></strong><a href="https://www.outerboxdesign.com/articles/digital-marketing/progressive-web-apps-pwas/"><strong><em>(OuterBox Design, 2024).</em></strong></a><strong><em><br>• 80% uninstall an app if it fails them three times or less </em></strong><a href="https://moldstud.com/articles/p-top-mistakes-to-avoid-during-android-app-development-and-launch-expert-tips-for-success"><strong><em>(MoldStud, 2025).</em></strong></a><strong><em><br>• Almost half of the apps are uninstalled within the first month </em></strong><a href="https://www.outerboxdesign.com/articles/digital-marketing/progressive-web-apps-pwas/"><strong><em>(OuterBox Design, 2024).</em></strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*41cmJzL3aaI2izOG.gif" /><figcaption>When users leave a slow app. Homer Simpson backing into bushes, GIF from GIPHY.</figcaption></figure><blockquote>The million-dollar question then: how do we make our mobile app faster?</blockquote><p><strong>There are two broad categories of ways to do this:</strong></p><ol><li><strong><em>Making speed improvements users can feel immediately:</em></strong> caching data, optimising images, and reducing app launch times. These are the optimisations that shape a user’s very first impression.</li><li><strong><em>Playing with the behind-the-scenes work,</em> </strong>including writing efficient code, optimizing client-server interactions, and monitoring performance in real-world conditions. These practices ensure that your app remains reliable and scalable long after its launch.</li></ol><p>In this article, we’ll look at a few practical techniques from both sides that can help make your mobile app faster and more reliable.</p><p><strong><em>Table of Contents:<br>1. Cache Data Effectively<br>2. Optimize Images<br>3. Speed Up App Launch<br>4. Keep Code Clean and Efficient<br>5. Optimize Client-Server Interaction<br>6. Monitor with Observability<br>7. Resources</em></strong></p><h3>Cache Data Effectively</h3><p>Caching is one of the easiest ways to improve speed. This means storing data on the device so the app doesn’t need to fetch it from the server each time.</p><h4>Types of caching:</h4><ul><li><strong><em>In-memory caching (RAM)</em> </strong><br> <br>This is when you store recently accessed data in memory using tools like NSCache (iOS) or LruCache (Android).<br> <br>But not <em>everything</em> benefits equally; for example, cached text or small JSON objects won’t magically make the UI feel faster. Where it really shines is <strong>media-heavy content</strong>, especially images.<br> <br><strong>Think about how Instagram loads:</strong> when you scroll through your feed, the app pulls images from memory if you recently viewed them. This avoids refetching or redecoding large assets. <strong><em>The result?</em></strong> <strong>Smooth, uninterrupted scrolling</strong> even through image-heavy lists.</li><li><strong><em>Disk caching (persistent storage)</em></strong><em> </em><br> <br>Here, data is stored on the device in a more permanent way using SQLite, Core Data, Room, or a similar framework. This reduces repeated network calls <em>and</em> gives your app offline access. <br> <br><strong>A simple real-world example:</strong> A news app may locally store the latest fetched articles. Even if the user opens the app without an internet connection, they can still browse the most recently synced content. When the connection returns, the app refreshes only the changed data instead of downloading everything again. This greatly improves perceived speed and reduces server load.</li></ul><h4>Cache Invalidation Strategies</h4><p>Keeping cached data fresh is as important as caching data itself; we don’t want users to see old data when they’re expecting new data or updates in the app. Thus, we use conditional caching:</p><ul><li><strong><em>Time-based:</em></strong> Refresh data after a set duration.</li><li><strong><em>Event-based:</em></strong> Clear cache when specific events occur, maybe it is an event related to your project’s business, or the server could indicate to us that the data has changed.</li><li><strong><em>Version-based:</em></strong> Invalidate cache when the app or API version changes.</li></ul><p>A clean caching layer typically sits between the <strong>network</strong> and <strong>repository</strong> layers to ensure the UI always gets the fastest available data, while background tasks update it silently when needed:</p><pre>Network → Cache → Repository → ViewModel → UI</pre><h4>Security Considerations</h4><p>While caching improves performance, it can also introduce risks if the cached data includes anything sensitive. Not all cached information needs protection (e.g., public images or non-personal metadata), but some types do, especially anything tied to a specific user (i.e., personally identifiable information (PII)) or account. In these cases, security must also be integrated into our caching strategy.</p><ul><li><strong><em>Use secure storage (Keychain and EncryptedSharedPreferences)</em></strong> <br> <br><strong>Best for:</strong> authentication tokens, refresh tokens, session identifiers, or anything long-lived and sensitive. These storages offer OS-level encryption and access control, ensuring sensitive credentials aren’t exposed even if the device is compromised.</li><li><strong><em>Encrypt disk caches when they hold personal data</em></strong><em> </em><br> <br><strong>Best for:</strong> offline user profiles, chat history, private documents, or cached API responses containing personal data. Files stored on disk are more easily inspected, so encryption protects the data even if someone gains filesystem access.</li><li><strong><em>Clear cached data when the user logs out or switches accounts</em></strong> <br> <br><strong>Best for:</strong> any app supporting multiple accounts or shared-device usage to prevent cross-account data exposure. User B should never see User A’s cached content, even unintentionally.</li></ul><p>This ensures your caching system stays both fast <em>and</em> safe.</p><h4>Pro tips:</h4><ul><li><strong><em>Cache changes that occur rarely</em></strong> (e.g., app configuration, user preferences). These values are stable and don’t require frequent network calls. Caching them avoids unnecessary API hits. Examples include feature flags, theme settings, language choice, and remote config values.</li><li><strong><em>Don’t over-cache;</em></strong> large caches waste storage and slow down access time. Caching everything increases disk usage and can degrade performance as reading large cache files takes longer. Also, excessive caching may lead to <strong>cache thrashing</strong>, where frequently evicted items are repeatedly re-fetched. This creates extra network requests, higher CPU usage, and slower app performance. <br> <br><strong>Rule of thumb:</strong> Cache only the data that meaningfully improves user experience. For example, media, feed items, or app configurations rather than every API response.</li><li><strong><em>Not all API responses should be cached.</em></strong> It depends on the business needs and how it impacts user experience. <strong>For example,</strong> news articles or product listings are good to cache, but real-time prices and live match scores are not supposed to be cached.</li></ul><h3>Optimise Images</h3><p>Images are the <strong>biggest contributors to slow apps</strong>. They take time to load, consume bandwidth, and use memory.</p><h4>Best practices:</h4><ul><li><strong><em>Resize Before Upload</em></strong><em> </em><br> <br>Uploading full resolution (e.g., 4032×3024) camera images is unnecessary most of the time. What we can often do is resize them to the dimensions in which they will be presented to the user. For example, scaling down full-resolution images to 1080px x 1080px.<br> <br><strong>This can be done by:<em> </em><br></strong><em> — iOS: UIImage → .jpegData(compressionQuality:)<br> — Android: Use Bitmap scaling or libraries like Coil / Glide.</em></li><li><strong><em>Compress Images</em></strong><em> </em><br> <br>Compression reduces image size with minimal visual loss. JPEG compression at a quality level of (0.7–0.8) typically achieves optimal file size reduction with minimal perceptual loss <a href="https://developers.google.com/speed/docs/insights/OptimizeImages"><em>(Google Developers, 2024).</em></a><br> <br>You can also use modern compression libraries if needed (e.g., TinyPNG API, ImageMagick) before uploading.</li><li><strong><em>Use Modern Image Formats</em></strong><em> (HEIC/WebP/AVIF).</em><br> <br><strong>This can be done by:<em> </em><br></strong><em> — iOS: Capture in HEIC (default) → convert to JPEG only if needed<br> — Web/Android: Prefer WebP or AVIF for product images.</em></li><li><strong><em>Lazy Load Images </em></strong><br> <br>Lazy-loading is a concept whereby resources are only fetched at the exact moment they’re needed. In the context of images, the fetching of these images can be delayed until they enter the view, reducing unnecessary network and memory usage.<br> <br>This improves scrolling performance and speeds up initial screen load, especially in image-heavy feeds.<br> <br><strong>Potential Downside:</strong> While lazy loading improves performance, it introduces a few considerations, as users may briefly see placeholders or blank areas if images load too slowly. Also, the critical images should still be preloaded for immediate visibility, so the best practice is to lazy-load non-critical content.<br> <br><strong><em>For iOS: </em></strong><em>Use lazy containers combined with asynchronous image loading so assets load only when cells appear:<br>- LazyVStack / LazyHStack in SwiftUI<br>- List with AsyncImage or custom loaders with caching</em><br> <br><strong><em>For Android:</em></strong><em> Use recycling containers with smart image loaders:<br>- RecyclerView for efficient view reuse<br>- Libraries like </em><strong><em>Coil</em></strong><em>, </em><strong><em>Glide</em></strong><em>, or </em><strong><em>Picasso,</em></strong><em> which load images only when views are visible, cancel in-flight requests when items scroll off-screen, and integrate memory + disk caching automatically</em></li></ul><blockquote><strong><em>Remember:</em></strong><em> Don’t fetch a 2000px photo to display a 200px thumbnail. If we are building an e-commerce app, product thumbnails should be pre-compressed and sized correctly.</em></blockquote><h4>Use a CDN to Deliver Images Faster</h4><p>A Content Delivery Network (CDN) is a globally distributed network of servers that stores cached copies of your images. Instead of every user downloading images from your main server (which might be far away), a CDN serves them from a location close to the user. This reduces latency, increases download speeds, and lowers your backend load.</p><p>CDNs not only theoretically improve performance, but they also deliver measurable speed gains in real-world usage. In practice, serving images through a CDN combined with automatic resizing and modern formats such as WebP or AVIF can reduce image load times by <strong>40–70%</strong> while significantly lowering payload sizes <a href="https://developers.cloudflare.com/images/polish/compression/"><em>(Cloudflare, 2024).</em></a></p><p>By serving content from geographically closer servers and dynamically generating right-sized images, CDNs minimize latency, bandwidth consumption, and decoding overhead on mobile devices, resulting in smoother scrolling and a more responsive user experience, particularly on slower networks (<a href="https://developers.cloudflare.com/images/polish/compression/"><em>Cloudflare, 2024;</em></a><em> </em><a href="https://developers.google.com/speed/docs/insights/OptimizeImages"><em>Google Developers, 2024</em></a>).</p><p><strong>Why CDNs Make Mobile Apps Faster</strong></p><ul><li><strong><em>Lower latency:</em></strong> Images load from the nearest geographic server.</li><li><strong><em>Higher reliability:</em></strong> CDNs are built to handle heavy traffic and spikes.</li><li><strong><em>Automatic optimization:</em></strong> Many CDNs can resize, compress, and convert images to efficient formats like WebP/AVIF, offloading work from your API and the backend team can focus on logic, not file serving.</li></ul><p>All of this leads to faster image loading, smoother scrolling, and a more responsive UI, especially on slower networks. We take advantage of these CDN benefits by requesting optimised versions of each image using URL parameters. Instead of downloading the full-resolution file, the CDN generates a resized, compressed version on the fly based on parameters like width, quality, or format. For example, the app might request:</p><pre>https://cdn.example.com/product/123?w=200&amp;q=70&amp;format=webp</pre><p>This ensures the device only downloads the exact size it needs for the UI, reducing bandwidth, memory usage, and decoding time without extra logic inside the app.</p><h4>Pro tips:</h4><ul><li><strong>Test on older devices,</strong> low memory + big images = crashes.</li><li><strong>Apply caching</strong> for images used repeatedly.</li></ul><h3>Speed Up App Launch</h3><blockquote>First impressions matter. Nearly half of users expect an app to launch in two seconds or less.</blockquote><h4>Understanding App Startup Types:</h4><p>The speed at which an app launches greatly affects first impressions, user retention, and engagement. To optimize launch performance effectively, it helps to understand the three main startup types:</p><ul><li><strong><em>Cold start:</em></strong> App starts fresh (most resource-heavy) <br> <br>In a cold app launch, your app is starting from scratch. This means that the app’s process has not been created by the system until then; this is a time-consuming process for the phone’s operating system, as memory must be allocated, old resources evicted to make space for that memory, etc.</li><li><strong><em>Warm start:</em></strong> App was closed but still in memory <br> <br>In a warm start, the app was backgrounded long enough for the system to kill it, but not long enough to be totally evicted, or the user had left the app recently. So, the OS was able to reclaim parts of the application that still exist in memory, most typically the previously used code pages, cached resources, compiled bytecode, and some system-level memory mappings. The OS can reuse these preloaded components, allowing the app to avoid repeating expensive initialization work.</li><li><strong><em>Hot start:</em></strong> App is already running in the background <br> <br>A hot start occurs when the app process is still active in the background. The system restores it immediately: the activity/view controller tree, in-memory objects, UI state, and app logic are all already loaded. The app just needs to resume from its suspended state, making it nearly instantaneous.</li></ul><h4>Ways to reduce launch time:</h4><ul><li><strong><em>Initialise only critical services (auth, configs) at startup</em></strong> (e.g., auth, configs): Reduces the workload during cold starts, so the app reaches the first screen faster.</li><li><strong><em>Defer analytics, ads, or logs until after launch:</em></strong> Minimizes background work during cold and warm starts, allowing the UI to load smoothly.</li><li><strong><em>Simplify the first screen layout</em></strong> (less nesting, lighter UI): Speeds up rendering across all startup types, especially noticeable in cold starts.</li><li><strong><em>Batch network requests</em></strong> (fetch headlines + user settings in one call): Reduces total network latency, benefiting cold and warm starts on multiple requests.</li><li><strong><em>Use placeholders for images until real data is ready:</em> </strong>Improves perceived load time during cold and warm starts.</li><li><strong><em>Optimize assets:</em> </strong>pre-load small icons and critical images. Ensures that even hot starts feel snappy and responsive.</li></ul><blockquote><strong>Example:</strong> A news app that takes several seconds to launch can significantly improve its startup time by deferring non-critical initialization and caching frequently accessed data, such as top headlines.</blockquote><h4>Pro tips:</h4><ul><li>On <strong>iOS</strong>, apps that take longer than <strong>20 seconds to launch</strong> get killed by the system.</li><li>On <strong>Android, Google</strong> suggests keeping cold start <strong>under 5 seconds</strong>.</li><li><strong>Splash screens</strong> don’t reduce load time but <strong>make the wait feel smoother</strong>.</li></ul><h3>Keep Code Clean and Efficient</h3><blockquote>Poorly written code = slow, buggy apps. Regular code hygiene is essential.</blockquote><h4>Best practices:</h4><ul><li><strong><em>Update libraries:</em> </strong>Use the latest SDKs for security and performance.<br> <br>Keep in touch with your outdated dependencies as they can slow down your app or introduce bugs, and regularly <strong>remove unused dependencies.</strong> Every library increases app size and startup time.</li><li><strong><em>Fix memory leaks:</em></strong> Make sure objects get deallocated when not in use. <br> <br>A memory leak happens when your app keeps objects in memory even after they are no longer needed, and the active scope of your application has no reference to those objects. These objects remain in memory, wasting resources and potentially slowing or crashing the app.</li><li><strong><em>Run heavy tasks off the main thread</em></strong><em> </em><br> <br>Network requests, JSON parsing, or file operations should not block the UI. <strong>For example,</strong> A news app that parses JSON on the main thread may freeze during updates. Moving parsing to a background thread keeps the UI responsive.</li><li><strong><em>Don’t run constant background services unless necessary.</em></strong></li><li><strong><em>Cache and display last-viewed content instead of showing errors.</em></strong></li></ul><p><strong>Example 1: Memory Leak in Swift</strong></p><p><strong>In iOS (Swift),</strong> memory leaks often occur due to strong reference cycles in closures or class references. <strong>In Android (Java/Kotlin),</strong> memory leaks can happen when you keep references to activities, contexts, or views longer than necessary.</p><pre>class ViewController: UIViewController {</pre><pre>    // ViewController holds a reference to the Timer.<br>    var timer: Timer?</pre><pre>    override func viewDidLoad() {<br>        super.viewDidLoad()</pre><pre>        // Strong reference cycle: timer holds self strongly<br>        timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in<br>            self.updateUI()<br>        }<br>    }</pre><pre>    func updateUI() {<br>        print(&quot;Updating UI&quot;)<br>    }<br>}</pre><p><strong>This creates a strong reference cycle:</strong> Because of this cycle, the ViewController never gets deallocated, even when you leave the screen. That’s a memory leak.</p><pre>ViewController → Timer → Closure → ViewController</pre><p><strong>Fixed version using [weak self]:</strong></p><pre>override func viewDidLoad() {<br>    super.viewDidLoad()<br>    <br>    // Weak reference to the view controller. Fixed it!<br>    timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] _ in<br>        self?.updateUI()<br>    }<br>}</pre><p><strong>What changed?</strong></p><p><strong>[weak self] tells the closure: </strong><em>“Don’t hold a strong reference to self. If self goes away, it becomes nil instead of keeping it alive.”</em> Now, when the ViewController is dismissed, it can be deallocated, and the memory is freed.</p><p><strong>Example 2: Freezes UI in Swift</strong></p><pre>let data = try! Data(contentsOf: url) // Blocks main thread<br>let json = try! JSONSerialization.jsonObject(with: data)</pre><p><strong>Efficient version using a background thread:</strong></p><pre>// Start the parsing work on a background thread<br>DispatchQueue.global(qos: .background).async {<br>    if let data = try? Data(contentsOf: url),<br>       let json = try? JSONSerialization.jsonObject(with: data) {</pre><pre>        // Switch back to the main thread to update the UI<br>        DispatchQueue.main.async {<br>            // Update UI with parsed data<br>        }<br>    }<br>}</pre><h4>Pro tips:</h4><ul><li><strong>Use Instruments (iOS) or Android Profiler</strong> to identify bottlenecks.</li><li><strong>Optimize slow methods and memory leaks,</strong> then <strong>re-profile</strong> to confirm.</li><li><strong>Test on all types of devices, </strong>especially low-end ones.</li><li><strong>Refactor regularly:</strong> Old code piles up technical debt.</li></ul><h3>Optimise Client-Server Interaction</h3><blockquote>Apps often fail not because of bad code, but because of poor code concurrency.</blockquote><p><strong><em>Scenario:</em></strong></p><ul><li><em>The mobile app makes </em><strong><em>5 network requests</em></strong><em> to load the main screen.</em></li><li><em>Average network latency per request = </em><strong><em>500 ms</em></strong><em> (0.5 seconds).</em></li><li><em>Each request has a payload of 200 KB.</em></li><li><em>Users consider the app “slow” if the screen takes </em><strong><em>&gt;2 seconds to load</em></strong><em>.</em></li></ul><p><strong>If requests are sequential (one after another):</strong></p><pre>Total network time = 5 network requests × 0.5s / network request = 2.5s</pre><p>Even without considering rendering time, the network alone exceeds the <strong>2-second threshold</strong>, which is enough to make users perceive the app as slow.</p><p><strong>Optimisation opportunity</strong></p><p>If requests are parallelised (all 5 at once), <strong>the total network time ≈ 0.5 s, well below the threshold.</strong> If responses are cached, repeated visits can load instantly (0s network delay).</p><h4>Best practices:</h4><ul><li><strong><em>Focus on fetching only what you need.</em></strong><em> <br></em> <br>Instead of requesting entire datasets, fetch just the data needed for the current screen. <strong>For example,</strong> a travel app should fetch only flight names and prices in the search results. Full details, reviews, and high-resolution images can load later when the user taps a flight.</li><li><strong><em>Server-side filtering and pagination.</em></strong><em><br></em> <br>Never fetch all results and filter locally. Use query parameters on the server to let the server perform the filtering:</li></ul><pre>GET /flights?from=NYC&amp;to=LAX&amp;fields=flightName&amp;page=1&amp;limit=20</pre><p><strong><em>Fields: </em></strong><em>Returns only flight names.</em></p><p><strong><em>Pagination:</em></strong><em> Loads 20 results at a time.</em></p><p>This reduces payload size, speeds up loading, and improves the experience for users on poor networks.</p><ul><li><strong><em>Use CDNs:</em> </strong>Distribute images, videos, and static content closer to the user.</li><li><strong><em>Avoid redirects:</em></strong> Every redirect adds extra latency.</li><li><strong><em>Test on poor networks:</em></strong> Use Network Link Conditioner (iOS) or Android Profiler.</li></ul><h4>Pro tips:</h4><ul><li><strong>Combine multiple requests</strong> into one batch when possible.</li><li><strong>Use concurrent API request</strong> when possible.</li><li><strong>Use caching headers</strong> so repeat requests hit the cache instead of the network.</li><li><strong>Monitor API response times</strong> to spot backend bottlenecks.</li><li><strong>Large payloads not only slow the app</strong> but can drain the battery.</li></ul><h3>Monitor with Observability</h3><blockquote>Performance work doesn’t end at launch; the real test starts when users interact with your app in unpredictable, real-world conditions.</blockquote><p>This is where observability becomes essential. It helps teams detect performance issues early — often before they turn into bad reviews and gives teams the feedback loop they need to continuously improve performance long after release.</p><h4>Key Metrics to Monitor</h4><ul><li><strong><em>Crashes:</em></strong> Use Crashlytics or Sentry to capture errors with stack traces.</li><li><strong><em>Performance metrics:</em></strong> Track launch times, slow screens, and memory usage.</li><li><strong><em>Network latency:</em></strong> Measure API response times, especially during peak hours.</li><li><strong><em>Resource-heavy screens:</em></strong> Identify slow-loading UI (image-heavy, animations).</li><li><strong><em>Battery and memory usage:</em></strong> Watch out for leaks or background processes.</li><li><strong><em>Device &amp; OS distribution:</em></strong> Some issues only appear on older devices.</li><li><strong><em>Cold vs warm launches:</em></strong> Measure them separately; they behave differently.</li><li><strong><em>Offline/poor network:</em></strong> Monitor how your app reacts to unstable connectivity.</li></ul><h4>Crashlytics: The “How” Behind Finding Real Root Causes</h4><p>Crashlytics isn’t just a crash counter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/0*5jrx0bakWs4rXABw.gif" /><figcaption>Realizing there’s more going on than expected. Scene from <em>Twin Peaks</em>. GIF from GIPHY.</figcaption></figure><p><strong>The real power comes from signal + context:</strong></p><ul><li><strong><em>Breadcrumbs </em></strong><br> <br>Automatically logs navigation steps, background/foreground events, and custom logs you add.</li></ul><pre>Crashlytics.log(&quot;Tapped checkout button&quot;)</pre><ul><li><strong><em>Non-fatal errors </em></strong><br> <br>Most performance problems never cause a full crash. <br> <br>You can log request timeouts, decoding errors, failed login attempts, and memory warnings. Over time, you’ll see patterns, e.g.,<em> “80% of timeout errors come from the restaurant list endpoint.”</em></li><li><strong><em>Performance signals </em></strong><br> <br>Crashlytics integrates with Firebase Performance, giving you: <br><strong><em>- slow screen render warnings <br>- ANR-like freezes (Application Not Responding) <br>- cold/warm launch durations</em></strong></li><li><strong><em>User impact heatmap <br></em></strong> <br>You instantly know whether an issue affects 0.1% or 40% of sessions. This helps prioritize what to fix first, instead of guessing.</li></ul><p><strong>Example: </strong>A food delivery app notices spikes in non-fatal errors for the restaurant list. Crashlytics shows that all affected users are on older devices, and the UI thread is blocked for a few seconds during JSON parsing. The team moves parsing off the main thread → the spike disappears.</p><blockquote>A <strong>spike</strong> is a sudden, unusual increase in a metric that normally stays stable, for example, crashes, network errors, timeouts, or slow-screen reports. You usually see it as a sharp jump on your monitoring dashboard.</blockquote><h4>Pro tips:</h4><ul><li><strong>Set up alerts for spikes</strong> in crash rates or non-fatal errors.</li><li><strong>Watch session length:</strong> Drops may indicate performance issues.</li><li><strong>Use logs + metrics</strong> to connect errors to <strong>real user behaviour</strong>.</li></ul><h3>Conclusion</h3><p>Performance is more than just a technical metric; it’s the backbone of user experience. Fast apps feel smooth, reliable, and trustworthy, while slow ones frustrate users and drive them away. <strong>By combining user-facing optimizations</strong> like caching, image management, and launch improvements <strong>with solid engineering practices</strong> such as clean code, efficient networking, and observability, you ensure your app not only meets user expectations today but <strong>scales gracefully for tomorrow.</strong></p><blockquote><strong>Remember:</strong> Performance isn’t a one-time task, it’s a mindset. Measure, optimize, and monitor continuously. Every millisecond counts, and the improvements you make can directly translate into happier users, longer engagement, and a stronger app reputation. Start small, iterate smartly, and watch your app’s speed, and user satisfactio.</blockquote><p>Thanks for reading! I hope these techniques help you build faster, smoother apps. Good luck building!</p><h3>Resources</h3><p>Here are some resources for the above info, for anyone interested.</p><ul><li><a href="https://42matters.com/stats"><strong><em>42matters. App Store Statistics 2025 Snapshot. 2025.</em></strong></a></li><li><a href="https://developer.android.com/topic/performance/vitals/launch-time"><strong><em>Android Developers. App Startup Time &amp; App Quality. Google, 2024–2025.</em></strong></a></li><li><strong><em>Back Market Engineering. Improving Android App Startup by 50% Using Baseline Profiles. </em></strong><a href="https://engineering.backmarket.com/how-we-enhanced-our-android-apps-startup-time-by-over-50-0fb220d27b14"><strong><em>Back Market Tech Blog, 2024.</em></strong></a></li><li><a href="https://sentry.io/resources/mobile-performance-best-practices/"><strong><em>Sentry. Mobile Performance Best Practices:</em></strong></a><strong><em> Profiling, Tracing &amp; Metrics. March 2024.</em></strong></li><li><a href="https://uxcam.com/blog/sentry-vs-crashlytics/"><strong><em>UXCam. Crashlytics vs Sentry:</em></strong></a><strong><em> Detailed Comparison for Mobile Monitoring. February 2025.</em></strong></li><li><a href="https://moldstud.com/articles/p-best-practices-for-real-time-mobile-app-monitoring-enhance-performance-user-experience"><strong><em>MoldStud. Real-Time Mobile Monitoring Best Practices. June 2025.</em></strong></a></li><li><a href="https://solveit.dev/blog/improve-mobile-app-performance"><strong><em>SolveIt.dev. Mobile App Performance: How to Improve It. Article, 2023.</em></strong></a></li><li><a href="https://www.outerboxdesign.com/articles/digital-marketing/progressive-web-apps-pwas/"><strong><em>OuterBox Design. Mobile eCommerce Statistics &amp; UX Impact. OuterBox Insights, 2024.</em></strong></a></li></ul><p><em>Note: This article speaks only to my personal views / experiences and is not published on behalf of Deloitte LLP and associated firms, and does not constitute professional or legal advice.</em></p><p><em>All product names, logos, and brands are property of their respective owners. All company, product and service names used in this website are for identification purposes only. Use of these names, logos, and brands does not imply endorsement.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fd1be7f503a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/deloitte-uk-cloud-blog/how-to-make-your-mobile-app-faster-2fd1be7f503a">How to Make Your Mobile App Faster</a> was originally published in <a href="https://medium.com/deloitte-uk-cloud-blog">Deloitte UK Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Clutter to Clarity: A Real-World Swift Refactoring Case Study]]></title>
            <link>https://medium.com/@essammohamedomran/from-clutter-to-clarity-a-real-world-swift-refactoring-case-study-90540e5e7d97?source=rss-f97cf1a05be4------2</link>
            <guid isPermaLink="false">https://medium.com/p/90540e5e7d97</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[code-review]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[swift-development]]></category>
            <dc:creator><![CDATA[Essam Fahmy]]></dc:creator>
            <pubDate>Mon, 24 Feb 2025 13:43:46 GMT</pubDate>
            <atom:updated>2025-03-02T23:52:17.858Z</atom:updated>
            <content:encoded><![CDATA[<h3>Code Refactoring: A Simple Use Case for Filter Management in Swift</h3><h3>Introduction</h3><p>Refactoring code is essential for improving readability, maintainability, and testability. In this article, I’ll walk through a real-world scenario where I refactored an iOS filtering system to separate concerns, improve structure, and leverage static methods for better organization.</p><h3>The Problem</h3><p>Originally, the filtering logic was tightly coupled with the ViewModel, making it harder to maintain and extend. The initializer handled both loading filters from UserDefaults and setting default values when necessary:</p><pre>class FilterViewModel {<br>    var filterItems: [FilterItem] = []<br>    <br>    init() {<br>        if let filterData = UserDefaults.standard.data(forKey: FilterStorage.filterKey),<br>           let filter = try? JSONDecoder().decode(Filter.self, from: filterData) {<br>            self.filterItems = filter.filterItems<br>        } else {<br>            self.filterItems = [FilterItem(id: UUID().uuidString, key: &quot;filter key 1&quot;, value: &quot;value 1&quot;),<br>                                FilterItem(id: UUID().uuidString, key: &quot;filter key 2&quot;, value: &quot;value 2&quot;)]<br>        }<br>    }<br>}</pre><h3>Issues with this Approach</h3><ol><li>The initializer performs data retrieval and default value creation.</li><li>Default filters are embedded within the initializer.</li><li>Modifying filter logic requires editing the initializer.</li><li>Tight coupling to UserDefaults makes unit testing harder.</li></ol><h3>The Refactored Solution</h3><p>To improve clarity and maintainability, we extract logic into separate methods and introduce dependency injection:</p><pre>class FilterViewModel {<br>    var filterItems: [FilterItem] = []<br>    private let storage: FilterStorageProtocol<br>    <br>    // MARK: - Init<br>    init(storage: FilterStorageProtocol = UserDefaultsFilterStorage()) {<br>        self.storage = storage<br>        self.filterItems = FilterViewModel.loadFilterItems(from: storage)<br>    }<br>    <br>    // MARK: - Private Methods<br>    private static func loadFilterItems(from storage: FilterStorageProtocol) -&gt; [FilterItem] {<br>        return storage.fetchFilters() ?? defaultFilterItems()<br>    }<br>    <br>    private static func defaultFilterItems() -&gt; [FilterItem] {<br>        return [<br>            FilterItem(id: UUID().uuidString, key: &quot;filter key 1&quot;, value: &quot;value 1&quot;),<br>            FilterItem(id: UUID().uuidString, key: &quot;filter key 2&quot;, value: &quot;value 2&quot;),<br>            FilterItem(id: UUID().uuidString, key: &quot;filter key 3&quot;, value: &quot;value 3&quot;)<br>        ]<br>    }<br>}</pre><h3>Introducing Dependency Injection</h3><p>Instead of directly using UserDefaults, we abstract storage handling:</p><pre>protocol FilterStorageProtocol {<br>    func fetchFilters() -&gt; [FilterItem]?<br>}<br><br>class UserDefaultsFilterStorage: FilterStorageProtocol {<br>    func fetchFilters() -&gt; [FilterItem]? {<br>        guard let filterData = UserDefaults.standard.data(forKey: FilterStorage.filterKey),<br>              let filter = try? JSONDecoder().decode(Filter.self, from: filterData) else {<br>            return nil<br>        }<br>        return filter.filterItems<br>    }<br>}</pre><h3>Why Use Static Methods?</h3><ol><li><strong>No Need to Create an Instance</strong>: Since these methods don’t use self, they don’t require an instance of FilterViewModel.</li><li><strong>Cannot Use Normal Methods During Init</strong>: Regular instance methods require an initialized instance, but we need to load filters during initialization itself.</li></ol><h3>Key Benefits of This Approach</h3><ul><li>Default filter creation is now independent of data retrieval.</li><li>Different storage implementations can be injected.</li><li>We can now mock FilterStorageProtocol for unit testing.</li><li>Logic is neatly split into clearly defined methods.</li></ul><h3>Real-World Impact</h3><ul><li><strong>New developers could onboard faster</strong> since the logic is easier.</li><li><strong>Additional filter sources (e.g., API-based) could be added without modifying the </strong><strong>ViewModel.</strong></li><li><strong>Unit tests improved</strong>, as logic could be tested in isolation.</li><li><strong>Code reviews became more focused on business logic</strong>, not structure.</li></ul><h3>Conclusion</h3><p>Refactoring isn’t just about functionality — it’s about writing <strong>clean, maintainable, and scalable</strong> code. We made the filtering system more flexible and testable by applying <strong>Separation of Concerns</strong>, <strong>Encapsulation</strong>, and <strong>Dependency Injection</strong>.</p><p>#SwiftDevelopment #CodeRefactoring #iOSDevelopment #CleanCode #SoftwareEngineering</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90540e5e7d97" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Struct vs Class in Swift: A Complete Guide From Basics to Performance]]></title>
            <link>https://medium.com/@essammohamedomran/struct-vs-class-in-swift-a-complete-guide-from-basics-to-performance-9b1e0ef2b0cb?source=rss-f97cf1a05be4------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b1e0ef2b0cb</guid>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[class]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[struct]]></category>
            <dc:creator><![CDATA[Essam Fahmy]]></dc:creator>
            <pubDate>Fri, 10 Jan 2025 14:40:44 GMT</pubDate>
            <atom:updated>2025-01-10T14:40:44.944Z</atom:updated>
            <content:encoded><![CDATA[<p>When building iOS apps, one of our most fundamental decisions is choosing between structs and classes. Let’s explore their differences, from basic concepts to advanced performance insights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b5d3xHOasoDD19xYXvfzIA.png" /><figcaption>Struct vs Class in Swift: A Complete Guide From Basics to Performance</figcaption></figure><h3>Part 1: The Foundation</h3><h4>Value vs Reference Types</h4><p>The most basic difference between structs and classes lies in how they handle data:</p><pre>// Structs are value types<br>struct UserStruct {<br>    var name: String<br>}<br><br>var user1 = UserStruct(name: &quot;Alice&quot;)<br>var user2 = user1 // Creates a copy<br>user2.name = &quot;Bob&quot;<br>print(user1.name) // Prints &quot;Alice&quot;<br><br>// Classes are reference types<br>class UserClass {<br>    var name: String<br>    init(name: String) {<br>        self.name = name<br>    }<br>}<br><br>var user1 = UserClass(name: &quot;Alice&quot;)<br>var user2 = user1 // Points to same instance<br>user2.name = &quot;Bob&quot;<br>print(user1.name) // Prints &quot;Bob&quot;</pre><h4>Inheritance and Initialization</h4><p><strong>Structs:</strong></p><ul><li>No inheritance support</li><li>Free memberwise initializer</li><li>Support protocols</li><li>No deinitializers</li></ul><p><strong>Classes:</strong></p><ul><li>Support inheritance</li><li>Must write initializers</li><li>Support protocols</li><li>Have deinitializers</li></ul><pre>struct Dog {<br>    let name: String<br>    let breed: String<br>    // Free memberwise initializer!<br>}<br><br>class Animal {<br>    let species: String<br>     <br>    init(species: String) {<br>        self.species = species<br>    }<br>     <br>    deinit {<br>        print(&quot;Animal deallocated&quot;)<br>    }<br>}</pre><h3>Part 2: Memory Management</h3><h4>Memory Location and Management</h4><p><strong>Structs:</strong></p><ul><li>Stored on the stack</li><li>No reference counting needed</li><li>Automatically deallocated</li><li>Faster allocation and deallocation</li></ul><p><strong>Classes:</strong></p><ul><li>Stored on the heap</li><li>Uses Automatic Reference Counting (ARC)</li><li>Need memory management</li><li>More overhead for allocation/deallocation</li></ul><pre>class Car {<br>    var model: String<br>    <br>    init(model: String) {<br>        self.model = model<br>        print(&quot;Car initialized&quot;)<br>    }<br>    <br>    deinit {<br>        print(&quot;Car deinitialized&quot;) // ARC in action<br>    }<br>}</pre><h3>Part 3: The Performance</h3><p>Here’s where things get really interesting. The way structs and classes handle method calls can significantly impact performance.</p><h4>Static Dispatch (Structs)</h4><p>When you call a method on a struct, Swift knows exactly which code to run at compile time:</p><pre>struct MenuItem {<br>    let name: String<br>    let basePrice: Double<br>    <br>    func calculatePrice(withDiscount discount: Double)-&gt; Double {<br>        return basePrice * (1 - discount)<br>    }<br>}<br><br>let item = MenuItem(name: &quot;Coffee&quot;, basePrice: 3.99)<br>item.calculatePrice(withDiscount: 0.1) // Direct call, no lookup needed</pre><h4>Dynamic Dispatch (Classes)</h4><p>Classes require a runtime lookup to find the right method:</p><pre>class MenuItem {<br>    let name: String<br>    let basePrice: Double<br>    <br>    init(name: String, basePrice: Double) {<br>        self.name = name<br>        self.basePrice = basePrice<br>    }<br>    <br>    func calculatePrice(withDiscount discount: Double) -&gt;Double {<br>        return basePrice * (1 - discount)<br>    }<br>}<br><br>let item = MenuItem(name: &quot;Coffee&quot;, basePrice: 3.99)<br>item.calculatePrice(withDiscount: 0.1) // Requires lookup in virtual table</pre><h4>Impact on Real-World Scenarios</h4><p>Consider processing a menu of items:</p><pre>// Using structs (faster)<br>struct FastMenuItem {<br>    let name: String<br>    let price: Double<br>    <br>    func applyDiscount(_ discount: Double) -&gt; Double {<br>        return price * (1 - discount)<br>    }<br>}<br><br>let menuItems = [<br>    FastMenuItem(name: &quot;Coffee&quot;, price: 3.99),<br>    FastMenuItem(name: &quot;Tea&quot;, price: 2.99),<br>    FastMenuItem(name: &quot;Sandwich&quot;, price: 6.99)<br>]<br><br>// Each method call is direct and fast<br>for item in menuItems {<br>    let discountedPrice = item.applyDiscount(0.1)<br>}</pre><p><strong>The struct version will be noticeably faster when:</strong></p><ol><li>Processing large collections</li><li>Calling methods frequently</li><li>Working in performance-critical code paths</li></ol><h3>Making the Right Choice</h3><h4><strong>Use Structs When:</strong></h4><ul><li>You want value semantics</li><li>You’re working with small, simple data</li><li>Performance is critical</li><li>You don’t need inheritance</li><li>You’re calling methods frequently in loops</li></ul><h4>Use Classes When:</h4><ul><li>You need inheritance</li><li>You want reference semantics</li><li>You’re working with Objective-C</li><li>Identity comparison is important</li><li>You need to share mutable state</li></ul><h4>Best Practices</h4><ol><li><strong>Start with Structs by Default</strong><br>Structs should be your go-to choice for creating types in Swift. Their simplicity, immutability by default, and value semantics make them ideal for most scenarios.</li><li><strong>Move to Classes When Needed</strong><br>Opt for classes only when you need specific features they offer, such as inheritance, reference semantics, or Objective-C compatibility. These use cases are less common, but they’re crucial in certain designs.</li><li><strong>Consider Performance Implications in Critical Paths</strong><br> In performance-sensitive areas of your app, understand how your choice impacts memory management and method dispatch. Structs benefit from static dispatch and avoid the overhead of reference counting, while classes introduce dynamic dispatch and ARC.</li><li><strong>Profile Before Optimizing</strong><br>Never assume performance issues without evidence. Use tools like Xcode’s Instruments to profile your app and identify actual bottlenecks before investing time in optimization. Premature optimization can lead to unnecessary complexity.</li><li><strong>Use Value Types for Data Models</strong><br> When modeling data, prefer value types like structs unless there’s a compelling reason to use classes. Value types ensure clarity, immutability, and thread safety by default, making them an excellent choice for most data-handling scenarios.</li></ol><h3>Conclusion</h3><p>While the basic differences between structs and classes are important, understanding method dispatch can help you make better performance decisions in your Swift code. Remember to choose based on your design needs first, then optimize if needed.</p><p>The performance benefits of static dispatch make structs an even more attractive default choice but always choose the right tool for your specific use case.</p><h3>Acknowledgment</h3><p>Special thanks to <a href="https://www.linkedin.com/in/kareem-abd-elsattar-448606146/"><strong>Kareem Abd El Sattar</strong></a> for always being there and for this amazing collaboration. His input is helping to present the concept from different perspectives. I truly appreciate his insights and support throughout this process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b1e0ef2b0cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing Software Design: A Real-World Journey from Code Smell to SOLID Principles]]></title>
            <link>https://medium.com/@essammohamedomran/enhancing-software-design-a-real-world-journey-from-code-smell-to-solid-principles-2e07b1cadf97?source=rss-f97cf1a05be4------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e07b1cadf97</guid>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[solid]]></category>
            <dc:creator><![CDATA[Essam Fahmy]]></dc:creator>
            <pubDate>Tue, 31 Dec 2024 17:44:57 GMT</pubDate>
            <atom:updated>2024-12-31T17:44:57.731Z</atom:updated>
            <content:encoded><![CDATA[<p>As software engineers, especially if you’re just starting, you’ll often hear about SOLID principles: five design guidelines that can make code easier to maintain, understand, and extend. In this article, we’ll walk through a code example inspired by a real-world codebase, showcasing how SOLID can help transform a piece of code from hard-to-maintain to a clean, flexible design.</p><p>Let’s dive into the “before” and “after” to see the impact of each SOLID principle in action!</p><h3>Before: The Legacy Code</h3><p>Originally, our DocumentProcessor class handled various responsibilities — detecting, logging, and syncing document types — all within one function. As new document types were added, this design became more challenging to maintain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cgtKvHJo1FxRpg8M" /><figcaption>A snapshot of the original code with SOLID violations, where responsibilities are mixed and extensibility is limited.</figcaption></figure><p>At first glance, this code seems okay. It can handle different document types, syncing, and logging. However, as we add more document types, it quickly becomes cluttered and hard to maintain. This design violates several SOLID principles, making it difficult to add new document types or change the behavior without modifying processDocument.</p><h3>Analyzing the SOLID Violations</h3><p>Let’s break down how each SOLID principle is violated and what that means for the code:</p><h4>SRP (Single Responsibility Principle):</h4><p><strong>Violation:</strong> The processDocument function taking on multiple tasks directly within the DocumentProcessor class itself, rather than delegating them, while simply calling other functions, is still responsible for coordinating multiple actions — detecting, syncing, and logging — which bundles distinct responsibilities into one method.</p><blockquote><em>This coordination should ideally be split so that each task (e.g., detecting document type, syncing, and logging) is handled independently.</em></blockquote><p>For example, let’s suppose we want to add a new document type, say HRDocument, with a unique logging behavior. In the legacy design, we would have to:</p><p>1- You modify processDocument to detect the HRDocument by adding a condition to handle this specific document type.</p><p>2- After detection, you add custom behavior for HRDocuments, like specific logging or syncing logic that would be unique to HR documents.</p><p>Every time you add a new document type, you are forced to modify multiple responsibilities within this one function. This approach becomes harder to maintain as more document types are added, especially when each document type needs specific behavior like logging or syncing.</p><h4>OCP (Open-Closed Principle):</h4><p><strong>Violation:</strong> Each time a new document type (e.g., “HR document”) needs handling, we have to modify processDocument. This makes the code “closed” to extensions, forcing changes to existing logic whenever new document requirements arise.</p><h4>LSP (Liskov Substitution Principle):</h4><p><strong>Violation:</strong> We lack the flexibility to substitute different logging behaviors for different document types, such as unique logging for finance versus legal documents. This forces us to modify processDocument to introduce specialized logging, undermining the ability to handle document types interchangeably.</p><h4>ISP (Interface Segregation Principle):</h4><p><strong>Violation:</strong> The document-handling responsibilities — detection, protection, syncing, and logging — are all managed within DocumentProcessor, rather than being separated into more focused interfaces. This grouping makes DocumentProcessor depends on methods it may not always need, complicating its role.</p><h4>DIP (Dependency Inversion Principle):</h4><p><strong>Violation:</strong> DocumentProcessor relies directly on methods like syncWithCloud, rather than using interfaces like ICloudSyncService. This dependence on concrete implementations limits flexibility and makes testing harder, as swapping services would require modifying the code.</p><h3>After: Refactored Code with SOLID Principles</h3><p>Let’s refactor this code to follow SOLID principles. Here’s a version that uses interfaces and separates each responsibility into its class. Each task — such as detecting the document type, syncing with the cloud, and logging — is now handled independently.</p><h4>Interfaces and Base Classes:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*02Sv6p7G69wE34x0" /><figcaption>The refactored code showcases the application of SOLID principles, with a clear separation of responsibilities and a more flexible design.</figcaption></figure><h4>DocumentProcessor and Usage Example:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p9sH1IDkQgHSrKww" /><figcaption>The refactored code showcases the application of SOLID principles, with a clear separation of responsibilities and a more flexible design.</figcaption></figure><h4>Explanation of the SOLID Refactoring</h4><p><strong>SRP (Single Responsibility Principle)</strong></p><p>In the refactored code, each class and interface now handles a single, specific task. For instance, document type matching is handled by IDocumentClassifier and ICloudSyncService is solely responsible for syncing documents, while DocumentType subclasses handle document-specific logging actions.</p><blockquote><em>This design shift aligns each responsibility to its own component, reducing complexity in processDocument and making the code easier to extend or modify for specific document behaviors without needing to change the core processing logic.</em></blockquote><p>For example, let’s suppose we want to add a new document type, say HRDocument, with a unique logging behavior. In the refactored design, you simply:</p><p>1- Create a new subclass called HRDocument.</p><p>2- Implement a logDocumentAction() method in HRDocument for custom logging behavior.</p><p>Since each document type (like FinanceDocument, LegalDocument, or the new HRDocument) handles its own logging, you don’t have to touch the processDocument function in DocumentProcessor at all. processDocument will call logDocumentAction() on whatever document type is passed, and each document type will handle its own logging behavior.</p><p><strong>OCP (Open-Closed Principle)</strong></p><p>With this design, we can easily introduce new document types — such as FinanceDocument or LegalDocument — by creating new subclasses. This change doesn’t require modifications to processDocument, allowing the core processing logic to stay the same even as new document types are added.</p><p><strong>LSP (Liskov Substitution Principle)</strong></p><p>Previously, logging was hardcoded within the main processing logic, which limited flexibility for document-specific behavior. Now, with specialized subclasses like FinanceDocument and LegalDocument, each document type can implement its version of logDocumentAction. This lets us use different document types interchangeably without altering DocumentProcessor, ensuring that behavior is consistent for each document type without additional modification.</p><p><strong>ISP (Interface Segregation Principle)</strong></p><p>Each interface — such as IDocumentClassifier and ICloudSyncService — now focuses on a single task. This means DocumentProcessor only interacts with the specific functionalities it requires (like classification and syncing), making it less dependent on unrelated methods and keeping each task focused.</p><p><strong>DIP (Dependency Inversion Principle)</strong></p><p>By depending on abstractions (IDocumentClassifier and ICloudSyncService) rather than concrete implementations, the DocumentProcessor can work with any compatible implementation of these interfaces. This makes it easy to replace, extend, or mock dependencies like syncing and classification, allowing for greater flexibility and easier testing.</p><h3>Acknowledgment</h3><p>Thanks to my friend and colleague <a href="https://www.linkedin.com/article/edit/7257575092287590400/#">Ibrahim El-Geddawy</a> for reviewing this article. While working on a high-impact U.S. project together, we encountered real-world challenges that highlighted the importance of SOLID principles. This experience inspired us to share a practical example to make these concepts clearer and more applicable for new engineers.</p><h3>Conclusion</h3><p>By applying SOLID principles, we’ve improved the DocumentProcessor design, making it flexible, easy to extend, and simpler to maintain. For junior developers, this example shows that SOLID isn’t just theoretical — applying these principles makes a real difference in how manageable and adaptable your code becomes.</p><p>Following SOLID is a great way to grow your skills and write professional-grade code. Try refactoring a small part of your codebase using these principles — you’ll notice the difference!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e07b1cadf97" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling API Dependencies with Chain of Responsibility and Modern Concurrency in Swift]]></title>
            <link>https://medium.com/@essammohamedomran/handling-api-dependencies-with-chain-of-responsibility-and-modern-concurrency-in-swift-83a4735a3976?source=rss-f97cf1a05be4------2</link>
            <guid isPermaLink="false">https://medium.com/p/83a4735a3976</guid>
            <category><![CDATA[chain-of-responsibility]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Essam Fahmy]]></dc:creator>
            <pubDate>Mon, 23 Dec 2024 21:39:53 GMT</pubDate>
            <atom:updated>2024-12-30T20:46:19.385Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>When building iOS applications, we often encounter scenarios requiring multiple sequential API calls, where each subsequent call depends on the previous one’s result. A common example might look like this:</p><ol><li><strong>Fetch user details</strong></li><li><strong>Use those details to retrieve account information</strong></li><li><strong>Use the account information to fetch transaction history</strong></li></ol><p>Without proper organization, dependencies can quickly become unmanageable. In this context, we’ll explore how this happens and then discuss how to break down complex operations into reusable steps. This brings us to today’s topic: the Chain of Responsibility pattern, combined with Swift’s modern concurrency features, to create a clean and maintainable solution.</p><h3>Problems with the Traditional Approach</h3><p>Consider this typical scenario in a banking app:</p><pre>// Problematic approach<br>func fetchUserData() async {<br>    do {<br>        let userDetails = try await fetchUserDetails()<br>        let accountInfo = try await fetchAccountInfo(userId: userDetails.userId)<br>        let transactions = try await fetchTransactions(accountId: accountInfo.accountId)<br>        // Handle the results<br>    } catch {<br>        // Handle errors<br>    }<br>}</pre><p><strong>Tight Coupling</strong></p><ul><li>Data from one step is hardwired to the next</li><li>Code must be used as a single unit</li></ul><p><strong>Hard to Modify</strong></p><ul><li>Adding new API calls requires changing existing code</li><li>Difficult to add optional steps</li></ul><p><strong>Complex Error Handling</strong></p><ul><li>Nested error-handling blocks become messy</li><li>Different error types at each level</li></ul><p><strong>Testing Challenges</strong></p><ul><li>Must mock the entire chain for any test</li><li>Hard to test specific error scenarios</li></ul><h3>The Solution: Chain of Responsibility</h3><p>The Chain of Responsibility pattern allows us to break this complex operation into discrete, reusable steps. Combined with Swift’s async/await, it creates a clean and maintainable solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7qPATXgAfkcZCgW1g2T9SQ.png" /><figcaption>High-Level Design — Chain of Responsibility Pattern for API Handling</figcaption></figure><h4>Step 1: Define the Protocol</h4><p>First, we create a protocol that each handler will implement:</p><pre>protocol AsyncAPIHandler {<br>    func handle(input: Any?) async throws -&gt; Any<br>}</pre><h4>Step 2: Create Model Types</h4><p>We’ll use Codable for type-safe data handling:</p><pre>struct UserDetails: Codable {<br>    let userId: String<br>    let username: String<br>}<br><br>struct AccountInfo: Codable {<br>    let accountId: String<br>    let balance: Double<br>}<br><br>struct Transaction: Codable {<br>    let id: String<br>    let amount: Double<br>}</pre><h4>Step 3: Implement the Handlers</h4><p>Each handler focuses on one specific API call:</p><pre>class UserDetailsHandler: AsyncAPIHandler {<br>    func handle(input: Any?) async throws -&gt; Any {<br>        let url = URL(string: &quot;https://api.example.com/user&quot;)!<br>        let (data, _) = try await URLSession.shared.data(from: url)<br>        return try JSONDecoder().decode(UserDetails.self, from: data)<br>    }<br>}<br><br>class AccountInfoHandler: AsyncAPIHandler {<br>    func handle(input: Any?) async throws -&gt; Any {<br>        guard let userDetails = input as? UserDetails else {<br>            throw HandlerError.invalidInput<br>        }<br>         <br>        let url = URL(string: &quot;https://api.example.com/account/\(userDetails.userId)&quot;)!<br>        let (data, _) = try await URLSession.shared.data(from: url)<br>        return try JSONDecoder().decode(AccountInfo.self, from: data)<br>    }<br>}<br><br>class TransactionHandler: AsyncAPIHandler {<br>    func handle(input: Any?) async throws -&gt; Any {<br>        guard let accountInfo = input as? AccountInfo else {<br>            throw HandlerError.invalidInput<br>        }<br>        <br>        let url = URL(string: &quot;https://api.example.com/transactions/\(accountInfo.accountId)&quot;)!<br>        let (data, _) = try await URLSession.shared.data(from: url)<br>        <br>        return try JSONDecoder().decode([Transaction].self, from: data)<br>    }<br>}</pre><h4>Step 4: Create the Chain</h4><p>The chain class orchestrates the execution:</p><pre>class AsyncAPIChain {<br>    private var handlers: [AsyncAPIHandler] = []<br>    <br>    func addHandler(_ handler: AsyncAPIHandler) {<br>        handlers.append(handler)<br>    }<br>    <br>    func execute() async throws -&gt; Any {<br>        var result: Any? = nil<br>        <br>        for handler in handlers {<br>            result = try await handler.handle(input: result)<br>        }<br>         <br>        return result ?? &quot;No Result&quot;<br>    }<br>}</pre><h4>Step 5: Integration with SwiftUI</h4><p>In the first part, we’ll focus on how to set up the AsyncAPIChain with the required handlers and inject it into the ViewModel in the App structure.</p><pre>import SwiftUI<br><br>@main<br>struct BankingApp: App {<br>    var body: some Scene {<br>        WindowGroup {<br>            // Create the handlers for the chain<br>            let userDetailsHandler = UserDetailsHandler()<br>            let accountInfoHandler = AccountInfoHandler()<br>            let transactionHandler = TransactionHandler()<br><br>            // Create the AsyncAPIChain with the handlers<br>            let apiChain = AsyncAPIChain()<br>            apiChain.addHandler(userDetailsHandler)<br>            apiChain.addHandler(accountInfoHandler)<br>            apiChain.addHandler(transactionHandler)<br><br>            // Inject the apiChain into the ViewModel<br>            ContentView(viewModel: ViewModel(apiChain: apiChain))<br>        }<br>    }<br>}<br><br>struct ContentView: View {<br>    @StateObject private var viewModel: ViewModel<br>    <br>    init(viewModel: ViewModel) {<br>        _viewModel = StateObject(wrappedValue: viewModel)<br>    }<br>    <br>    var body: some View {<br>        VStack {<br>            if let latestTransaction = viewModel.latestTransaction {<br>                Text(&quot;Latest Transaction: \(latestTransaction.transactionId), Amount: \(latestTransaction.amount))&quot;)<br>            }<br>            Text(&quot;Total Transactions: \(viewModel.transactionCount)&quot;)<br>        }<br>        .padding()<br>        .task {<br>            await viewModel.fetchData()<br>        }<br>    }<br>}</pre><p><strong>Key Highlights:</strong></p><ul><li><strong>AsyncAPIChain Setup</strong>: Here we create and configure the AsyncAPIChain by adding the relevant handlers (UserDetailsHandler, AccountInfoHandler, and TransactionHandler).</li><li><strong>Injecting into </strong><strong>ViewModel</strong>: The chain is then injected into the ViewModel using dependency injection, making the ViewModel ready to handle the chained API requests.</li></ul><p>Now, let’s look at how the ViewModel interacts with the AsyncAPIChain to fetch data and update the view with the results.</p><pre>import SwiftUI<br><br>@MainActor<br>class ViewModel: ObservableObject {<br>    @Published var transactionCount: Int = 0<br>    @Published var latestTransaction: Transaction? = nil<br><br>    private let apiChain: AsyncAPIChain<br><br>    init(apiChain: AsyncAPIChain) {<br>        self.apiChain = apiChain<br>    }  <br>  <br>    func fetchData() async {<br>        do {<br>            let finalResult = try await apiChain.execute()<br>            if let transactions = finalResult as? [Transaction] {<br>                transactionCount = transactions.count<br>                latestTransaction = transactions.first  // Assuming the first is the latest<br>            }<br>        } catch {<br>            result = &quot;Error: \(error.localizedDescription)&quot;<br>        }<br>    }<br>}</pre><p>The @MainActor attribute is used to ensure that the ViewModel&#39;s properties and methods are accessed and updated on the main thread.</p><p><strong>Key Highlights:</strong></p><ul><li><strong>ViewModel Properties</strong>: transactionCount and latestTransaction hold the results fetched by the API chain.</li><li><strong>Fetching Data</strong>: The fetchData method asynchronously fetches data from the AsyncAPIChain. The results are then mapped to update the transactionCount and latestTransaction properties.</li></ul><h3>Mocking Handlers for Unit Testing</h3><p>As we showed above, how we design and build the AsyncAPIChain to manage the API dependencies and provide the final result for the ViewModel easily as it is injected from outside, let&#39;s now explore how we can mock the handlers and test our ViewModel.</p><p>By injecting dependencies such as the AsyncAPIChain into our ViewModel, we decouple the business logic from external systems, allowing us to write clean and maintainable unit tests. This approach helps us simulate different API responses and ensures that we can test the ViewModel in isolation, without making real network requests.</p><h4>Create Mock Handlers</h4><p>Mock handlers simulate the behavior of the actual handlers used in the AsyncAPIChain. These handlers provide predefined outputs, enabling us to simulate various test scenarios without the need for real network calls.</p><p><strong>Example Mock Handler for </strong><strong>UserDetailsHandler:</strong></p><pre>class MockUserDetailsHandler: AsyncAPIHandler {<br>    func handle(input: Any?) async throws -&gt; Any {<br>        return UserDetails(userId: &quot;mockUserId&quot;, username: &quot;mockUser&quot;)<br>    }<br>}</pre><p><strong>Example Mock Handler for </strong><strong>AccountInfoHandler:</strong></p><pre>class MockAccountInfoHandler: AsyncAPIHandler {<br>    func handle(input: Any?) async throws -&gt; Any {<br>        guard let userDetails = input as? UserDetails else {<br>            throw HandlerError.invalidInput<br>        }<br>        return AccountInfo(accountId: &quot;mockAccountId&quot;, balance: 100)<br>    }<br>}</pre><p><strong>Example Mock Handler for </strong><strong>TransactionHandler:</strong></p><pre>class MockTransactionHandler: AsyncAPIHandler {<br>    func handle(input: Any?) async throws -&gt; Any {<br>        return [<br>            Transaction(id: &quot;mockTx1&quot;, amount: 100),<br>            Transaction(id: &quot;mockTx2&quot;, amount: 200)<br>        ]<br>    }<br>}</pre><h4>Testable ViewModel</h4><p>Now that we have mock handlers in place, we can inject them into the ViewModel to simulate API calls during testing. This allows us to test the business logic in isolation without relying on real network data.</p><p><strong>Example of a </strong><strong>ViewModel Test:</strong></p><pre>import XCTest<br>import SwiftUI<br><br>class ViewModelTests: XCTestCase {<br>    func testFetchData_Success() async {<br>        // Arrange: Create mock handlers<br>        let mockUserDetailsHandler = MockUserDetailsHandler()<br>        let mockAccountInfoHandler = MockAccountInfoHandler()<br>        let mockTransactionHandler = MockTransactionHandler()<br><br>        // Create the AsyncAPIChain with the mock handlers<br>        let apiChain = AsyncAPIChain()<br>        apiChain.addHandler(mockUserDetailsHandler)<br>        apiChain.addHandler(mockAccountInfoHandler)<br>        apiChain.addHandler(mockTransactionHandler)<br><br>        // Inject the chain into the ViewModel<br>        let viewModel = ViewModel(apiChain: apiChain)<br><br>        // Act: Fetch data<br>        await viewModel.fetchData()<br><br>        // Assert: Verify the results<br>        XCTAssertEqual(viewModel.transactionCount, 2, &quot;Transaction count should be 2&quot;)<br>        XCTAssertEqual(viewModel.latestTransaction?.id, &quot;mockTx1&quot;, &quot;The latest transaction ID should be mockTx1&quot;)<br>        XCTAssertEqual(viewModel.latestTransaction?.amount, 100, &quot;The latest transaction amount should be 100&quot;)<br>    }<br><br>    func testFetchData_Error() async {<br>        // Arrange: Create a mock handler that throws an error<br>        class MockErrorHandler: AsyncAPIHandler {<br>            func handle(input: Any?) async throws -&gt; Any {<br>                throw NSError(domain: &quot;MockError&quot;, code: 123, userInfo: nil)<br>            }<br>        }<br><br>        // Create the AsyncAPIChain with the mock handlers<br>        let apiChain = AsyncAPIChain()<br>        let mockErrorHandler = MockErrorHandler()<br>        apiChain.addHandler(mockErrorHandler)<br><br>        // Inject the chain into the ViewModel<br>        let viewModel = ViewModel(apiChain: apiChain)<br><br>        // Act: Fetch data<br>        await viewModel.fetchData()<br><br>        // Assert: Verify the error result<br>        XCTAssertEqual(viewModel.result, &quot;Error: The operation couldn’t be completed. (MockError error 123.)&quot;, &quot;Error message should be properly set&quot;)<br>    }<br>}</pre><p>This section shows how we can mock handlers to create testable, isolated code. By doing so, we can efficiently test our ViewModel without relying on external systems.</p><h3>Benefits</h3><p>This approach offers several advantages:</p><ol><li><strong>Modularity</strong>: Each handler is independent and can be tested in isolation</li><li><strong>Flexibility</strong>: Easy to add, remove, or reorder API calls</li><li><strong>Reusability</strong>: Handlers can be reused in different chains</li><li><strong>Type Safety</strong>: Codable ensures type-safe data handling</li><li><strong>Error Handling</strong>: Centralized error handling in the chain</li><li><strong>Testability</strong>: Easy to mock handlers for testing</li></ol><h3>Conclusion</h3><p>The Chain of Responsibility pattern and Swift’s modern concurrency features provide a clean solution for handling complex API dependencies. This approach scales well as your application grows and makes future modifications easier.</p><p>Remember that while this pattern adds some complexity, the benefits of maintainability and flexibility often outweigh the initial setup cost for complex API workflows.</p><p>Feel free to adapt this pattern to your specific needs and simplify it for simpler use cases.</p><h3>Acknowledgments</h3><p>I want to extend my thanks to the reviewers for their valuable feedback and insights, which helped shape this guide. Special thanks to <a href="https://www.linkedin.com/in/kareem-abd-elsattar-448606146/">Kareem Abd El Sattar</a>, and <a href="https://www.linkedin.com/in/mohamed-goda-ba226a158/">Mohamed Goda</a> for their time and expertise in reviewing the content.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83a4735a3976" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-World Interview with a Tech Manager at Delivery Hero]]></title>
            <link>https://medium.com/@essammohamedomran/real-world-interview-with-a-tech-manager-at-delivery-hero-9fc5e234e1e1?source=rss-f97cf1a05be4------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fc5e234e1e1</guid>
            <category><![CDATA[legacy-code]]></category>
            <category><![CDATA[technical-interview]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[coding-best-practices]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Essam Fahmy]]></dc:creator>
            <pubDate>Thu, 19 Dec 2024 18:06:37 GMT</pubDate>
            <atom:updated>2024-12-20T14:49:21.252Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever faced the unwanted challenge of working with legacy code? You know, that moment when you need to add a shiny new feature but find yourself messy in a web of old, tightly coupled code? Let me share an exciting interview experience I had with a technical manager at Delivery Hero who tackled this problem.</p><h3>Setting the Scene</h3><p>Picture this: You’re in an interview, and the Technical Manager presents you with a common yet tricky scenario. You need to implement a new feature in a system that heavily relies on a singleton pattern — specifically, a `Configurator` that’s deeply embedded in the application’s core. The catch? You can’t refactor the entire system, and you’re on a tight deadline.</p><blockquote>Take a moment and think: How would you approach this challenge?</blockquote><h3>The Legacy Code Dilemma</h3><p>Here’s what made this problem particularly interesting:</p><ul><li>The system was already in production, serving customers</li><li>The singleton pattern was deeply integrated into multiple features</li><li>We needed to maintain business continuity</li><li>The new feature had to be testable and maintainable</li></ul><blockquote>What would be your first consideration in this situation? Would you prioritize quick delivery or code quality?</blockquote><h3>The Solution Journey</h3><p>Let’s walk through the thought process together.</p><h4>Step 1: Interface First</h4><p>Instead of diving straight into the implementation, I proposed creating an interface. Why? Because interfaces give us flexibility and abstraction. They allow us to define <em>what</em> we need without worrying about <em>how</em> it’s implemented.</p><blockquote>Think about it: How many times has an interface saved you from being locked into a specific implementation?</blockquote><h4>Step 2: The Wrapper Pattern</h4><p>Here’s where it gets interesting. We discussed creating a wrapper around the singleton that would implement our new interface. It’s like putting a clean, modern facade on an old building — the structure remains, but you get to work with a fresh interface.</p><blockquote>Have you used the wrapper pattern before? How did it help you deal with legacy code?</blockquote><h4>Step 3: Dependency Injection</h4><p>The final piece of the puzzle was using dependency injection to bring our wrapper into the new feature. This approach made testing a breeze — we could easily mock the wrapper without touching the singleton.</p><h3>The Bigger Picture</h3><p>But here’s what impressed the Technical Manager: this solution wasn’t just about solving today’s problem. It was about setting up for tomorrow’s success. With each new feature, we could:</p><ol><li>Implement the same pattern</li><li>Gradually reduce dependency on the singleton</li><li>Improve the codebase incrementally</li><li>Maintain business continuity</li></ol><blockquote>What long-term benefits do you see in this approach? How would you build upon it?</blockquote><h3>Understanding the Architecture</h3><p>Let’s visualize our solution with a class diagram. This visual representation helps us understand how all the pieces fit together:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*utc4Bt0suc530tT7lDIOsQ.jpeg" /><figcaption>Solution Architecture Diagram</figcaption></figure><h4>Breaking Down the Components</h4><p><strong>1- IConfigurator Interface:</strong></p><ul><li>This is our clean contract that defines what capabilities we need</li><li>Notice how it’s completely independent of the legacy singleton</li></ul><blockquote>Think about it: What other methods would you add to this interface for your use case?</blockquote><p><strong>2- ConfiguratorWrapper:</strong></p><ul><li>Acts as a bridge between old and new</li><li>Implements our new interface while using the legacy singleton</li><li>Provides a clean API for new features</li></ul><p><strong>3- Legacy Configurator:</strong></p><ul><li>The existing singleton we need to work with</li><li>Remains unchanged, minimizing risk to existing features</li></ul><p><strong>4- New Feature:</strong></p><ul><li>Depends only on the interface, not the concrete implementation</li><li>Completely testable through dependency injection</li><li>No direct knowledge of the legacy singleton</li></ul><p><strong>5- Legacy Feature:</strong></p><ul><li>Represents existing codebase, directly coupled to the singleton</li><li>Shows the technical debt we’re avoiding in the new code</li></ul><blockquote>Can you spot similar patterns in your codebase? How would you approach migrating them?</blockquote><h3>Key Takeaways</h3><p>Let’s reflect on what made this solution effective:</p><ol><li><strong>Practical Testability:</strong> The interface-wrapper approach made testing straightforward and reliable.<em> How do you ensure testability in your legacy code projects?</em></li><li><strong>Incremental Progress:</strong><em> </em>We didn’t need to boil the ocean. Small, manageable improvements add up. <em>What’s your experience with incremental vs. big-bang refactoring?</em></li><li><strong>Business First:</strong> The solution kept the business running while improving the technical foundation. <em>How do you balance technical debt with business needs?</em></li></ol><h3>Your Turn</h3><p>Legacy code challenges are universal in our field, and there’s always more than one way to solve them. I’d love to hear your thoughts:</p><ul><li>How have you handled similar situations?</li><li>What other patterns have you found useful when dealing with legacy code?</li><li>What’s your strategy for balancing quick delivery with code quality?</li></ul><p>Share your experiences in the comments below. Let’s learn from each other’s journeys in tackling legacy code challenges!</p><h3>Acknowledgments</h3><p>Special thanks to <a href="https://www.linkedin.com/in/kareem-abd-elsattar-448606146/"><strong>Kareem Abd El Sattar</strong></a> for his valuable collaboration and for designing the diagram that effectively illustrates the solution. His input was instrumental in refining the approach and presenting the concept visually.</p><p>#SoftwareEngineering #LegacyCode #TechnicalInterview #SoftwareArchitecture #CodingBestPractices</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fc5e234e1e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding and Managing Race Conditions in Swift]]></title>
            <link>https://medium.com/@essammohamedomran/understanding-and-managing-race-conditions-in-swift-43e128a12800?source=rss-f97cf1a05be4------2</link>
            <guid isPermaLink="false">https://medium.com/p/43e128a12800</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[race-condition]]></category>
            <category><![CDATA[grand-central-dispatch]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Essam Fahmy]]></dc:creator>
            <pubDate>Thu, 19 Dec 2024 14:15:08 GMT</pubDate>
            <atom:updated>2024-12-22T18:40:50.730Z</atom:updated>
            <content:encoded><![CDATA[<p>Race conditions or data races are common issues in concurrent programming that can lead to unpredictable behavior and bugs. They occur when two or more threads access shared data simultaneously, and at least one of the accesses modifies the data.</p><p>This guide explores various techniques in Swift to prevent race conditions, including the latest actors in Swift Concurrency. Whether you&#39;re building a high-performance app or just starting with concurrency, these solutions will help you safeguard your data and ensure thread safety in your code.</p><h3>The Problem: Race Condition in Action</h3><p>Let’s start with a simple example to illustrate the issue:</p><pre>class Counter {<br>    private var value = 0<br><br>    func increment() {<br>        value += 1<br>    }<br><br>    func getValue() -&gt; Int {<br>        return value<br>    }<br>}<br><br>let counter = Counter()<br>DispatchQueue.concurrentPerform(iterations: 1000) { _ in<br>    counter.increment()<br>}<br><br>print(counter.getValue()) // Output is not 1000!</pre><p>In this example, multiple threads increment the value property of Counter. Since the increment method is not thread-safe, some increments are lost due to simultaneous access.</p><h3>Techniques to Prevent Race Conditions</h3><h4>1. Using DispatchQueue for Thread Safety</h4><p>A serial DispatchQueue ensures that tasks are executed one at a time, avoiding simultaneous access to shared resources.</p><pre>class Counter {<br>    private var value = 0<br>    private let queue = DispatchQueue(label: &quot;com.example.counterQueue&quot;)<br><br>    func increment() {<br>        queue.async {<br>            self.value += 1<br>        }<br>    }<br><br>    func getValue() -&gt; Int {<br>        queue.sync {<br>            value<br>        }<br>    }<br>}<br><br>let counter = Counter()<br>DispatchQueue.concurrentPerform(iterations: 1000) { _ in<br>    counter.increment()<br>}<br><br>print(counter.getValue()) // Always 1000</pre><blockquote><strong>Hint</strong>: Use DispatchQueue when you want simplicity and compatibility with existing code. It’s best for cases where you need thread safety without performance concerns or complex logic.</blockquote><p><strong>Read-Heavy Scenarios? A Concurrent Queue with </strong><strong>.barrier</strong></p><p>The .barrier ensures that a specific task is executed in isolation by blocking all other concurrent tasks from accessing the queue while the barrier task runs. For that moment, it essentially behaves like a serial queue for the task.</p><p>While a serial queue guarantees thread safety by executing tasks one at a time, it processes tasks sequentially. This approach can limit the utilization of system resources. In contrast, a concurrent queue with .barrier enables multiple readers to access shared resources simultaneously while ensuring exclusive access for write operations.</p><pre>class Counter {<br>    private var value = 0<br>    private let queue = DispatchQueue(label: &quot;com.example.counterQueue&quot;, attributes: .concurrent)<br>    <br>    func increment() {<br>        queue.async(flags: .barrier) { <br>            self.value += 1<br>        }<br>    }<br><br>    func getValue() -&gt; Int {<br>        queue.sync {<br>            self.value<br>        }<br>    }<br>}<br><br>let counter = Counter()<br><br>// Use a DispatchGroup to wait for all increments to finish.<br>// Even though we are using a concurrent queue for performance, <br>// we still need to ensure that the increment operations are fully completed <br>// before accessing the final value. The DispatchGroup will help track <br>// when all the increment tasks have finished, even if some write operations <br>// overlap due to the concurrent execution. This ensures that we wait <br>// for all tasks to finish before printing the final value.<br>let dispatchGroup = DispatchGroup()<br><br>// Perform 1000 concurrent increments<br>DispatchQueue.concurrentPerform(iterations: 1000) { _ in<br>    dispatchGroup.enter()  <br>    counter.increment()<br>    dispatchGroup.leave()  <br>}<br><br>// Wait for all increments to finish before printing the value<br>dispatchGroup.wait()<br>print(counter.getValue()) // Always print 1000</pre><p><strong>Explanation:</strong></p><ol><li><strong>DispatchGroup:</strong> A DispatchGroup is used to track when all 1000 tasks have been completed. Each increment enters the group (dispatchGroup.enter()) before starting and leaves the group (dispatchGroup.leave()) when it completes.</li><li><strong>dispatchGroup.wait()</strong>: This makes sure that print(counter.getValue()) only happens after all the concurrent increment operations are finished.</li></ol><p><strong>Why sync or async?</strong></p><p>Although it’s not our main focus today, here’s a quick hint: Whether you’re using a concurrent queue or a serial queue, the key question is:</p><p><strong>Do you need to wait for the result?</strong></p><ul><li>If the result is needed immediately, such as printing a value, use sync.</li><li>If the result can be handled whenever it is completed, then async.</li></ul><p><strong>For example, in the </strong><strong>Counter example:</strong></p><ul><li>getValue uses sync because the value needs to be retrieved and returned immediately.</li><li>increment uses async because the update doesn’t require immediate confirmation.</li></ul><h4>2. Using NSLock for Mutual Exclusion</h4><p>NSLock provides a simple way to lock and unlock a critical section.</p><pre>import Foundation<br><br>class Counter {<br>    private var value = 0<br>    private let lock = NSLock()<br><br>    func increment() {<br>        lock.lock()<br>        value += 1<br>        lock.unlock()<br>    }<br><br>    func getValue() -&gt; Int {<br>        lock.lock()<br>        let currentValue = value<br>        lock.unlock()<br>        return currentValue<br>    }<br>}<br><br>let counter = Counter()<br>DispatchQueue.concurrentPerform(iterations: 1000) { _ in<br>    counter.increment()<br>}<br><br>print(counter.getValue()) // Always 1000</pre><blockquote><strong>Hint</strong>: Use NSLock when you need mutual exclusion in basic scenarios or for simple locking. It’s widely supported, but be cautious of deadlocks if multiple locks are involved.</blockquote><h4>3. Using os_unfair_lock for High Performance</h4><p>os_unfair_lock is a lightweight, low-level lock suitable for performance-critical tasks.</p><pre>import os<br><br>class Counter {<br>    private var value = 0<br>    private var lock = os_unfair_lock_s()<br><br>    func increment() {<br>        os_unfair_lock_lock(&amp;lock)<br>        value += 1<br>        os_unfair_lock_unlock(&amp;lock)<br>    }<br><br>    func getValue() -&gt; Int {<br>        os_unfair_lock_lock(&amp;lock)<br>        let currentValue = value<br>        os_unfair_lock_unlock(&amp;lock)<br>        return currentValue<br>    }<br>}<br><br>let counter = Counter()<br>DispatchQueue.concurrentPerform(iterations: 1000) { _ in<br>    counter.increment()<br>}<br><br>print(counter.getValue()) // Always 1000</pre><blockquote><strong>Hint</strong>: Choose os_unfair_lock when performance is paramount, especially in high-frequency or low-latency operations. It’s faster than NSLock, but requires careful handling as it’s a low-level API.</blockquote><h4>4. Using Actors in Swift Concurrency</h4><p>Actors are designed to isolate mutable states, providing the simplest and most modern solution for avoiding race conditions.</p><pre>actor Counter {<br>    private var value = 0<br><br>    func increment() {<br>        value += 1<br>    }<br><br>    func getValue() -&gt; Int {<br>        value<br>    }<br>}<br><br>let counter = Counter()<br><br>Task {<br>    await withTaskGroup(of: Void.self) { group in<br>        for _ in 1...1000 {<br>            group.addTask {<br>                await counter.increment()<br>            }<br>        }<br>    }<br><br>    print(await counter.getValue()) // Always 1000<br>}</pre><blockquote><strong>Hint</strong>: Use actors when you’re working with Swift 5.5+ and Swift Concurrency. They offer the safest, most modern solution for managing state across threads and are perfect for new codebases.</blockquote><h4>5. Using NSRecursiveLock for Reentrant Code</h4><p>NSRecursiveLock allows the same thread to acquire the lock multiple times without deadlocking, making it useful for recursive methods.</p><pre>import Foundation<br><br>class Counter {<br>    private var value = 0<br>    private let lock = NSRecursiveLock()<br><br>    func increment() {<br>        lock.lock()<br>        value += 1<br>        lock.unlock()<br>    }<br><br>    func getValue() -&gt; Int {<br>        lock.lock()<br>        let currentValue = value<br>        lock.unlock()<br>        return currentValue<br>    }<br>}<br><br>let counter = Counter()<br>DispatchQueue.concurrentPerform(iterations: 1000) { _ in<br>    counter.increment()<br>}<br><br>print(counter.getValue()) // Always 1000</pre><blockquote><strong>Hint</strong>: Use NSRecursiveLock when you have recursive methods that require multiple lock acquisitions on the same thread. It’s a more specialized solution compared to NSLock.</blockquote><h4>6. Using DispatchSemaphore for Resource Access Control</h4><p>DispatchSemaphore can be used to limit access to a shared resource.</p><pre>import Dispatch<br><br>class Counter {<br>    private var value = 0<br>    private let semaphore = DispatchSemaphore(value: 1)<br><br>    func increment() {<br>        semaphore.wait()<br>        value += 1<br>        semaphore.signal()<br>    }<br><br>    func getValue() -&gt; Int {<br>        semaphore.wait()<br>        let currentValue = value<br>        semaphore.signal()<br>        return currentValue<br>    }<br>}<br><br>let counter = Counter()<br>DispatchQueue.concurrentPerform(iterations: 1000) { _ in<br>    counter.increment()<br>}<br><br>print(counter.getValue()) // Always 1000</pre><blockquote><strong>Hint</strong>: Use DispatchSemaphore when you need to control access to a limited resource or manage concurrency by limiting the number of threads accessing a shared resource at the same time.</blockquote><h3>Choosing the Right Solution</h3><p>The table below summarizes the above techniques and highlights when to use each approach, its key advantages, and potential drawbacks, helping you quickly decide the best solution for your specific use case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oG32r_04HpmffFlCvr4Bxw.png" /><figcaption>A Comprehensive Comparison of Race Condition Solutions in Swift</figcaption></figure><p>By understanding and applying these techniques, you can avoid race conditions and build robust concurrent systems in Swift.</p><h3>Acknowledgments</h3><p>I would like to extend my heartfelt thanks to the reviewers for their valuable feedback and insights, which helped shape this guide. Special thanks to Kareem Abd El Sattar, and Ibrahim El Geddawiy for their time and expertise in reviewing the content.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43e128a12800" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[String — Encoding from zero to hero]]></title>
            <link>https://medium.com/@essammohamedomran/string-encoding-from-zero-to-hero-f205bc6d90a2?source=rss-f97cf1a05be4------2</link>
            <guid isPermaLink="false">https://medium.com/p/f205bc6d90a2</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[encoding]]></category>
            <category><![CDATA[string]]></category>
            <dc:creator><![CDATA[Essam Fahmy]]></dc:creator>
            <pubDate>Wed, 08 Apr 2020 15:26:19 GMT</pubDate>
            <atom:updated>2020-04-08T15:26:19.966Z</atom:updated>
            <content:encoded><![CDATA[<h3>String — Encoding from zero to hero</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*aLm26iD5N5-NO5Qb1cRaFA.jpeg" /></figure><h3>String!</h3><p>Really? Are you joking with me! No, I promise. I am here to discuss more than that pretty stuff you find everywhere on the internet. I am here to give you a solid base of strings (a piece of must-to-know knowledge) and how they work behind the scenes and that what makes a normal developer, solid one (how things work behind the scenes).</p><p><strong>String definition.</strong></p><p>As we all know, String is a type you use everywhere in your code to store your text data (e.g., your name, your address and more).</p><h3>How computers represent strings?</h3><p>A string is a sequence of characters but when we talk with computers, we need to convert each character to a computer’s own language (digital) and this is done by simply assigning each character a different number.</p><h3>Unicode</h3><p>If a computer wants the letter ‘a’ to be represented by the number 10 then so be it but when two computers start talking to each other, they need to agree about that mapping.</p><p><strong>Consider the following example:</strong></p><ul><li>Computer A: send 10 to computer B</li><li>Computer B: You mean ‘a’, right?</li></ul><blockquote>They use the same mapping. They both know that ‘a’ is represented by 10.</blockquote><ul><li>Computer A: Right ;]</li></ul><p><strong>Unicode standard</strong></p><p>The most modern standard computers agree on, is <strong>“Unicode”</strong>. It is a standard that assigns one number (called <strong>code point</strong>) to every character in the world. Now you need to represent these code points using bytes to store them in memory, that’s called <strong>Encoding </strong>(Next section, we will dive into different encoding methods and comparing them against others). The maximum valid Unicode code point (until now) is 1114111 (or 0x10FFFF in hexadecimal) and it consumes 21 bits.</p><p><strong>For example:</strong></p><p>Unicode map the letter ‘a’ to 97 and represents it as 1100001 in Binary. The number associated with each character is known as <strong>Code Point</strong> so, we can say “letter ‘a’ uses code point 97”.</p><p><strong>ASCII VS Unicode.</strong></p><p>It is also worth to mention another old standard called “ASCII”. ASCII originally used seven bits to encode each character which defines 128 unique characters (limited number of characters to represent) and as you figured out this is not enough so Unicode came in the picture with a big pocket to support Chine letters, Arabic letters, Emotions and more.</p><h3>Encoding</h3><p>It’s all about “How to store a string in memory?”.</p><p>Our string is a collection of Unicode code points (remember, code points are the associated numbers with characters).</p><p><strong>For example:</strong></p><ul><li>The word “cafe”.</li><li>The Unicode representation:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*ThNCOwrfVd6CiZQBvOZSfw.png" /><figcaption>Unicode representation for word “cafe”</figcaption></figure><p><strong>How computers represent code points in memory, UTF-32.</strong></p><p>If you are only ever using low code points (from 0 up to 128), such as if your text contains only Latin characters, then you can get away with using only 8 bits per code point. Numeric types in most programming languages come in sizes of addressable, powers of -2 bits, such as 8-bits, 16-bits, and 32-bits and because we know that the maximum valid code point right now is a 21-bit, we can store our string in [UInt32]. Every individual code point is in a 32-bit integer (each of these integers is what is known as a <strong>code unit</strong>). This encoding schema is known as <strong>UTF-32</strong>.</p><p><strong>UTF-32 downside.</strong></p><ul><li>Unfortunately, <strong>UTF-32</strong> is not a good approach to store strings! Why? Because it has inefficient memory usage!</li><li>Let’s represent the word “cat”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*clPRqLmQ4lzJsMl132bNFQ.png" /><figcaption><strong>UTF-32 downside — </strong>Unicode representation for word “cat”</figcaption></figure><p>Did you see how much space is useless! (zeros are unused bits) Once you represent a string that uses low code points (it does not use all available 32 bits), you will have much space that is not useful (empty space you cannot use anymore).</p><p>For that, here is another schema for you ;]</p><h3>UTF-8</h3><p>This schema uses only 8-bit to represent a code point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*4tinFpqsqNzYO4hKLmVEbg.png" /><figcaption>UTF-8</figcaption></figure><p>We saved a lot of space by storing our characters in 8 bits (UTF-8) rather than 32 bits (UTF-32). But how do we store code points that need more than 8 bits?</p><p><strong>UTF-8 diagrams.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*sx9NkGVYk2aeYgnT-LpHcg.png" /><figcaption><strong>UTF-8 diagrams</strong></figcaption></figure><p><strong>According to the diagrams above:</strong></p><ol><li>up to 7-bit code points use 1 UTF-8 code units (the first diagram).</li><li>8- to 11-bit code points use 2 UTF-8 code units (the second diagram).</li><li>12- to 16-bit code points use 3 UTF-8 code units (the third diagram).</li><li>17- to 21-bit code points use 4 UTF-8 code units (the fourth diagram).</li></ol><p><strong>For example:</strong></p><ul><li>The code point 0x00BD (in Hex-Decimal) represents the ‘½’ character.</li><li>In binary, this is 1011 1101 (8 bits)</li><li>Here is our rule:</li></ul><blockquote><em>“if code point is above 7 bits, a schema uses up to 4 code units”.</em></blockquote><ul><li>So, to store our 8-bit code point, we will use the second diagram.</li><li>Our code point is in binary: 1011 1101</li><li>Our schema diagram:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*4LvEK4GnDfokUOWzIXxvEQ.png" /></figure><p>The first 6 bits (111101) in our code point (from right) are stored in code unit №1 (look at our diagram from right) and the remaining bits (10) are stored in code unit №2.</p><p>That’s it ;]</p><p><strong>Print code units of character.</strong></p><ul><li>Would you like to see that in action!</li></ul><pre>/// &#39;½&#39; character let char = &quot;\u{00bd}&quot; <br>for codeUnit in char.utf8<br>{ <br>  print(codeUnit)<br>}</pre><p><strong>Output:</strong></p><pre>194 <br>189</pre><p><strong>What does this output say?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*ZwYUmKNYCMhIVJ08OMQrqg.png" /><figcaption>code units</figcaption></figure><p><strong>Examine another example (upside-down face emoji): ‘🙃’</strong></p><ul><li>The corresponding code point: 0x1F643 (Hex-Decimal)</li><li>In Binary: 1 1111 0110 0100 0011</li><li>It requires 17 bits so we will use the fourth diagram of UTF-8 schema diagrams.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*dQMEUuY64q43PlVIOW5aog.png" /><figcaption>UTF-8 schema diagrams</figcaption></figure><p><strong>In action!</strong></p><pre>/// upside-down face emoji <br>let char = &quot;\u{1F643}&quot; <br>for codeUnit in char.utf8 <br>{ <br>  print(codeUnit) <br>}</pre><p><strong>Output:</strong></p><pre>240 <br>159 <br>153 <br>131</pre><p><strong>What does this output say?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*TeJCFY46jv1IqKaG0nh8aQ.png" /><figcaption>code units</figcaption></figure><p>I have a gift for you. Check <a href="https://www.codeguru.com/cpp/misc/misc/multi-lingualsupport/article.php/c10451/The-Basics-of-UTF8.htm">here</a>, you will find an animation illustrate the<br><strong>UTF-8</strong> algorithm to encode a string. Awesome!</p><p>Does <strong>UTF-8</strong> have any downsides! Of course, it has but I will not discuss it here (google it) rather than we will dive into another popular amazing encoding schema. Bring your coffee!</p><h3>UTF-16</h3><p>You got it. It uses 16-bit code units.</p><p>If you are going to represent an up-to 16-bit code point, that’s pretty simple.</p><p><strong>How UTF-16 works.</strong></p><ul><li>The character ‘+’</li><li>The corresponding code point: 43 (Decimal)</li><li>The Binary form: 10 1011 (6 bits)</li></ul><p><strong>So, we will represent it using a single code unit.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*mBNLIkV7yTCD9ajN6uvnIQ.png" /><figcaption><strong>UTF-16</strong></figcaption></figure><p>What about code points of 17- to 21-bit?</p><p><strong>Some history to consider.</strong></p><p>In the past, all Unicode characters could be held by only 16 bits (from 0000 to FFFF) (0 to 65,535 in decimal). Unfortunately, over time, Unicode grew beyond 65,535 characters (Valens came in the picture. e.g., <a href="https://en.wikipedia.org/wiki/Ideogram">Ideographs</a>). The classic Unicode characters with code points 0000 (0) to FFFF (65, 535) are represented using a single code unit as we have seen in the previous example. Characters with code points 10000 (65,536) to 10FFFFF (1,114,111) are known as supplementary characters.</p><p>The supplementary characters are encoded as consecutive pairs of code units. Each of the values is in such an encoding pair falls into a range of 2048 <strong>unused values</strong> of the basic classic characters 16-bits, called the surrogate area. For the first code unit (high surrogate), D800 (55296) to DBFF (56319). For the second code unit (low surrogate), DC00 (56320) to DFFF (57343). This is clever because you can immediately tell whether a code unit encodes a single character or whether it is the first part of a supplementary character.</p><p><strong>UTF-16 surrogate schema algorithm.</strong></p><ul><li>The character ‘🙃’</li><li>The corresponding code point: 1F643 (Hex-Decimal)</li><li>The Binary form: 1 1111 0110 0100 0011 (17 bits)</li><li>It uses a 17-bit code point so we will store it using surrogate schema.</li></ul><p><strong>To find out the surrogate pairs for this code point, you apply the following algorithm:</strong></p><ol><li>Subtract 0x10000 to give 0x0F643, or 0000 1111 0110 0100 0011 in binary.</li><li>Split these 20 bits into two. This gives you 0000 1111 01 and 10 0100 0011.</li><li>Take the first and add 0xD800 to it, to give 0xD83D. This is your high surrogate.</li><li>Take the second and add 0xDC00 to it, to give 0xDE43. This is your low surrogate.</li></ol><p>So, in <strong>UTF-16</strong>, that upside-down face emoji is represented by the code unit 0xD83D followed by 0xDE43 and whenever we see 0xD83D, we can immediately know that this code unit encodes the first part of a supplementary character (The first part falls in D800 (55296) to DBFF (56319)).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*Urv6ABuhKTgmONNgYGB0GA.png" /><figcaption><strong>UTF-16 surrogate schema</strong></figcaption></figure><p><strong>Memory usage with UTF-8 and UTF-16.</strong></p><p>The memory usage with UTF-8 and UTF-16 is often different. For example, strings comprised of code points of 7 bits or less will take up twice the space in UTF-16 than they would in UTF-8. For a string made up of code points 7 bits or less, the string has to be entirely made up of those Latin characters contained in that range. Even the “£” sign is not in this range! So, often the memory usage of UTF-16 and UTF-8 are comparable.</p><h3>Cut</h3><p>Finally, as an iOS engineer, I have to say that Swift is one of the programming languages that actually use UTF-16 because it hits a sweet spot between memory usage (UTF-32) and complexity of operations (UTF-8).</p><p>Hope this was useful and interesting. See you guys 😁👋</p><p><em>Originally published at </em><a href="https://www.linkedin.com/pulse/string-encoding-from-zero-hero-ess-m-mohamed-fahmi/"><em>https://www.linkedin.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f205bc6d90a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Big Picture of OOP]]></title>
            <link>https://medium.com/@essammohamedomran/the-big-picture-of-oop-252d2029d30e?source=rss-f97cf1a05be4------2</link>
            <guid isPermaLink="false">https://medium.com/p/252d2029d30e</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[object-oriented]]></category>
            <dc:creator><![CDATA[Essam Fahmy]]></dc:creator>
            <pubDate>Wed, 26 Jun 2019 20:32:45 GMT</pubDate>
            <atom:updated>2019-07-04T09:12:58.298Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l5XvhYturdE29V2eE4Gxnw.jpeg" /></figure><p>When I was studying object-oriented programming course at school, I always got questions from my colleagues like :</p><ul><li>“What is the meaning of OOP ?”</li><li>“What is the difference between normal coding (procedural programming) and OOP ?”</li></ul><p>And I have never forgot my answer !</p><ul><li>“Have u create a class ?”</li><li>“Yes, I have !”</li><li>“Welcome to OOP world.”</li></ul><h3>Object-Oriented Programming (OOP)</h3><p>Object-oriented programming is simply the art of making and using objects. In other funny words, is to make your code oriented to object.</p><h3>Classes and Objects</h3><p>The object is a single unit of data and functions that operate on that data.<br>To create an object, you need a class ! The object has the same relationship to a class that a variable has to a data type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*oj8wU56saFMGDvVjzlj8SA.png" /></figure><p>So ? yes, the object is an instance of a class.<br>No more bla ! Let’s do some action 🤩</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*-1YcY_4asrg7XWAmnjgpgw.png" /></figure><p>Now, we have created our class (the new data type 😉)<br>Let’s use it …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*fw84Tqm1I_8l9H386QOEjw.png" /></figure><p>That’s it 🕺</p><h3>What’s Going On ?</h3><p>One benefit of OOP is the close corresponding between real-world objects and OOP classes 🙄</p><p>Think in terms of objects. For example, if you are developing a program that works around user, that’s a mark to go on and create a class (close correspondence)</p><p>In our example, we have created a class called “person” and we have added the attributes of person we concerns about in the object data and because of we have two operations which play around each person, we created two functions in our class.</p><p>Thanks to OOP, the close correspondence makes the process easy and awesome 😍</p><h3>Behind The Code !</h3><p>By encapsulating the data and the functions that operate on that data into a single unit, let’s see what we have achieved yet !</p><ol><li>Restricted access</li><li>Re-usability</li><li>Data hiding</li></ol><h4>1. Restricted Access</h4><p>Our functions have only an access to the data in object. In procedural programming, the functions have unrestricted access to global data which may be defined to be used by another function 🤮</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*ahXFrvPyOTKppWHPROZdYg.png" /></figure><p>In OOP, the functions have the right access to the right data 🤓</p><h4>2. Re-usability</h4><p>Once a class has been written, created and debugged, you can reuse it in other programs and it can also be distributed to other developers (I make this kind of work every new project 😅)</p><h4>3. Data Hiding</h4><p>You can not access the data in the class directly, you can only access “name” and “age” (defined in the class) through the member functions (functions that are defined in the class are called member functions)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*SFJz8HUotNcgx6NE1ssd8g.png" /></figure><p>Literally, you hide the data from the outer world !<br><em>Why ?</em> That makes our data safe from accidental alteration 🤠</p><h3>Cut 😳</h3><p>Our journey has ended, I hope it was awesome for u (as it acted for me).<br>The main goal behind this article is to understand the world of OOP and how it works (beginner guide) and remember that’s not the whole thing about OOP, it’s only … u know, <strong>The Big Picture </strong>🖐</p><p>My expectation is to understand OOP with a percentage above 50%, that’s cool and this is a great start to work around !</p><p>There is a lot to read and a lot to learn about OOP, I wish the road is now more clear and dust free than before … see u 😍</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=252d2029d30e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift — Installing and using VLCKit for tvOS, iOS and macOS]]></title>
            <link>https://medium.com/@essammohamedomran/swift-installing-and-using-vlckit-for-tvos-ios-and-macos-dc805e9ca117?source=rss-f97cf1a05be4------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc805e9ca117</guid>
            <category><![CDATA[vlc]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[tvos]]></category>
            <dc:creator><![CDATA[Essam Fahmy]]></dc:creator>
            <pubDate>Wed, 22 May 2019 08:53:19 GMT</pubDate>
            <atom:updated>2019-05-22T08:53:19.553Z</atom:updated>
            <content:encoded><![CDATA[<h3>Swift — Installing and using VLCKit for tvOS, iOS and macOS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tExCAYHLgC6aWQaeQZNXgQ.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FTmdSnCw-Mjw%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DTmdSnCw-Mjw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FTmdSnCw-Mjw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/263730b912f4828946de5bd3a805e458/href">https://medium.com/media/263730b912f4828946de5bd3a805e458/href</a></iframe><p>If you are an iOS developer who is preparing to establish a video streaming application, you probably started by using AVPlayer from AVFoundation framework for the video streaming but u have ended up with problem of support limitation. Right ?</p><p>AVPlayer doesn’t support a lot of media so that developers start thinking of another media player.</p><p>VLCMediaPlayer from VLC SDK !<br>VLC Media Player supports a very wide range of media.</p><p>The problem : There is no a well-explained reference (you may say, there is no any reference at all !) to guide u how to install and using the SDK.</p><p>I have faced the same problem like u and I started searching a lot and a lot. Every time, I find people saying “bla bla bla bla…” which made it worse !</p><p>Fortunately and eventually, I ended up with understanding the process very well and guess what ? It’s a very easy ! And to make it easy for every one else, i have decided to document it.</p><p>I will guide u guys step by step through the process of installing and using VLCKit, MobileVLCKit and TVVLCKit. Keep in touch !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc805e9ca117" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>