<?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 Sunday Ndu on Medium]]></title>
        <description><![CDATA[Stories by Sunday Ndu on Medium]]></description>
        <link>https://medium.com/@ndusundayDev?source=rss-4589e4ece6fe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*62Yu9ccriHjXVYuWfr1vbw.jpeg</url>
            <title>Stories by Sunday Ndu on Medium</title>
            <link>https://medium.com/@ndusundayDev?source=rss-4589e4ece6fe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 04:52:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ndusundayDev/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[Beyond the Boot Sequence: My Exploration of systemd Architecture, Diagnostics, and Security]]></title>
            <link>https://medium.com/@ndusundayDev/beyond-the-boot-sequence-my-exploration-of-systemd-architecture-diagnostics-and-security-e052f783015c?source=rss-4589e4ece6fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/e052f783015c</guid>
            <category><![CDATA[linux-kernel]]></category>
            <category><![CDATA[system-engineering]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[systemd-service]]></category>
            <dc:creator><![CDATA[Sunday Ndu]]></dc:creator>
            <pubDate>Fri, 07 Aug 2026 14:49:44 GMT</pubDate>
            <atom:updated>2026-08-09T12:01:01.800Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction: The Reality of PID 1</h3><figure><img alt="Visualizing the systemd ecosystem: Orchestrating web, application, and database services through unified dependency mapping and declarative control." src="https://cdn-images-1.medium.com/max/1024/0*vg2VsrVk2xy2PV8h.png" /><figcaption>Visualizing the systemd ecosystem: Orchestrating web, application, and database services through unified dependency mapping and declarative control.</figcaption></figure><p>Every time you boot your Linux machine, a silent orchestration takes place. For most modern distributions(Ubuntu, Debian, Fedora, Arch Linux, and openSUSE), systemd is responsible for this orchestration. It is the very first daemon to start with the reserved process ID 1 (PID 1).</p><p>Most people will know systemd as &quot;that tool I use to restart Nginx or PostgreSQL.&quot; Other people will know it for managing targets and dependencies. But if we pull back the curtain, systemd isn&#39;t just an init system; it is a massive software suite that acts as an operating system abstraction layer, managing everything from logging with journald to network states with networkd.</p><pre>pstree -p | head -n 10</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vN3XFJUM4cjX_sGp.png" /><figcaption>The pstree command shows systemd (PID 1) at the top of the process tree.</figcaption></figure><p>While systemd is often the subject of intense debate among Linux purists for violating the traditional Unix philosophy of “do one thing and do it well,” its structural predictability and robust feature set are undeniable.</p><p>The focus of this article is to explore and show how systemd handles units as declarative code. We will skip the generic history lessons to look under the hood at advanced diagnostics and how sandbox processes are handled natively.</p><h3>The Mental Model: Units as Code</h3><p>To truly understand <strong>systemd</strong>, you have to fix the mental model that sees services as procedural bash scripts. In the old SysVinit days, starting a service meant executing a complex shell script located in /etc/init.d/. If a service crashed, you had to write custom loop logic to restart it.</p><p>systemd changes the game by introducing the <strong>declarative approach</strong> for defining services. Everything it manages, whether it is a background daemon, a background timer (modern replacement of cron), a network storage mount, or a hardware device, is defined as a Unit.</p><p>You don’t have to manually write code to start a service; you declare its desired state in a plain-text config file.</p><h3>The Directory Hierarchy (Where the Magic Lives)</h3><p>This is where things get interesting, and you can follow along. systemd unit files are organized into a strict hierarchy that dictates which file takes precedence. Run this command to see the three primary directories where unit files reside.</p><pre>ls -l /lib/systemd/system/ /etc/systemd/system/ /run/systemd/system 2&gt;/dev/null | grep -E &#39;^/|total&#39; -A 3</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*amoBQR8NiK6fL1v9.png" /></figure><p>Here is how the hierarchy works under the hood:</p><ol><li>/lib/systemd/system or /usr/lib/...: This is the system vendor directory. When you install a package like Apache or Docker via apt or dnf, their default unit files are placed here. Never edit the files in this directory directly; your changes get overwritten by vendor updates, and this happens more often than you can keep track.</li><li>/etc/systemd/system/: This is your territory as a local admin. Files placed here override files of the same name in the vendor&#39;s /lib/. This is where we will build our custom unit file later.</li><li>/run/systemd/system: This is the Runtime volatile units. These are generated dynamically at boot or during operation(e.g transient services) and disappear when the system is rebooted. If you notice the result of the last command above, my /run/systemd/system result has a total of 0, but if you try it on your machine, it might be around 10-16 total. In my case, this is a new system spawned for this article. You can also spawn a quick system at <a href="https://distrosea.com/">https://distrosea.com/</a>.</li></ol><h4>Active vs Loaded States</h4><p>Before we build anything, let’s look at how systemd tracks these units. People(including me at some point) often confuse a service being loaded with a service being active. Let&#39;s inspect a core system service like the SSH daemon to see the distinction clearly. Run this command to see the status of a service using the systemctl status command:</p><pre>sudo systemctl status sshd || sudo systemctl status ssh</pre><figure><img alt="Terminal window highlighting the difference between Loaded and Active" src="https://cdn-images-1.medium.com/max/1024/0*iCgFwDdrXXKEQilE.png" /><figcaption>Terminal window highlighting the difference between Loaded and Active</figcaption></figure><p>Notice how systemd explicitly tells you exactly which unit file configuration path it loaded from the hierarchy, followed by its current runtime process state. If you edit a unit file on disk, systemd will warn you that the configuration is out of sync until you run systemctl daemon-reload to update its internal cache.</p><p>With this mental model established, let’s proceed to building our own custom service from scratch.</p><h3>Custom Unit Blueprint (Building a Service From Scratch)</h3><p>You can look through the existing services to see how services are declared, but let’s build our custom background daemon. We will create a simple web server, register it with systemd, and leverage production-grade configurations that are essential for most services. We will be building a simple Python web server; however, you can also use your existing or new server in your preferred language. I will provide the code to run and focus on its purpose, not the details.</p><p>Let’s run this code to create the <strong>my-app</strong> directory (or your preferred name) to hold the Python <strong>server.py</strong> file (or preferred name too) with a very basic server implementation.</p><pre>sudo mkdir -p /opt/my-app<br>sudo tee /opt/my-app/server.py &lt;&lt; &#39;EOF&#39;<br>import http.server<br>import socketserver<br><br>PORT = 8080<br>Handler = http.server.SimpleHTTPRequestHandler<br><br>print(f&quot;Starting application server on port {PORT}...&quot;)<br>with socketserver.TCPServer((&quot;&quot;, PORT), Handler) as httpd:<br>    httpd.serve_forever()<br>EOF</pre><p>Confirm the server runs correctly by executing it directly first: /usr/bin/python3 /opt/my-app/server.py. If port 8080 is already in use on your machine (for example, by another instance of this same script left running from a previous test), you&#39;ll see OSError: [Errno 98] Address already in use; in that case, stop the other process or temporarily change PORT in server.py before continuing. For the rest of this walkthrough, we&#39;ll assume port 8080 stays free.</p><h4>Writing the Production-Grade Unit File</h4><p>Now, we will leverage the directory hierarchy we discussed earlier. We will place our configuration inside <strong><em>/etc/systemd/system/</em></strong> so it takes top priority. Create the service unit file using this command(you can also choose to use vim or nano):</p><pre>sudo tee /etc/systemd/system/myapp.service &lt;&lt; &#39;EOF&#39;<br>[Unit]<br>Description=Our Simple Python Web Server<br>After=network.target<br><br>[Service]<br>Type=simple<br>ExecStart=/usr/bin/python3 /opt/my-app/server.py<br>Restart=on-failure<br>RestartSec=5s<br><br>[Install]<br>WantedBy=multi-user.target<br>EOF</pre><h4>Breaking Down the Directives</h4><p>You will notice the unit file is grouped into different sections: Unit, Service, Install, which is a similar flow for declarative config files. I would advise you to check them out outside the scope of this write-up. <strong>Check </strong><a href="https://www.digitalocean.com/community/tutorials/understanding-systemd-units-and-unit-files#anatomy-of-a-systemd-unit-file">DigitalOcean: Anatomy of Unit File</a>.</p><p>While the syntax looks clean, the power lies in how <strong>systemd</strong> handles orchestrating this process(server process):</p><ul><li><strong>After=network.target</strong>: This orders our service to start after the network <em>management stack</em> has initialized. Note that this doesn’t guarantee an interface actually has an IP or that connectivity is usable, a common systemd misconception. We’re using the simpler network.target here since this demo doesn&#39;t depend on real network access at startup; if your own service genuinely needs working connectivity before it starts, reach for Wants=network-online.target and After=network-online.target instead.</li><li><strong>Type=simple</strong>: Instructs systemd that the process started by ExecStart is the main process of the service. Explore the other possible options in the link shared above.</li><li><strong>Restart=on-failure</strong>: This is automatic process supervision. If our Python script crashes or exits with a failure, including being killed by a signal like SIGKILL, systemd will automatically resurrect it.</li><li><strong>RestartSec=5s</strong>: Prevents crash-looping by waiting 5 seconds before attempting a restart.</li><li><strong>WantedBy=multi-user.target</strong>: Defines the “hook” point. Enabling this service hooks it into the non-graphical multi-user boot phase (the equivalent of traditional runlevel 3).</li></ul><h3>Activating and Testing the Service</h3><p>Because we created a brand new file on disk, we must tell systemd to rebuild its memory cache. <strong>Always remember to run this reload command (<em>sudo systemctl daemon-reload</em>) if you make changes to your unit files</strong>. Run these lifecycle commands:</p><pre># Reload the daemon cache<br>sudo systemctl daemon-reload<br><br># Start the service right now<br>sudo systemctl start myapp.service<br><br># Enable it to start automatically on every system boot<br>sudo systemctl enable myapp.service</pre><p>Now, let’s verify that our custom daemon is active and running under PID 1’s supervision:</p><pre>systemctl status myapp.service</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /><figcaption>systemd status showing the status of the myapp.service</figcaption></figure><p>To prove our Restart=on-failure directive works, you can simulate a crash by killing the process manually via its PID, then running systemctl status again to watch systemd bring it back online automatically. <br><strong>Note</strong>: kill &lt;PID&gt; sends SIGTERM by default. Even though this will still terminate our simple script, systemd treats a SIGTERM-caused exit as an intentional stop rather than a failure, so Restart=on-failure will <em>not</em> trigger. To verify the directive, use kill -9 &lt;PID&gt; (SIGKILL) instead, which systemd treats as a failure worth restarting.</p><h4>Diagnostic Gold: systemd-analyze &amp; Advanced Logging</h4><p>One benefit of allowing <strong>systemd</strong> to manage your service is built-in logging, as <strong>systemd</strong> initializes your service and manages logging with journalctl — a centralized, fast diagnostic log tool. <br>Let’s look at how to profile system performance and master advanced log filtering.</p><h4>Profiling the Boot Process</h4><p>If your machine is booting slowly, you do not have to guess which service is the culprit. <strong>systemd</strong> records precise timestamps for every single component during startup. First, let’s look at the overall time your system took to reach a usable state.</p><pre>systemd-analyze</pre><pre>systemd-analyze blame | head -n 10</pre><pre>5.973s NetworkManager-wait-online.service<br>3.955s fstrim.service<br>2.755s NetworkManager.service<br>1.528s cloud-init-main.service<br>1.131s caddy.service<br> 836ms apt-daily-upgrade.service<br> 780ms e2scrub_reap.service<br> 761ms apt-daily.service<br> 714ms udisks2.service</pre><p>If you are looking for structural dependencies, blame doesn&#39;t tell the whole story because some services start in parallel. To see the critical path of sequential dependencies slowing down your boot, run:</p><pre>systemd-analyze critical-chain</pre><h4>Journalctl Mastery: Advanced Filtering</h4><p>Instead of using cat or grep on flat syslog files, journald stores logs in a structured binary format. This allows you to query logs instantly based on metadata, time windows, or severity. <br>Let&#39;s look at three advanced logging commands that will elevate your troubleshooting workflow:</p><ol><li><strong>Time-Bound Filtering</strong>: Need to see what crashed during a specific deployment window or incident? You can filter logs using human-readable time variables:</li></ol><pre>journalctl --since “1 hour ago”</pre><ol><li><strong>Real-Time Tracking with Unit Isolation</strong>: To follow the live outputs of our custom application (myapp.service) that we built earlier, run:</li></ol><pre>journalctl -u myapp.service -f</pre><ol><li><strong>Filtering by Severity Levels (Expert Pick)</strong>: If a system is noisy, you can filter out informational messages and display only errors, critical faults, or emergencies across the entire OS:</li></ol><pre>journalctl -p err..emerg --since today</pre><p>Using these binary queries means you no longer have to manually rotate, compress, or parse text strings; journald does the heavy lifting for you at the engine level.</p><h4>The Killer Feature: Security Sandbox</h4><p>When developers think about isolating an application for security, they immediately jump to containerization tools like Docker or Podman. While containers are great, they introduce architectural overhead. <br>One of <strong>systemd’s</strong> most powerful, underutilized capabilities is its native Linux kernel sandboxing integration. <strong><em>With just a few lines of declarative configuration, you can strip a service of its network privileges, lock down the filesystem, and prevent unauthorized exploits.</em></strong></p><h4>Auditing Your Current Exposure</h4><p>Before we harden our service, let’s see how systemd views the security posture of the applications running on your machine right now. Run this built-in security analyzer:</p><pre>systemd-analyze security | head -n 15</pre><pre>UNIT                                  EXPOSURE PREDICATE HAPPY<br>ModemManager.service                       6.3 MEDIUM    :-|<br>NetworkManager.service                     7.8 EXPOSED   :-(<br>accounts-daemon.service                    5.3 MEDIUM    :-|<br>getty@tty1.service                         9.6 UNSAFE    :-{<br>lightdm.service                            9.6 UNSAFE    :-{<br>myapp.service                              9.6 UNSAFE    :-{<br>nfs-blkmap.service                         9.5 UNSAFE    :-{</pre><p>This command evaluates your service configurations against modern Linux kernel security modules (like cgroups, namespaces, and Seccomp filters). If you look at our custom myapp.service, it has a high (<strong>9.6</strong>) unsafe score because it currently has full access to the system.</p><h4>Hardening the Custom Service File</h4><p>Let’s fix that. We can drastically reduce the attack surface of our Python web server by appending sandboxing directives to its service file. <br>Run this command or update the file directly with the content of the <strong><em>EOF</em></strong> to update <strong><em>/etc/systemd/system/myapp.service</em></strong> with advanced security controls:</p><pre>sudo tee /etc/systemd/system/myapp.service &lt;&lt; &#39;EOF&#39;<br>[Unit]<br>Description=My Custom Hands-On Python Web Server<br>After=network.target<br><br>[Service]<br>Type=simple<br>ExecStart=/usr/bin/python3 /opt/my-app/server.py<br>Restart=on-failure<br>RestartSec=5s<br><br># --- SECURITY SANDBOXING ---<br># Give the service its own isolated /tmp directory<br>PrivateTmp=true<br><br># Make the entire OS filesystem read-only to this service, except for runtime paths<br>ProtectSystem=strict<br><br># Block the service from attempting to elevate its privileges (prevents SUID execution)<br>NoNewPrivileges=true<br><br># Prevent the service from accessing home directories (/home, /root)<br>ProtectHome=true<br><br>[Install]<br>WantedBy=multi-user.target<br>EOF</pre><p>Like I said earlier, always remember to run a daemon reload so that systemd is aware of your new config update. <br>Let’s do the daemon reload and restart the <strong>myapp</strong> service:</p><pre>sudo systemctl daemon-reload<br>sudo systemctl restart myapp.service</pre><p>Now, re-run the security analyzer again and look out for the updated rating of our myapp.service. Run: <strong><em>systemd-analyze security | head -n 15</em></strong></p><pre>UNIT                                  EXPOSURE PREDICATE HAPPY<br>getty@tty1.service                         9.6 UNSAFE    :-{<br>lightdm.service                            9.6 UNSAFE    :-{<br>myapp.service                              8.7 EXPOSED   :-(<br>nfs-blkmap.service                         9.5 UNSAFE    :-{</pre><p>As you will notice, the exposure has dropped from the original <strong>9.6</strong> to <strong>8.7</strong>, better, but there is still some room for improvement.</p><p>By adding just four plain-text lines, you have leveraged namespaces and kernel flags to lock the application into a tight security sandbox. Even if an attacker finds an exploit in your Python code, they cannot read home directories, write to the core OS files, or elevate privileges to root.</p><h3>Conclusion &amp; Next Steps</h3><p>Digging beneath the surface of systemd reveals that it is far more than a basic boot manager. While critics often argue its sprawling design deviates from the core Unix philosophy, its real-world implementation provides a highly cohesive toolset for modern systems engineering. By standardizing process declaration, centralizing logging with metadata-rich binaries, and offering native sandbox isolation, systemd acts as a complete control plane for your operating system.</p><p>Mastering these features bridges the gap between simply running a Linux server and truly orchestrating it. The next time you find yourself troubleshooting a broken deployment or deploying a new daemon, skip the generic script wrappers and look toward native declarative units.</p><h4>Deepen Your Reading</h4><p>To continue expanding your knowledge on process tracking, architecture, and advanced unit definitions, check out these excellent external resources:</p><ul><li><a href="https://www.geeksforgeeks.org/operating-systems/introduction-of-process-synchronization/"><strong>⁠GeeksforGeeks: Introduction to Process Synchronization</strong></a> — Understand how the underlying Linux operating system handles cooperative processes, resource concurrency, and race conditions.</li><li><a href="https://www.digitalocean.com/community/tutorials/understanding-systemd-units-and-unit-files"><strong>⁠DigitalOcean: Understanding Systemd Units and Unit Files</strong></a> — A brilliant conceptual deep dive into socket activation, unit dependency graphs, and drop-in configuration overrides.</li></ul><h3>Let’s connect</h3><p>Now it is your turn to jump into the terminal. <br>Run systemd-analyze security on your local machine and let me know your thoughts:</p><ul><li>What was the most surprising vulnerability score you uncovered?</li><li>Do you prefer native systemd sandboxing directives or spinning up lightweight Docker containers?</li></ul><p>Drop your findings, terminal logs, or favorite custom configuration tricks in the comments below!</p><p><em>Originally published at </em><a href="https://sundayndu.substack.com/p/beyond-the-boot-sequence-my-exploration"><em>https://sundayndu.substack.com</em></a><em> on August 7, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e052f783015c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplify Dependency Declarations with Gradle’s Type-Safe Project Accessors]]></title>
            <link>https://medium.com/@ndusundayDev/simplify-dependency-declarations-with-gradles-type-safe-project-accessors-2227859330fe?source=rss-4589e4ece6fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/2227859330fe</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[gradle-plugin]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[gradle]]></category>
            <dc:creator><![CDATA[Sunday Ndu]]></dc:creator>
            <pubDate>Sun, 11 Feb 2024 08:08:46 GMT</pubDate>
            <atom:updated>2024-02-11T08:08:46.589Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="An astronaut untangling cables in space" src="https://cdn-images-1.medium.com/max/1024/1*LBukEE5dcD8mcrbVxH7Rlw.jpeg" /></figure><p>In a big Gradle project, it is recommended to structure the project as a multimodule project. Each module will be included in the project’s settings gradle file(<strong><em>settings.gradle</em></strong> or <strong><em>settings.gradle.kts</em></strong>) and a module can specify other modules as dependencies.</p><pre>// settings.gradle.kts<br>include(&quot;:app&quot;)<br>include(&quot;:core:common&quot;)<br>include(&quot;:core:ui&quot;)<br>include(&quot;:core:testing&quot;)</pre><pre>// build.gradle.kts<br>dependencies {<br>    implementation(project(&quot;:core:cache&quot;))<br>    implementation(project(&quot;:core:common&quot;))<br>    implementation(project(&quot;:core:ui&quot;))<br>}</pre><p>The issue with using this method — <strong><em>project(“:some:path”)</em></strong> to include dependent modules in a build gradle file is that you have to remember the paths to every project you want to depend on. Changing a project path could open you to missing some occurrences across your project or mistyping a path in some places.</p><blockquote>Gradle 7.0 introduced an experimental feature <strong><em>TYPESAFE_PROJECT_ACCESSORS</em></strong> that allows you to create type-safe project accessors in your multi-module gradle projects.</blockquote><p>The typesafe project accessors simplifies <strong><em>project(“:some:path”)</em></strong><em> </em>to <strong><em>project(projects.some.path)</em></strong><em>. </em>The provided <strong><em>projects</em></strong> object allows you to use code completion when setting up project dependency.</p><h3>Configuring type-safe project accessors</h3><ul><li><a href="https://docs.gradle.org/7.0/release-notes.html">Gradle 7.0</a> or higher — this was included in Gradle 7.0 as an experimental feature, therefore Gradle 7.0 and above is needed.</li><li>To use the type-safe project accessors feature, you can add the <strong><em>enableFeaturePreview(“TYPESAFE_PROJECT_ACCESSORS”) </em></strong>to your settings gradle file:</li></ul><pre>// settings.gradle.kts<br>rootProject.name = &quot;ExampleApp&quot;<br>enableFeaturePreview(&quot;TYPESAFE_PROJECT_ACCESSORS&quot;)<br>include(&quot;:app&quot;)<br>include(&quot;:core:common&quot;)<br>include(&quot;:core:ui&quot;)<br>include(&quot;:core:testing&quot;)</pre><p>Enabling the <strong><em>TYPESAFE_PROJECT_ACCESSORS </em></strong>makes it easier and safer to include dependent modules/projects in your build gradle files. This saves time trying to remember paths to modules and removes the possibility of introducing wrong module paths.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*PKIqN7oBWhpBZ5XvDnm61w.gif" /></figure><h3>Bonus information</h3><ul><li>To learn more about Type-safe project dependencies, check— <a href="https://docs.gradle.org/7.0/userguide/declaring_dependencies.html#sec:type-safe-project-accessors">https://docs.gradle.org/7.0/userguide/declaring_dependencies.html#sec:type-safe-project-accessors</a></li><li>With <a href="https://docs.gradle.org/7.0/release-notes.html">Gradle 7.0</a>, version catalogs was also included to help centralize and ease dependency versions in multi-module android projects. For more detail check — <a href="https://docs.gradle.org/current/userguide/platforms.html">https://docs.gradle.org/current/userguide/platforms.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2227859330fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Memory Management in Kotlin: Primitives vs. Complex Data Structures]]></title>
            <link>https://medium.com/@ndusundayDev/demystifying-memory-management-in-kotlin-primitives-vs-complex-data-structures-e3dba8f4e13a?source=rss-4589e4ece6fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3dba8f4e13a</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[memory-management]]></category>
            <dc:creator><![CDATA[Sunday Ndu]]></dc:creator>
            <pubDate>Fri, 06 Oct 2023 09:26:33 GMT</pubDate>
            <atom:updated>2023-10-06T09:26:33.588Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*8GSebllM4D35zGdRY0O5mQ.jpeg" /></figure><p>If you’re a Kotlin developer, you’re likely familiar with the basics of memory management. You know that memory is allocated when you create variables and objects, and it’s automatically deallocated when they go out of scope. But did you know that memory management can vary significantly depending on whether you’re working with primitive types or complex data structures? In this article, we’ll explore this often-overlooked aspect of Kotlin and shed light on the differences between these two categories.</p><h3>The Simplicity of Primitive Types</h3><p>Let’s start with the basics. Primitive types in Kotlin include integers, floats, booleans, and characters. These types have a fixed size and are stored directly in memory. When you create a variable of a primitive type, you’re essentially reserving a specific amount of memory to hold that value. For example:</p><pre>val x: Int = 42</pre><p>In this case, x is a variable of type Int, and it directly holds the value 42 in memory. It&#39;s simple, efficient, and requires no extra memory management on your part.</p><h3>The Complexity of Complex Data Structures</h3><p>Now, let’s shift our focus to complex data structures like objects, mutable objects, arrays, and other custom data types. Unlike primitive types, these data structures are not stored directly in memory. Instead, they require dynamic memory allocation because they can vary in size and structure.</p><p>Consider this example:</p><pre>data class Person(val name: String, val age: Int)</pre><p>When you create an instance of the Person class, Kotlin allocates memory on the heap to store the object&#39;s data. The Person object may contain references to other objects or data structures, and all of this information needs to be managed correctly to avoid memory leaks.</p><h3>References and Pass-by-Reference</h3><p>One key distinction between primitive types and complex data structures is how they are passed around in your code. <strong><em>Primitive types are typically passed by value.</em></strong> When you assign a primitive variable to another variable or pass it to a function, you’re working with a copy of the value. Changing one variable doesn’t affect another.</p><p>For example:</p><pre>var a = 10<br>var b = a // &#39;b&#39; holds a copy of the value &#39;10&#39;<br>b = 20    // &#39;a&#39; remains unaffected</pre><p>In contrast, <strong><em>complex data structures are often passed by reference.</em></strong> When you assign a complex data structure to another variable or pass it to a function, both variables refer to the same object in memory. Changes made through one reference affect the object itself and are visible through other references.</p><p>Consider this code:</p><pre>val alice = Person(&quot;Alice&quot;, 30)<br>val bob = alice // &#39;bob&#39; now refers to the same &#39;Person&#39; object as &#39;alice&#39;<br>bob.age = 35    // &#39;alice&#39; and &#39;bob&#39; both reflect the age change</pre><h3>Memory Management Challenges</h3><p>The differences in memory management between primitive types and complex data structures introduce unique challenges. When working with complex data structures, you need to be mindful of memory allocation and deallocation. While Kotlin’s automatic memory management helps, you still need to consider cases where objects may retain references longer than intended, leading to memory leaks.</p><p>In some languages, like C and C++, manual memory management is the norm, requiring developers to explicitly allocate and deallocate memory. Kotlin, fortunately, abstracts most of these complexities away with its garbage collector. Still, understanding how memory is allocated and released can help you write more efficient and reliable code.</p><h3>Immutability and State</h3><p>Another crucial aspect to consider is immutability. Primitive types are typically immutable, meaning their values cannot be changed after creation. This immutability simplifies memory management because you don’t have to worry about unexpected changes to variables.</p><p>On the other hand, complex data structures can be mutable, allowing their internal state to be modified. While mutability provides flexibility, it also introduces complexity in managing object states and ensuring data consistency.</p><h3>Conclusion</h3><p>Understanding the nuances of memory management in Kotlin is essential for writing efficient and reliable code, particularly when dealing with complex data structures. The differences between primitive types and complex objects, including references, pass-by-reference behavior, and memory allocation, can significantly impact your program’s performance and behavior.</p><p>As a Kotlin developer, take the time to dive deeper into memory management concepts, practice proper memory management, and be vigilant about potential memory leaks in your code. By mastering memory management, you’ll not only write more efficient programs but also gain a deeper understanding of how Kotlin works under the hood.</p><p>In conclusion, while Kotlin abstracts many memory management complexities, knowing the differences between primitives and complex data structures empowers you to write high-quality code that performs optimally and avoids memory-related pitfalls.</p><p>Happy Hacking!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3dba8f4e13a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memory Management in Kotlin Lists: A Comprehensive Guide]]></title>
            <link>https://medium.com/@ndusundayDev/memory-management-in-kotlin-lists-a-comprehensive-guide-cf199b25ba9a?source=rss-4589e4ece6fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf199b25ba9a</guid>
            <category><![CDATA[lists]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[kotlin-native]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Sunday Ndu]]></dc:creator>
            <pubDate>Mon, 18 Sep 2023 15:23:21 GMT</pubDate>
            <atom:updated>2023-09-18T15:23:21.795Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>Kotlin, a versatile and concise programming language, offers powerful data structures like lists for managing collections of elements. Understanding how Kotlin handles memory and space when creating, filling, and modifying lists is crucial for writing efficient and performant code. In this intermediate to expert-level guide, we’ll delve into Kotlin’s list implementation and explore memory management aspects when adding, extending, or modifying lists.</p><p><strong>Creating a Kotlin List</strong></p><p>Let’s start by creating a basic Kotlin list:</p><pre>val myList = mutableListOf&lt;Int&gt;()</pre><p>This line of code initializes an empty mutable list of integers. Now, let’s fill it with elements:</p><pre>myList.add(1)<br>myList.add(2)<br>myList.add(3)</pre><p><strong>Memory Allocation for Lists</strong></p><p>Kotlin lists are backed by arrays, which dynamically adjust their size as elements are added or removed. When you create a list, Kotlin typically allocates an initial array with a fixed size (e.g., 10 elements) to store elements efficiently. <em>As you add more elements, Kotlin automatically resizes the underlying array to accommodate the new data.</em></p><p><strong>Memory Allocation on List Extension</strong></p><p>When you extend a list by adding elements to the end using list.add(element), Kotlin checks if there&#39;s enough space in the underlying array. If there isn&#39;t, it allocates a new, larger array, copies the existing elements to the new array, and adds the new element. This process ensures that the list remains efficient as it grows.</p><p>Here’s an example:</p><pre>myList.add(4) // Adds 4 to the end of the list</pre><p>In this case, if the current array is full, Kotlin would allocate a larger array (usually twice the size), copy the existing elements (1, 2, 3), and then add 4 to the end.</p><p><strong>Memory Allocation on Insertion</strong></p><p>When you add an element at a specific position using list.add(position, element), Kotlin reallocates the array if necessary, but this operation can be less efficient. If you insert an element at the beginning or middle of a list, all subsequent elements need to be shifted to make room for the new element.</p><pre>myList.add(0, 0) // Adds 0 at the beginning</pre><p>In this case, Kotlin would allocate a new array, copy the existing elements (1, 2, 3, 4), insert 0 at the beginning, and update the references accordingly.</p><p><strong>Efficient List Modifications</strong></p><p>If you anticipate frequent insertions or modifications at specific positions, consider using a different data structure, such as a linked list or a deque (double-ended queue), which can provide more efficient insertions without shifting elements.</p><pre>val linkedList = LinkedList&lt;Int&gt;()<br>linkedList.addFirst(0) // Adds 0 at the beginning efficiently</pre><p><strong>Conclusion</strong></p><p>Kotlin’s list implementation combines the benefits of an array-based structure with dynamic resizing to efficiently manage memory and space. When extending lists, Kotlin intelligently reallocates memory as needed, while insertions can involve more complex operations due to element shifting. To write performant code, choose the right data structure based on your specific use case, and be mindful of the potential overhead when inserting elements in the middle of a list.</p><p>Understanding how Kotlin handles memory and space for lists empowers you to write code that’s not only clean and concise but also optimized for performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf199b25ba9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android App Automation with Fabrics- Part 1: Crashlytics]]></title>
            <link>https://medium.com/@ndusundayDev/android-app-automation-with-fabrics-part-1-crashlytics-94e993b41ad9?source=rss-4589e4ece6fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/94e993b41ad9</guid>
            <category><![CDATA[fastlane]]></category>
            <category><![CDATA[crashlytics]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[fabric]]></category>
            <category><![CDATA[automation-tools]]></category>
            <dc:creator><![CDATA[Sunday Ndu]]></dc:creator>
            <pubDate>Tue, 18 Jun 2019 14:22:01 GMT</pubDate>
            <atom:updated>2019-06-18T14:23:12.822Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine adding a feature to your android project and after you have gradle built your code, you had to share the debug-apk to a few of your friends or beta testers every time you have an update. A related scenario is when you give these testers your app to test for you. They can experience some app crashes and you have to contact each of them to get their reviews on each of your projects. This becomes tedious when you have too many beta testers testing your app.</p><p>You would have wondered at some point how you can automate the above scenarios and focus on your coding.</p><p>I will show you how to automate beta testing and get real-time crash reports in your development workflow. This will improve your bug fixing time and buy you more time to improve or expand the project. We will be using fabric tools such as crashlytics and fastlane and in later tutorials, we will explore other tools.</p><p>So let’s get down into coding mood and see what we can achieve with Fabrics. I am going to list the scope of this article and what you need to get started.</p><ul><li>You should already have basic android development knowledge.</li><li>Android Studio installed and ready to start a project and a basic understanding of the IDE will be cool too.</li><li>A Fabric account (visit <a href="http://www.fabric.io)./">www.fabric.io).</a></li><li>Basic knowledge of Kotlin syntax is expected</li></ul><p>With a verified email, that is if you are signing up for a new fabric account. You should get to a point where you will have to select the kind of project you are working on (Android or IOS). This process is the onboarding process. Select android.</p><p>You will get a prompt as shown to install the fabric plugin to proceed from the boarding section. To get through this you get on your android project in your android studio IDE or create a new project if you haven’t. This project is the project you want to automate beta testing on and get crash reports in real time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X-JLtEWZUUv-nBR7Dei3xw.png" /><figcaption>Fabric Onboarding</figcaption></figure><p>With the android project set up, we are ready to include fabric to our project. Add the fabric plugging to your android studio IDE. You will have it added on the right side of you IDE above the gradle navigation. When you click to open the pane you should have this pop out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*JjnUVv65ho-vV1GzmhFh3Q.png" /></figure><p>Enter your login details, you will get to the page that shows you the organization you created while signing up on Fabric. Select the organization of your choice in case you have other options to select from. You can now set up your beta service which by default is Crashlytics from the prompt in your IDE, but other options are HockeyApp and GooglePlay beta service.</p><p>While setting up Crashytics, your build.gradle, Android Manifest and Application or Activity class will be updated. Follow the prompt from the fabric plugin on your android studio IDE or follow the instructions I am going to be highlighting here. They are basically the same thing. So if you are able to set up with that you can skip this part of the article.</p><p>On your <strong>project’s build.gradle file</strong> and under repositories add,</p><pre>maven { url &#39;<a href="https://maven.fabric.io/public&#39;">https://maven.fabric.io/public&#39;</a> }</pre><p>and in your dependencies(in the same build file) add</p><pre><a href="https://docs.fabric.io/android/changelog.html#fabric-gradle-plugin">plugin</a><br>    classpath &#39;io.fabric.tools:gradle:1.+&#39;<br>  }</pre><p>So your project’s build file will finally look like this</p><pre>buildscript {<br>  repositories {<br>    maven { url &#39;<a href="https://maven.fabric.io/public&#39;">https://maven.fabric.io/public&#39;</a> }<br>  }</pre><pre>dependencies {<br>    // These docs use an open ended version so that our plugin<br>    // can be updated quickly in response to Android tooling updates</pre><pre>// We recommend changing it to the latest version from our changelog:<br>    // <a href="https://docs.fabric.io/android/changelog.html#fabric-gradle-plugin">https://docs.fabric.io/android/changelog.html#fabric-gradle-plugin</a><br>    classpath &#39;io.fabric.tools:gradle:1.+&#39;<br>  }<br>}</pre><p>Then update your<strong> app’s gradle file or the gradle file you are using as an entry to the Android application.</strong> First, add the io.fabric plugin and also include the maven repository as shown.</p><pre>apply plugin: &#39;io.fabric&#39;  <br>repositories {   <br>    maven { url &#39;https://maven.fabric.io/public&#39; } <br>}</pre><p>also to your dependency add the crashlytics dependency like this</p><pre>implementation(&#39;com.crashlytics.sdk.android:crashlytics:2.10.1@aar&#39;) {     transitive = true;   }</pre><p>Then your final app gradle file looks like this.</p><pre>apply plugin: &#39;com.android.application&#39; // Put Fabric plugin after Android plugin</pre><pre>apply plugin: &#39;io.fabric&#39;  <br>repositories {   <br>     maven { url &#39;https://maven.fabric.io/public&#39; } <br>}</pre><pre>dependencies {   compile fileTree(dir: &#39;libs&#39;, include: [&#39;*.jar&#39;])   testCompile &#39;junit:junit:4.12&#39;   compile &#39;com.android.support:appcompat-v7:23.1.1&#39;   compile &#39;com.android.support:design:23.1.1&#39;</pre><pre>implementation(&#39;com.crashlytics.sdk.android:crashlytics:2.10.1@aar&#39;) {     transitive = true;   }</pre><p>Then in your Android Manifest, you are going to be adding the code below in your application tag.</p><pre>&lt;meta-data<br>            android:name=&quot;io.fabric.ApiKey&quot;<br>            android:value=&quot;YOUR API KEY GOES HERE&quot; /&gt;</pre><p>The “android: value” should receive your fabric API key. If you don’t have it yet visit <a href="http://www.fabric.io/">www.fabric.io</a> and navigate to your dashboard setting and create a new app you will be directed to a page where you select the fabric service you want to use which is Crashlytics. From there you will get app API key.</p><p>NB: Your Android Manifest file should include INTERNET permission as crash reports and other necessary information will be sent to your fabric dashboard in real time.</p><p>The “final piece of the puzzle” is adding crashlytics to your Activity or Application class. The good way is using your top-level application class. To your Activity or Application class, add this line in your onCreate</p><pre>Fabric.with(this, new Crashlytics());</pre><p>Then your activity or application class onCreate is like this, make sure to add it just after the super.onCreate method.</p><pre><a href="http://twitter.com/Override">@Override</a>    <br>protected void onCreate(Bundle savedInstanceState) {  <br>    super.onCreate(savedInstanceState);       <br>    Fabric.with(this, new Crashlytics());  <br>    setContentView(R.layout.activity_main);  <br>}</pre><p>After updating your build.gradle, Android Manifest file and your activity or application class, you can decide to build and proceed to adding the fastlane service to your project. I will address the fastlane implementation in the second part of this article.</p><p>To check your if crashlytics is well connected to fabrics, add a forced crash implementation in any of your activity. Include a test button to your activity layout to run a forceCrash method when clicked.</p><pre>&lt;Button<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:text=&quot;Force Crash!&quot;<br>        android:onClick=&quot;forceCrash&quot;<br>        android:layout_centerVertical=&quot;true&quot;<br>        android:layout_centerHorizontal=&quot;true&quot; /&gt;</pre><p>and this implementation of the forceCrash method in your activity.</p><pre>public void forceCrash(View view) {<br>        throw new RuntimeException(&quot;This is a crash&quot;);<br>    }</pre><p>With this method included in your activity class, build and run the application on a device or emulator to check if your crashlytics is connected to your fabric account.</p><p>After stimulating a crash from your device your fabric dashboard should be wearing a new look.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KqASn3BbrLewBVF_RsfjEA.png" /><figcaption>The FastlaneStarter project added to your fabric dashboard</figcaption></figure><p>On the right side of “the recently viewed Apps card”, you will see the new issue which is the crash report I simulated with on my MainActivity class. By Clicking and navigating through the report, you get to see the report like this which is similar to what you have in your android studio logcat.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tOwG94ZGxUhBn8KY32fAww.png" /><figcaption>The crash report showing where the reason for the crash.</figcaption></figure><p>With this crash report, you can go back to your android studio with accurate specifics of why the app crashed and fix it. You can come to your fabric dashboard and close this crash session as soon as you are done fixing the crash.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x4eTol0cgLGqRh8YHsQ08w.png" /><figcaption>Closed Crashlytic’s crash report.</figcaption></figure><p>Closing the crash report is done using the button on the top right corner after selecting the crash report you fixed.</p><p>The next part of this article is going to be featuring using fastlane to share your app and app update your beta testers and using crashlytics to observe the crashes from each beta tester.</p><p>The link to the android project <a href="https://github.com/SunnyBe/fastlane-starter">https://github.com/SunnyBe/fastlane-starter</a>, and you can use it as a starter for your projects, all you need to update is your fabric API keys and if you include the fastlane tool you will make some updates to your fastlane files too.</p><p>Thanks for coming this long with me on using app automation on your android project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94e993b41ad9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>