<?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 Rwan Hossam Eldein on Medium]]></title>
        <description><![CDATA[Stories by Rwan Hossam Eldein on Medium]]></description>
        <link>https://medium.com/@RwanHossam?source=rss-e6594c14ec85------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SgZtmnDnQNTAeFz56BMp_Q.jpeg</url>
            <title>Stories by Rwan Hossam Eldein on Medium</title>
            <link>https://medium.com/@RwanHossam?source=rss-e6594c14ec85------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 10:52:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@RwanHossam/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[Behind the Scenes: How Programs Actually Execute — Processes, Threads & Multithreading]]></title>
            <link>https://medium.com/@RwanHossam/behind-the-scenes-how-programs-actually-execute-processes-threads-multithreading-65c17df54e02?source=rss-e6594c14ec85------2</link>
            <guid isPermaLink="false">https://medium.com/p/65c17df54e02</guid>
            <dc:creator><![CDATA[Rwan Hossam Eldein]]></dc:creator>
            <pubDate>Wed, 04 Nov 2026 21:01:02 GMT</pubDate>
            <atom:updated>2026-11-04T21:01:02.278Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l5AG4PrfdR5Z0p-WpFngbA.png" /></figure><h3>Introduction</h3><p>Have you ever wondered what actually happens behind the scenes when you click an application icon on your laptop or phone?</p><p>What happens when you press <strong>Run</strong> and execute your code? How can your device open multiple browser tabs, run several applications simultaneously, and keep everything working smoothly?</p><p>And here’s another interesting question: Why can an application crash without necessarily affecting the other applications running on the same device?</p><p>We use computers and applications every day, but we rarely think about what’s happening behind the scenes to make all of this possible.</p><p>Programs can follow different execution models, such as <strong>Single-threaded</strong> and <strong>Multi-threaded execution</strong>. But what do these terms actually mean? What are Processes and Threads? How does the operating system manage running applications? And how do programming languages and their runtimes provide ways to handle multiple tasks?</p><p>In this article, we’ll take a journey behind the scenes to understand how programs are executed, how the operating system manages them, and how Processes and Threads make it possible for our devices to handle multiple tasks.</p><h3>What Happens When You Run a Program?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y8oWxdHXUWx_adtq1giNdQ.jpeg" /></figure><p>Let’s start with a simple idea: every program we use on our devices, whether it’s a desktop application, a mobile application, or even a program executed from the terminal, is essentially a set of instructions that the computer needs to execute.</p><p>But does the computer understand the code we write?</p><p>Let’s take a simple example:</p><pre>total = price + tax;</pre><p>As humans, we understand that we want to add the value of price to tax and store the result in total.</p><p>However, the CPU doesn’t understand code in the same way we do. It works with low-level instructions, which are ultimately represented using binary (0s and 1s).</p><p>So, we need a way to translate the code we write into instructions that the CPU can execute.</p><h4>From Source Code to Machine Instructions</h4><p>This is where the <strong>Compiler</strong> comes in.</p><p>A compiler takes source code written in a programming language and transforms it into another form that can be executed. The exact process depends on the programming language and its execution model.</p><p>For example, languages like C++ are typically compiled into <strong>Machine Code</strong>, which can be stored in an executable file.</p><p>Our simple statement:</p><pre>total = price + tax;</pre><p>might be translated into a set of instructions similar to the following:</p><pre>LOAD R1, price<br>LOAD R2, tax<br>ADD R3, R1, R2<br>STORE total, R3</pre><p>This is highly simplified, assembly-like pseudocode for illustration. It does not necessarily represent the actual instructions generated by a compiler.</p><p>Instead of executing the single line exactly as we wrote it, the CPU may need to execute several smaller instructions to perform the same operation.</p><p><strong>Important Note:</strong> Not all programming languages follow the same execution process.</p><ul><li><strong>C++:</strong> Typically compiled into native machine code before execution.</li><li><strong>Java:</strong> Compiled into bytecode, which is executed by the JVM using mechanisms such as interpretation and Just-In-Time (JIT) compilation.</li><li><strong>Python:</strong> In the commonly used CPython implementation, source code is compiled into bytecode, which is then executed by the Python Virtual Machine.</li></ul><p>We’ll explore these differences later. For now, the key idea is that the CPU ultimately executes machine instructions.</p><h4>Where Is the Program Stored?</h4><p>Once a program is prepared for execution, its files are stored on persistent storage devices, such as:</p><ul><li>Hard Disk Drives (HDDs) or Solid-State Drives (SSDs) on computers.</li><li>Internal Storage on mobile devices.</li></ul><p>For example, on Windows, an executable file may have the .exe extension. On Android, an APK contains the application&#39;s code, resources, and other components required for installation and execution.</p><p>However, having a program stored on the disk doesn’t mean it is actually running.</p><p>At this point, it’s simply data stored on the device, just like a recipe in a cookbook. Having the recipe doesn’t mean someone has started cooking!</p><h4>From Storage to RAM</h4><p>Why doesn’t the CPU simply execute the program directly from the disk?</p><p>Because the CPU needs to access instructions and data extremely quickly, and RAM is much faster than persistent storage devices.</p><p>That’s why, when we request to run a program, the <strong>Operating System (OS)</strong> starts preparing it for execution.</p><p>At a high level, the following happens:</p><ol><li>The OS receives a request to launch the program.</li><li>It prepares a Process and its Virtual Address Space.</li><li>It sets up the required memory mappings for the program’s files.</li><li>The required code and data pages are loaded into RAM when needed. The entire executable doesn’t necessarily have to be loaded at once.</li><li>The OS provides the memory needed during execution, including areas for the Stack and Heap.</li><li>It creates at least one Thread to begin executing the program’s instructions.</li></ol><p>And this brings us to one of the most important concepts in Operating Systems:</p><p><strong>A Program becomes a Process when it starts running.</strong></p><p>But what exactly does that mean?</p><ul><li><strong>Program:</strong> A set of instructions and data stored on a device.</li><li><strong>Process:</strong> A program in execution, with its own resources, execution state, and virtual address space.</li></ul><p>We’ll explore this concept in the next section.</p><h4>How Does the CPU Execute Instructions?</h4><p>Once the program starts executing, the CPU begins processing its instructions.</p><p>There is a well-known educational model that explains this process, called the:</p><p><strong>Fetch — Decode — Execute Cycle</strong></p><p>It consists of three main stages:</p><p>StageWhat Happens?FetchThe CPU retrieves the next instruction to be executed.DecodeThe CPU interprets the instruction and determines what operation is required.ExecuteThe CPU performs the requested operation, such as addition, comparison, or moving data.</p><p>After that, it proceeds to the next instruction, and the cycle continues throughout program execution.</p><p>Modern CPUs are much more sophisticated than this simplified model, but it’s a useful starting point for understanding how instruction execution works.</p><h4>Two Important CPU Components</h4><p>There are two important components we should understand now because we’ll need them later when discussing Threads and Context Switching.</p><p><strong>1. Registers</strong></p><p>Registers are very small and extremely fast storage locations inside the CPU. They temporarily hold values, addresses, and other data needed during instruction execution.</p><p><strong>2. Program Counter (PC)</strong></p><p>The Program Counter is a special register that holds the address of the next instruction to be executed.</p><p>You can think of it as a pointer that tells the CPU where it currently is in the instruction sequence and which instruction should come next.</p><h3>What Is a Process?</h3><p>In the previous section, we learned what happens when we run a program and how the Operating System prepares it for execution.</p><p>But once a program starts running, what exactly is it?</p><p>This brings us to one of the most important concepts in Operating Systems: <strong>The Process</strong>.</p><p>A <strong>Process</strong> is an instance of a program in execution. It represents more than just the program’s code loaded into memory. It includes:</p><ul><li>The program’s code and data.</li><li>Its own virtual address space.</li><li>Resources allocated or assigned by the Operating System.</li><li>One or more Threads responsible for executing its instructions.</li><li>Information the OS maintains to track and manage it.</li></ul><p>In simple terms:</p><ul><li><strong>Program:</strong> A static set of instructions stored on a device.</li><li><strong>Process:</strong> A running instance of that program, managed by the Operating System.</li></ul><p>Think of a program as a recipe in a cookbook. The recipe itself doesn’t do anything. But when someone starts following it, an actual cooking process begins.</p><p>And here’s something interesting: <strong>The same program can have multiple running processes at the same time.</strong></p><p>For example, you might launch the same command in two different terminal windows, creating two separate processes. Some applications can also run multiple processes as part of their architecture.</p><h4>Why Do We Need Processes?</h4><p>Imagine that your Operating System has dozens of programs running simultaneously.</p><p>It needs to keep track of several things:</p><ul><li>Which program is running, and where is its memory?</li><li>Which files and resources is each program allowed to access?</li><li>Which resources belong to each process?</li><li>What should happen when a process terminates?</li><li>How can the OS prevent one process from interfering with another?</li></ul><p>Without a clear way to organize and manage running programs, the OS would have difficulty keeping track of their execution and resources.</p><p>That’s why the Operating System uses the <strong>Process</strong> abstraction.</p><p>A process acts like an organized container that groups the resources, memory, and execution context associated with a running program.</p><p>This allows the OS to manage processes independently, control their access to resources, and clean up their resources when they terminate.</p><h4>How Does the OS Create a Process?</h4><p>When you launch a program, the Operating System performs several operations to prepare it for execution.</p><p>At a high level, the process looks like this:</p><ol><li><strong>Creates the Process:</strong> The OS creates a new process and establishes its virtual address space.</li><li><strong>Loads the Program:</strong> It maps the executable’s required code and data into the process’s address space. Pages are brought into physical memory when needed.</li><li><strong>Allocates Memory:</strong> It prepares the memory areas needed by the process, including the Stack and Heap.</li><li><strong>Assigns a PID:</strong> Each process receives a Process ID (PID), which identifies it while it exists in the system.</li><li><strong>Sets Up Resources:</strong> The OS establishes the resources and access permissions the process needs, such as open files and network sockets.</li><li><strong>Creates the Initial Thread:</strong> A process needs at least one Thread to execute its instructions. The OS initializes its execution context, including the initial Program Counter and CPU registers.</li></ol><p>The OS also maintains information about the process in a data structure commonly known as the <strong>Process Control Block (PCB)</strong>.</p><p>The PCB helps the OS track and manage the process throughout its lifetime.</p><p>Notice that the Program Counter belongs to the Thread’s execution context, not to the process as a whole. We’ll understand why when we explore Threads.</p><h4>Process States</h4><p>A process doesn’t remain in the same state throughout its lifetime. It moves between different states depending on what it’s doing and what resources it needs.</p><p>A simplified process-state model includes five main states:</p><p>StateDescription<strong>New</strong>The process is being created.<strong>Ready</strong>The process is ready to execute but is waiting for CPU time.<strong>Running</strong>Its execution is currently using the CPU.<strong>Waiting (Blocked)</strong>Its execution is waiting for an event, such as I/O completion.<strong>Terminated</strong>The process has finished or has been stopped.</p><p>The transitions can be illustrated as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q4AUdv2WeJTxBuqljk6raw.png" /><figcaption>Process Lifecycle State Diagram</figcaption></figure><p>Let’s understand what happens in a real situation.</p><p>Imagine a program requests data from a file or waits for a response from a network operation.</p><p>If its executing Thread performs a blocking operation, it may have to wait until that operation completes.</p><p>During that time, the scheduler can give CPU time to another Ready Thread instead of leaving the CPU idle.</p><p>Once the required event occurs, the waiting Thread can become Ready again and wait for its next opportunity to execute.</p><p><strong>Important:</strong> This is a simplified model for learning. Modern Operating Systems schedule Threads rather than treating an entire multi-threaded Process as one indivisible execution unit. Also, asynchronous I/O can allow a Thread to continue doing other work without blocking while waiting for the result.</p><p>We’ll return to this idea when we discuss Blocking, Non-blocking, and the Main Thread.</p><h4>Process Isolation: Why Does It Matter?</h4><p>One of the most important benefits of processes is <strong>Memory Isolation</strong>.</p><p>Each process has its own virtual address space. This means that one process cannot normally access another process’s memory directly.</p><p>The Operating System and hardware enforce these memory-protection boundaries.</p><h4>Why is this important?</h4><p>Imagine the following situations:</p><ul><li><strong>Application crashes:</strong> If one application crashes, the other applications can usually continue running independently.</li><li><strong>Memory protection:</strong> One application cannot normally read or modify another application’s private memory.</li><li><strong>Resource management:</strong> If the system runs low on memory, the OS may terminate a background process to free resources without necessarily affecting other processes.</li></ul><p>For example:</p><ul><li>On Android, applications typically run in separate processes with distinct Linux user IDs, although an application can also use multiple processes.</li><li>On iOS, applications run within the iOS security sandbox, which restricts their access to other applications’ data and system resources.</li></ul><p>This isolation improves system stability and security, but it doesn’t mean applications can never communicate or affect each other.</p><p>For example, applications can exchange information through mechanisms provided by the OS, such as <strong>Inter-Process Communication (IPC)</strong>.</p><p>And this introduces an important trade-off:</p><p>If processes have separate memory spaces, how can they communicate with each other?</p><p>They need specific communication mechanisms, rather than directly accessing each other’s private memory.</p><p>We’ll explore IPC later.</p><blockquote>Key Takeaway</blockquote><blockquote>A Process is more than a program loaded into RAM. It’s an Operating System abstraction that represents a running instance of a program, including its memory, resources, Threads, and execution-related information.</blockquote><blockquote>Processes allow the OS to manage running programs, control their resources, and isolate them from one another.</blockquote><h3>Understanding Process Memory</h3><p>Every Process has its own <strong>Virtual Address Space</strong>, which gives it the impression that it has a large, continuous memory space of its own.</p><p>This address space is commonly illustrated using four main memory regions:</p><ul><li>Code (Text Segment)</li><li>Data Segment</li><li>Heap</li><li>Stack</li></ul><p>Each region has a different responsibility.</p><p>This is what we previously referred to as <strong>Memory Isolation</strong>. Now, let’s look inside a Process and understand how its memory is organized.</p><p>The Operating System provides each Process with its own virtual address space. This is part of a mechanism called <strong>Virtual Memory</strong>, which we’ll explore in more detail later.</p><h3>Process Memory Layout</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nMert_2GnHdaVeHgLK3nzA.png" /></figure><p>As you can see in the diagram, the Stack and Heap are commonly illustrated as growing toward each other, with unused virtual address space between them.</p><h4>Why?</h4><p>Because their sizes can change during program execution:</p><ul><li>The Stack grows and shrinks as functions are called and return.</li><li>The Heap grows and shrinks as dynamic memory is allocated and released.</li></ul><p>Unlike these two regions, the Code and Data regions generally have sizes determined by the program and its loading requirements.</p><p><em>Note: This is a simplified traditional memory layout. Actual layouts vary between operating systems and architectures.</em></p><h3>1. Code Segment (Text Segment)</h3><p>This region contains the program’s executable instructions.</p><p>In other words, it contains the machine instructions that the CPU needs to execute.</p><p><strong>Important characteristics:</strong></p><ul><li>The CPU fetches instructions from executable memory, and the Program Counter holds the address of the next instruction to execute.</li><li>It is typically marked as <strong>Read-Only</strong>, meaning the program cannot normally modify its instructions while running.</li><li>It can also be marked as executable, allowing the CPU to execute instructions stored there.</li><li>If multiple Processes run the same program, the OS may allow them to share the same physical memory pages containing the executable code, since the code is generally not modified.</li></ul><p>This sharing helps reduce memory usage.</p><h3>2. Data Segment</h3><p>The Data Segment stores global and static variables that have static storage duration.</p><p>For example:</p><pre>int counter = 0; // Global variable</pre><p>The variable counter exists throughout the lifetime of the program.</p><p>The Data Segment is commonly divided into two parts:</p><ul><li><strong>Initialized Data:</strong> Stores global and static variables that have an explicit initial value.</li><li><strong>BSS (Block Started by Symbol):</strong> Stores global and static variables that are zero-initialized or have no explicit initializer.</li></ul><p>Unlike dynamically allocated memory, these variables don’t get created and destroyed every time a function is called.</p><p>Their lifetime is generally tied to the lifetime of the program.</p><h3>3. Stack</h3><p>The Stack is one of the most important memory regions, and we’ll keep coming back to it when discussing Threads.</p><p>So, how does it work?</p><p>Every time a function is called, a new <strong>Stack Frame</strong> is typically created to hold information needed for that function’s execution.</p><p>A Stack Frame may contain:</p><ul><li>Local variables.</li><li>Function parameters.</li><li>Return address: information about where execution should continue after the function finishes.</li><li>Other temporary execution-related information.</li></ul><p>When the function returns, its Stack Frame is removed.</p><p>This follows the <strong>LIFO (Last In, First Out)</strong> principle: the last function call is the first one to return.</p><p>Let’s take a simple example:</p><pre>void a() {<br>    b();<br>}<br>void b() {<br>    c();<br>}<br>void c() {<br>    // Do something<br>}</pre><p>When c() is executing, the conceptual Stack may look like this:</p><pre>┌──────────────┐<br>│     c()      │  ← Most recent call<br>├──────────────┤<br>│     b()      │<br>├──────────────┤<br>│     a()      │<br>├──────────────┤<br>│    main()    │<br>└──────────────┘</pre><p>When c() finishes, its Stack Frame is removed, and execution returns to b() using the return information.</p><p>This is part of how the program keeps track of its function calls and knows where to continue execution.</p><p><strong>Important characteristics:</strong></p><ul><li>Stack allocation and deallocation are generally very fast because they often involve adjusting a Stack Pointer.</li><li>Stack memory is managed automatically according to the function calling convention and the compiler/runtime.</li><li>Each Thread has its own Stack because each Thread has its own independent execution flow.</li><li>Stack size is limited. If the program uses more Stack memory than is available, it may encounter a <strong>Stack Overflow</strong>.</li></ul><p>For example, infinite recursion can repeatedly create new Stack Frames until the available Stack space is exhausted.</p><h3>4. Heap</h3><p>The Heap is an area of memory used for <strong>dynamic memory allocation</strong>.</p><p>Unlike the Stack, where memory is typically associated with function calls, the Heap allows programs to allocate memory dynamically during execution.</p><p>For example:</p><ul><li>Creating objects dynamically.</li><li>Allocating memory for a list that can grow as elements are added.</li><li>Storing data whose size is determined at runtime.</li></ul><p>In languages like C++, you can explicitly allocate memory using new or other allocation mechanisms.</p><p>In Dart, objects are dynamically allocated and managed by the runtime.</p><p><strong>Important characteristics:</strong></p><ul><li>It is generally used for data that needs a lifetime independent of a single function call.</li><li>Its size can change during program execution.</li><li>Allocation and deallocation are more complex than typical Stack operations, although modern memory allocators can make them very efficient.</li><li>Memory reclamation depends on the programming language and its memory-management model.</li></ul><p>For example:</p><ul><li><strong>C/C++:</strong> Memory can be managed manually or through mechanisms such as RAII and smart pointers in C++.</li><li><strong>Java and Dart:</strong> Use Garbage Collection (GC) to reclaim objects that are no longer reachable.</li><li><strong>Swift:</strong> Uses Automatic Reference Counting (ARC) to manage object lifetimes.</li></ul><p>If memory remains allocated or objects remain unnecessarily reachable when they are no longer needed, the application can suffer from a <strong>Memory Leak</strong>.</p><h4>What Happens When We Have Multiple Threads?</h4><p>Now we are getting closer to the next major topic: Threads.</p><p>As we learned, a Process has several memory regions, but not all of them are treated the same way when multiple Threads exist.</p><p>Threads belonging to the same Process generally share:</p><ul><li>Code Segment.</li><li>Data Segment.</li><li>Heap.</li></ul><p>However, <strong>each Thread has its own Stack</strong>.</p><h4>Why?</h4><p>Because every Thread has its own execution flow.</p><p>Imagine two Threads executing different functions at the same time. Each one needs to keep track of its own function calls, local variables, and return information.</p><p>That’s why each Thread needs its own Stack.</p><p>This shared memory model has an important advantage: Threads can easily access shared data without needing separate communication mechanisms like independent Processes do.</p><p>But it also introduces challenges.</p><p>For example, what happens if two Threads try to modify the same variable at the same time?</p><p>This can lead to a problem called a <strong>Race Condition</strong>.</p><p>We’ll explore that when we discuss Concurrency and Synchronization.</p><h3>What Is a Thread?</h3><p>We’ve learned that a Process is a running instance of a program, with its own memory space and resources.</p><p>But here’s an important question: Does a Process execute all its instructions through one execution path?</p><p>Not necessarily!</p><p>A <strong>Thread</strong> is a path of execution within a Process.</p><p>Think of it this way:</p><ul><li>A <strong>Process</strong> is like a house that contains everything needed to get work done.</li><li>A <strong>Thread</strong> is like a worker inside that house who actually performs the tasks.</li></ul><p>The Process provides the environment and resources, while Threads are responsible for executing instructions.</p><p>Every Process has at least one Thread, commonly called the <strong>Main Thread</strong>. Additional Threads can be created to allow multiple execution paths within the same Process.</p><p>So far, we’ve been imagining a Process with only one execution path, where instructions are executed one after another.</p><p>Now, imagine an application that needs to perform two tasks:</p><ol><li>Download a large file from the internet.</li><li>Continue responding to user interactions.</li></ol><p>If the application performs the download using a blocking operation on its only Thread, that Thread will have to wait until the operation completes.</p><p>During that time, it cannot process other tasks.</p><p>As a result, the application may become unresponsive.</p><p>One possible solution is to create another Process to handle the download. However, Processes have separate memory spaces and resources, so communication between them requires additional mechanisms such as IPC.</p><p>Creating and managing another Process also generally involves more overhead than creating another Thread within an existing Process.</p><p>So, what if we could create another execution path inside the same Process?</p><p>That’s exactly where <strong>Multithreading</strong> comes in.</p><p>Instead of creating an entirely new Process, we can create additional Threads within the same Process.</p><p>Each Thread can execute its own sequence of instructions while sharing the Process’s memory and resources.</p><p>This allows one Thread to handle a time-consuming task while another continues processing user interactions.</p><blockquote><em>Note: Multiple Threads are one solution to this problem. Asynchronous, non-blocking I/O is another approach that allows a Thread to continue doing other work while waiting for an operation to complete.</em></blockquote><h4>What Is Shared and What Is Private?</h4><p>Remember the memory regions we discussed earlier?</p><ul><li>Code</li><li>Data</li><li>Heap</li><li>Stack</li></ul><p>Now let’s understand how these regions behave when a Process contains multiple Threads.</p><p>ComponentShared Between Threads?Code SegmentSharedData Segment (Global / Static)SharedHeapSharedOpen files and process resourcesGenerally sharedStackPrivate to each ThreadCPU RegistersPrivate to each ThreadProgram CounterPrivate to each Thread</p><p>But why are the Stack, Program Counter, and Registers private?</p><p>Because every Thread has its own execution flow.</p><p>For example, one Thread might be executing function calculate(), while another is executing downloadFile().</p><p>Each Thread needs to remember:</p><ul><li>Where it currently is in the execution sequence.</li><li>Which function calls it has made.</li><li>Where execution should continue after a function returns.</li><li>The values it is currently working with.</li></ul><p>That’s why each Thread needs its own Stack, Program Counter, and CPU Registers.</p><p>If these were shared, Threads would interfere with each other’s execution state.</p><p>We can visualize the structure like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6bKtlCBOSjLRYZ3SaUBAlQ.jpeg" /></figure><p>This is why we needed to understand Process Memory before moving to Threads</p><h4>What Does the OS Know About Each Thread?</h4><p>Just as the Operating System maintains information about each Process through a structure called the <strong>Process Control Block (PCB)</strong>, it also maintains information about individual Threads.</p><p>This information is often described using a structure called the <strong>Thread Control Block (TCB)</strong>.</p><p>A TCB contains information the OS needs to manage and schedule a Thread, such as:</p><ul><li><strong>Thread ID:</strong> An identifier for the Thread.</li><li><strong>Thread State:</strong> Its current state, such as Ready, Running, or Waiting.</li><li><strong>Program Counter:</strong> The address of the next instruction to execute.</li><li><strong>CPU Registers:</strong> The Thread’s current register values.</li><li><strong>Stack Information:</strong> Information about the Thread’s Stack.</li></ul><p>The exact structure and name of these internal data structures can vary between operating systems.</p><p>[Insert Thread Control Block (TCB) Diagram Here]</p><h4>How Does the OS Schedule Threads?</h4><p>Now we reach another important concept.</p><p>In modern general-purpose Operating Systems, such as Windows, Linux, Android, and iOS, the scheduler generally schedules <strong>Threads</strong>, rather than treating an entire Process as one indivisible unit of execution.</p><p>This means that the Thread is the execution unit that gets scheduled to run on a CPU core.</p><p>For example, imagine a Process containing three Threads:</p><ul><li>Thread 1 handles user interactions.</li><li>Thread 2 processes some data.</li><li>Thread 3 performs another background task.</li></ul><p>The OS scheduler decides which Threads get CPU time and when.</p><p>Depending on the number of available CPU cores and the scheduling decisions, multiple Threads may execute in parallel or take turns using the CPU.</p><p>The Process itself acts as the container that groups these Threads and their shared resources.</p><h4>Context Switching Between Threads</h4><p>Remember that the CPU can execute only a limited number of Threads simultaneously, depending on its available execution resources.</p><p>When the OS switches the CPU from one Thread to another, this is called a <strong>Context Switch</strong>.</p><p>During a Thread Context Switch, the OS needs to save the execution state of the current Thread and restore the state of the next Thread.</p><p>This includes information such as:</p><ul><li>CPU Registers.</li><li>Program Counter.</li><li>Stack-related execution state.</li></ul><p>An interesting point is that switching between two Threads belonging to the same Process can be cheaper than switching between Threads belonging to different Processes.</p><h4>Why?</h4><p>Because Threads within the same Process share the same virtual address space.</p><p>Therefore, a switch between Threads in the same Process usually doesn’t require switching to a completely different address space.</p><p>However, this doesn’t mean Thread Context Switching is free. It still involves saving and restoring execution state and scheduling overhead.</p><h4>Advantages and Trade-offs of Multithreading</h4><p>Like any other technique, Multithreading has advantages and disadvantages.</p><p><strong>Advantages:</strong></p><ol><li><strong>Lower Overhead:</strong> Creating and managing Threads generally requires fewer resources than creating separate Processes.</li><li><strong>Easier Communication:</strong> Threads can access shared memory directly, without requiring IPC mechanisms.</li><li><strong>Better Responsiveness:</strong> One Thread can perform a time-consuming task while another continues handling other work.</li><li><strong>Concurrency and Parallelism:</strong> Multiple Threads can make progress concurrently and, when multiple CPU cores are available, execute in parallel.</li></ol><p><strong>Trade-offs:</strong></p><ol><li><strong>No Memory Isolation Between Threads:</strong> Threads share the same Process memory space. An invalid memory operation by one Thread can affect the entire Process.</li><li><strong>Shared Memory Risks:</strong> If multiple Threads access and modify the same data without proper synchronization, they can produce unexpected results.</li><li><strong>Synchronization Complexity:</strong> Shared resources require coordination mechanisms such as Locks and Mutexes.</li><li><strong>Debugging Complexity:</strong> Some problems depend on timing and execution order, making them difficult to reproduce.</li></ol><p>One example of these problems is a <strong>Race Condition</strong>, which we’ll explore in a later section.</p><blockquote>Key Takeaway</blockquote><blockquote>A Process provides the memory space and resources needed by a running program, while Threads provide independent execution paths within that Process.</blockquote><blockquote>Threads make it possible to perform multiple tasks within the same Process, improving responsiveness and enabling concurrency and parallelism.</blockquote><blockquote>However, sharing memory also introduces risks, which means Threads need proper synchronization and coordination.</blockquote><h3>Single-threaded vs Multi-threaded Execution</h3><p>Imagine we have a restaurant with a chef responsible for preparing orders.</p><p>We have three orders:</p><ul><li>Pizza</li><li>Burger</li><li>Pasta</li></ul><p><strong>Scenario 1: Single-threaded</strong></p><p>We have only one chef responsible for handling all three orders.</p><p>The chef starts preparing the pizza, then moves on to the burger, and finally prepares the pasta.</p><p>But does having only one chef mean they must wait for each order to be completely finished before starting the next one?</p><p>Not necessarily!</p><p>For example:</p><ul><li>Put the pizza in the oven.</li><li>Use the cooking time to prepare the burger.</li><li>Start preparing the pasta.</li><li>Go back to check on the pizza when needed.</li></ul><p>In other words, a single chef can manage multiple tasks and make use of waiting time instead of wasting it.</p><p><strong>Scenario 2: Multi-threaded</strong></p><p>Now, imagine the restaurant has three chefs instead of one.</p><ul><li>Chef 1 is responsible for the pizza.</li><li>Chef 2 is responsible for the burger.</li><li>Chef 3 is responsible for the pasta.</li></ul><p>Each chef can work on a separate task independently, and all three can work at the same time.</p><p><strong>The Main Difference</strong></p><p>The difference is not the number of tasks, but the number of execution paths responsible for handling them.</p><ul><li><strong>Single-threaded:</strong> One execution path manages the tasks.</li><li><strong>Multi-threaded:</strong> Multiple execution paths can handle different tasks independently.</li></ul><h4>1. Single-threaded Execution</h4><p>In a single-threaded program, there is only one execution path responsible for executing instructions.</p><p>In a simple sequential execution model, tasks are handled one after another. If a task blocks the thread while waiting for something, the thread cannot move on to execute other tasks until that blocking operation finishes.</p><p><strong>Example: </strong>Imagine an application that needs to perform three tasks:</p><ol><li>Download an image from the internet.</li><li>Read a local file.</li><li>Respond to a user’s button click.</li></ol><p>If all three tasks are executed sequentially using blocking operations:</p><p><strong>The user clicked earlier, but the thread is still busy.</strong></p><p><strong>Advantages:</strong></p><ul><li>Simpler to implement and understand.</li><li>Easier to debug and test.</li><li>No race conditions between multiple threads accessing shared data.</li></ul><p><strong>Disadvantages:</strong></p><ul><li>A blocking operation can prevent other tasks from running.</li><li>A slow operation can delay user interactions.</li><li>CPU-intensive work can make the application unresponsive if it runs on the UI thread.</li></ul><h4>2. Multi-threaded Execution</h4><p>In a multi-threaded program, multiple threads can execute different tasks within the same process.</p><p>Using our previous example:</p><ul><li>Thread 1: Download Image ..............</li><li>Thread 2: Read File</li><li>Thread 3: Handle User Click ← Responds immediately</li></ul><p>Instead of relying on one execution path, different threads can handle different tasks independently.</p><p><strong>Advantages:</strong></p><ul><li><strong>Responsiveness:</strong> The user interface can remain responsive while other threads handle background work.</li><li><strong>Better Resource Utilization:</strong> When one thread is waiting for I/O, other threads can use the available CPU time.</li><li><strong>Potential Performance Improvement:</strong> On multi-core processors, independent CPU-intensive tasks can execute in parallel.</li></ul><p><strong>Disadvantages:</strong></p><ul><li>More complex code that is harder to debug and test.</li><li><strong>Race Conditions:</strong> Multiple threads accessing shared data can produce unexpected results.</li><li><strong>Deadlocks:</strong> Threads can get stuck waiting for resources held by each other.</li><li><strong>Thread Overhead:</strong> Each thread requires resources, such as its own stack, scheduling, and context-switching overhead. Creating too many threads can reduce performance instead of improving it.</li></ul><h4>What Determines Whether We Should Use Single-threading or Multi-threading?</h4><p>Choosing between single-threaded and multi-threaded execution is not simply about using more threads to get better performance. The right choice depends on several factors:</p><p><strong>1. The Type of Work</strong></p><p>The first thing to consider is whether the task is I/O-bound or CPU-bound.</p><ul><li><strong>I/O-bound tasks</strong> spend most of their time waiting for external operations, such as network requests or file access. Using multiple threads can help handle other tasks while one thread is waiting.</li><li><strong>CPU-bound tasks</strong> spend most of their time performing calculations. Splitting this work across multiple cores may improve performance, if the tasks can run independently.</li></ul><p><strong>2. The Number of CPU Cores</strong></p><p>The number of available cores affects how much work can run in parallel.</p><ul><li>With a single core, multiple threads can take turns using the CPU, but they cannot provide true CPU parallelism on that core.</li><li>With multiple cores, independent tasks may execute in parallel, potentially reducing execution time.</li></ul><p><strong>3. The Need for Responsiveness</strong></p><p>If an application has a user interface, it should remain responsive while other work is being performed.</p><p>For example, a long-running task should not block the UI thread. Moving that work to another thread can allow the application to continue responding to user interactions.</p><p><strong>4. How Much the Work Can Be Divided</strong></p><p>Multi-threading is most useful when a task can be divided into smaller, independent parts.</p><p>If one part depends on the result of another, those parts cannot run independently and may need to execute in sequence.</p><p>The portion of work that must remain sequential limits the maximum possible speedup. This idea is described by <strong>Amdahl’s Law</strong>.</p><p><strong>5. Shared Data Between Threads</strong></p><p>When multiple threads need to access and modify the same data, synchronization may be required to prevent unexpected results.</p><p>As shared mutable data increases, coordination between threads becomes more complex and can introduce performance overhead.</p><p><strong>6. The Size of the Workload</strong></p><p>Creating and managing threads has a cost. Threads require resources and may introduce scheduling and context-switching overhead.</p><p>For very small tasks, this overhead may be greater than the performance benefit of using multiple threads.</p><p><strong>7. Code Complexity and Reliability</strong></p><p>Multi-threaded code is generally more complex to implement, debug, and test because of issues such as race conditions and deadlocks.</p><p>If the task does not benefit significantly from parallel execution, a simpler single-threaded solution may be easier to maintain and reason about.</p><p><strong>Ultimately, the goal is not to use as many threads as possible. It is to choose an execution model that fits the workload while maintaining good performance, responsiveness, and reliability.</strong></p><h3>Thread Scheduling &amp; Context Switching</h3><h3>What Is a CPU Core?</h3><p>A <strong>CPU Core</strong> is an independent processing unit inside the CPU chip. It has its own:</p><ul><li><strong>Registers</strong></li><li><strong>Program Counter</strong></li><li><strong>Execution Units:</strong> Hardware components responsible for performing operations.</li></ul><p>Each core can perform the <strong>Fetch → Decode → Execute</strong> cycle independently.</p><p><strong>A single CPU core can execute one thread at a time</strong> (assuming no simultaneous multithreading, such as Intel Hyper-Threading).</p><h3>The Scheduler</h3><p>At any given moment, hundreds of threads may be ready to run. But the CPU has a limited number of cores.</p><p>So, who decides which thread gets to use a core and when?</p><p>That’s the <strong>Scheduler</strong>.</p><p>The Scheduler is part of the Operating System (OS). Its job is to select the next thread from the <strong>Ready Queue</strong> and assign it to an available CPU core.</p><p>The scheduling process relies on several important concepts:</p><ul><li><strong>Time Slice (Quantum):</strong> Each thread gets a small amount of CPU time, usually measured in milliseconds. If it doesn’t finish within that period, the OS can interrupt it and give another thread a turn. This is called <strong>Preemptive Scheduling</strong>.</li><li><strong>Priority:</strong> Threads with higher priority may get preference over lower-priority threads. For example, UI-related work often needs responsive scheduling to keep the application smooth.</li><li><strong>Waiting State:</strong> If a thread is waiting for an I/O operation, such as a network response, it moves to the Waiting state and releases the CPU. The scheduler can then assign the core to another ready thread without waiting for the original time slice to expire.</li></ul><p>This explains why everything appears to run at the same time.</p><p>The OS switches between threads <strong>many times per second</strong>, making concurrent execution appear simultaneous, even on a single core.</p><p>And this brings us to an important distinction we’ll explore next: <strong>Concurrency vs. Parallelism</strong>.</p><h3>Context Switching</h3><p>A <strong>Context Switch</strong> happens when the OS stops executing one thread and switches the CPU core to another thread.</p><h4>For example, when switching from Thread A to Thread B:</h4><ol><li>Pause Thread A.<br>2. Save its execution state:<br> - Program Counter (PC)<br> - CPU Registers<br> - Stack Pointer<br> This information is saved in its Thread Control Block (TCB).<br>3. Load Thread B&#39;s saved execution state from its TCB.<br>4. Resume Thread B from where it previously stopped.</li></ol><p>This brings us back to the <strong>Program Counter and Registers</strong> we discussed earlier.</p><p>Saving and restoring these values allows a thread to resume execution from exactly where it stopped, as if nothing had interrupted it.</p><h3>The Cost of Context Switching</h3><p>Context switching isn’t free. It introduces two types of overhead:</p><ol><li><strong>Direct Cost</strong></li></ol><p>The CPU spends time saving the current thread’s state and restoring the next thread’s state instead of executing application instructions.</p><p><strong>2. Indirect Cost</strong></p><p>Each CPU core has caches that store frequently accessed data.</p><p>When Thread A is replaced by Thread B, some of the cached data may no longer be useful to Thread B. This can lead to cache misses and additional memory access delays until the cache becomes useful again.</p><h3>Concurrency vs. Parallelism</h3><p>Concurrency and Parallelism are two concepts that are often confused because both involve working with multiple tasks. However, they describe two different ways of handling work.</p><h3>What Is Concurrency?</h3><p><strong>Concurrency</strong> means dealing with multiple tasks during the same period of time by making progress on them without necessarily executing them simultaneously.</p><p>The system switches between tasks, allowing each one to make progress while others are waiting or paused.</p><p><strong>Example: One Chef, Multiple Tasks</strong></p><p>Imagine one chef preparing a meal:</p><ul><li>Puts the soup on the stove.</li><li>While the soup is boiling, starts chopping vegetables.</li><li>Goes back to stir the soup.</li><li>Checks what’s cooking in the oven.</li><li>Returns to preparing the salad.</li></ul><p>The chef is handling multiple tasks within the same period, switching between them as needed.</p><p>However, the chef is still one person and cannot physically perform two actions with their hands at exactly the same moment.</p><p>That’s <strong>Concurrency</strong>.</p><h3>What Is Parallelism?</h3><p><strong>Parallelism</strong> means executing multiple tasks at exactly the same time.</p><p>This requires multiple processing units, such as different CPU cores, to execute tasks simultaneously.</p><p><strong>Example: Three Chefs, Multiple Tasks</strong></p><p>Imagine three chefs preparing the same meal:</p><ul><li>Chef 1 prepares the soup.</li><li>Chef 2 chops the vegetables.</li><li>Chef 3 prepares the salad.</li></ul><p>All three chefs are working at the same time, each handling a different task.</p><p>That’s <strong>Parallelism</strong>.</p><h3>How Are They Related to Threads and CPU Cores?</h3><p>Here’s an important distinction:</p><ul><li>You can write a <strong>concurrent program</strong> using multiple threads, but it doesn’t necessarily execute in parallel. If the device has only one CPU core, the OS can switch between those threads, allowing them to make progress without running simultaneously.</li><li>A device may have multiple CPU cores, but if your program uses only a single thread, it won’t automatically benefit from all those cores.</li></ul><p><strong>True parallel execution requires both:</strong></p><ol><li>Hardware with multiple processing units (such as CPU cores).</li><li>A program structured in a way that allows multiple tasks to execute independently.</li></ol><h3>The Key Takeaway</h3><p>Concurrency and Parallelism solve related but different problems:</p><ul><li><strong>Concurrency</strong> is about managing multiple tasks at the same time.</li><li><strong>Parallelism</strong> is about executing multiple tasks at the same time.</li></ul><p>As Rob Pike famously put it:</p><blockquote><em>“Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of things at once.”</em></blockquote><h3>The Main Thread and Why You Shouldn’t Block It</h3><p>The whole idea can be summarized in one sentence:</p><p><strong>An application has one main worker responsible for handling the UI. If that worker gets stuck doing a time-consuming task, the interface stops responding.</strong></p><p>Let’s understand why.</p><h3>The Coffee Shop Analogy</h3><p>Imagine a coffee shop with only one cashier. This cashier represents the <strong>Main Thread</strong>.</p><p>Their responsibilities include:</p><ul><li>Taking orders from customers.</li><li>Serving completed orders.</li><li>Responding to customers’ questions.</li></ul><p>Customers stand in a queue, and the cashier serves them one by one.</p><p>A customer walks in and orders a coffee. The cashier prepares it quickly and serves it. Everything works smoothly.</p><p>Now, imagine another customer places a huge order:</p><p>“I need 50 cups of coffee, and you’ll have to go outside to the storage room to get the ingredients.”</p><p>What happens if the cashier goes to the storage room personally?</p><p>The cashier is no longer available to serve customers. The entire queue has to wait. No one can place a new order or get served until the cashier returns.</p><p>This is exactly what <strong>blocking</strong> means: a time-consuming operation keeps the only worker responsible for handling the UI occupied, preventing other events from being processed.</p><p><strong>So, what’s the solution?</strong></p><p>Instead of sending the cashier to the storage room, the coffee shop hires another worker.</p><p>This worker represents a <strong>Background Thread</strong>.</p><p>The background worker goes to get the ingredients while the cashier stays at the counter and continues serving customers. Once the ingredients are ready, the worker delivers them to the cashier, who can continue with the order.</p><p>This is the basic idea behind moving time-consuming work away from the Main Thread.</p><p>However, an important detail: <strong>not every slow operation requires a background thread.</strong> For example, when waiting for a network response, asynchronous non-blocking I/O can allow the Main Thread to continue handling other events without waiting for the response.</p><h3>Why Does One Thread Handle the UI?</h3><p>A user interface contains many interconnected elements: buttons, text, animations, layouts, and more.</p><p>Imagine multiple threads trying to modify these elements at the same time. Their operations could conflict, leading to race conditions and unpredictable UI states.</p><p>To simplify UI management, most GUI frameworks follow a model where <strong>one designated thread owns UI operations</strong>.</p><p>This thread is commonly called the <strong>UI Thread</strong>.</p><p>Other threads can perform background work, but when they need to update the interface, they send the result or a request back to the UI Thread, which performs the actual UI update.</p><p>One important distinction:</p><p>The <strong>Main Thread</strong> is the initial thread created when a program starts executing. It is not necessarily the UI Thread in every type of application.</p><p>However, in many GUI applications, the framework assigns UI responsibilities to the Main Thread. That’s why the terms Main Thread and UI Thread are often used interchangeably in this context.</p><h3>The Queue = Event Loop</h3><p>Remember the queue of customers in our coffee shop?</p><p>The cashier handles customers one by one. The same general idea applies to the <strong>Event Loop</strong>.</p><p>The Event Loop continuously checks for pending events, such as:</p><ul><li>Button clicks.</li><li>User interactions.</li><li>UI updates.</li><li>Scheduled callbacks.</li></ul><p>It picks up an event, executes its callback, and then moves on to the next one.</p><p>A callback that takes too long delays the events behind it. That’s why a long-running operation on the Main Thread can make an application feel unresponsive.</p><h3>What About the 16ms Frame Budget?</h3><p>A screen needs to display new frames continuously to make animations and transitions look smooth.</p><p>For example:</p><ul><li>Refresh Rate= 60 Hz: ~16.67 ms per frame.</li><li>Refresh Rate= 90 Hz: ~11.11 ms per frame.</li><li>Refresh Rate= 120 Hz: ~8.33 ms per frame.</li></ul><p>At 60 Hz, the display refreshes approximately 60 times per second. This means a new frame needs to be ready roughly every 16.67 milliseconds.</p><p>If the application misses a frame deadline, the animation may appear to stutter. This is commonly called <strong>jank</strong>.</p><p>If the Main Thread remains blocked for a longer period, the interface may stop responding entirely.</p><p>Keep in mind that this is the overall frame budget, not time reserved exclusively for the Main Thread. The application also has other work to complete before a frame can be displayed.</p><h3>Why Don’t Empty CPU Cores Save Us?</h3><p>You might wonder:</p><p>“If my computer has multiple CPU cores, why can’t another available core take over when the Main Thread gets blocked?”</p><p>The answer is that CPU cores don’t automatically divide the work of a single thread between themselves.</p><p>A thread can execute on one CPU core at a time. The operating system may move it from one core to another, but the same thread cannot execute its instructions simultaneously on multiple cores.</p><p>So, if the Main Thread is busy executing a long CPU-intensive operation, another core cannot simply take over that same thread’s execution.</p><p>If the Main Thread is waiting for an I/O operation, such as a network response, another core cannot make that response arrive sooner either.</p><p>The solution is to structure the work differently: keep the Main Thread available for UI responsibilities, and use asynchronous operations or background execution when appropriate.</p><p><strong>The main takeaway:</strong> The goal isn’t to make the Main Thread do everything faster. It’s to make sure it doesn’t spend time waiting for work that can happen elsewhere.</p><h3>Thread Synchronization: When Shared Data Becomes a Problem</h3><p>Threads within the same process share the same memory space. This makes communication and data exchange easier, but it also introduces a new problem:</p><p><strong>What happens when two threads try to modify the same data at the same time?</strong></p><p>Let’s understand why this happens and how synchronization solves it.</p><h3>What Do Threads Actually Share?</h3><p>Threads belonging to the same process generally share:</p><ul><li><strong>Heap:</strong> Dynamically allocated objects and data.</li><li><strong>Global and Static Variables:</strong> Variables accessible across different parts of the program.</li><li><strong>Code:</strong> The program’s executable instructions.</li></ul><p>However, each thread has its own:</p><ul><li><strong>Stack:</strong> Used for function calls, parameters, and local variables.</li><li><strong>Registers:</strong> Store the thread’s current execution context.</li><li><strong>Program Counter:</strong> Tracks the next instruction to execute.</li></ul><p>This means every thread can access shared global variables and heap objects.</p><p>Local variables are stored in each thread’s private stack, so their individual storage locations are not shared. However, a local variable can still hold a reference or pointer to a shared object. In that case, accessing the object through that local variable can still cause a race condition.</p><h3>The Problem: A Race Condition</h3><p>Imagine we have a shared variable called counter, initially set to 5.</p><p>Two threads, A and B, want to increment it by one.</p><p>The expected result is 7.</p><p>But here’s something important: an operation like:</p><pre>counter = counter + 1;</pre><p>is not necessarily executed as one indivisible operation.</p><p>Conceptually, it involves three steps:</p><p>1. Read → Read the current value of counter.<br>2. Add → Add 1 to the value.<br>3. Write → Store the new value back into counter.</p><p>The operating system’s scheduler can switch between threads while these operations are in progress.</p><p>Let’s see what could happen:</p><pre>Initial value: counter = 5</pre><ul><li>Thread A: Read → reads 5</li><li>Thread B: Read → reads 5 (before A writes)</li><li>Thread A: Add → calculates 6</li><li>Thread B: Add → calculates 6</li><li>Thread A: Write → stores 6</li><li>Thread B: Write → stores 6 (overwrites A’s result)</li></ul><p>Final value: counter = 6</p><p>The expected result was 7, but we got 6.</p><p>One increment was lost!</p><p>Even worse, there’s no error or crash. The program may work correctly many times and fail only under certain timing conditions, making the problem difficult to reproduce and debug.</p><p>This is called a <strong>Race Condition</strong>: the result of an operation depends on the timing or order in which multiple threads access shared data.</p><p>And this is exactly why we need synchronization.</p><h3>Critical Section and Mutual Exclusion</h3><p>A <strong>Critical Section</strong> is a part of the code that accesses shared data and must be protected from conflicting concurrent access.</p><p>In our example, the critical section includes the three operations:</p><ul><li>Read → Add → Write</li></ul><p>The basic rule is:</p><p><strong>Only one thread should be allowed inside a protected critical section at a time.</strong></p><p>This principle is called <strong>Mutual Exclusion</strong>.</p><p>If one thread is executing the critical section, another thread trying to enter it must wait until the first one leaves.</p><h3>The Solution: Locks (Mutex)</h3><p>Think of a bathroom with only one key.</p><ul><li>Whoever wants to enter must take the key.</li><li>Once inside, they keep the key.</li><li>After finishing, they return it.</li><li>If someone else wants to enter while the key is taken, they have to wait.</li></ul><p>A <strong>Lock</strong> works in a similar way.</p><p>A thread acquires the lock before entering the critical section and releases it after finishing.</p><p>Let’s apply this to our counter:</p><ul><li>Thread A: Lock → Read → Add → Write → Unlock</li><li>Thread B: Waiting...</li></ul><p>Then:</p><ul><li>Thread B: Lock → Read → Add → Write → Unlock</li></ul><p>Now Thread A completes the entire operation before Thread B can access the protected data.</p><p>The result becomes:</p><pre>Initial value: 5</pre><ul><li>Thread A: Reads 5 → Writes 6</li><li>Thread B: Reads 6 → Writes 7</li></ul><p>Final value: counter = 7</p><p>A <strong>Mutex</strong> (short for Mutual Exclusion) is a synchronization mechanism that allows only one thread at a time to own a particular lock.</p><p>One important rule: <strong>Always release the lock, even if an error occurs.</strong></p><p>Otherwise, other threads may wait indefinitely for a lock that will never become available.</p><p>This is why programming languages often provide mechanisms such as try/finally, defer, or scoped locking to ensure that locks are released safely.</p><h3>Other Synchronization Mechanisms</h3><p>There are several synchronization tools, each designed for different situations:</p><p>MechanismMain Idea<strong>Mutex / Lock</strong>Allows only one thread at a time to enter a protected section.<strong>Semaphore</strong>Controls access to a resource with a limited number of available permits. For example, three threads can access a resource simultaneously.<strong>Atomic Operations</strong>Operations performed indivisibly, without exposing intermediate states to other threads.<strong>Condition Variable</strong>Allows a thread to wait until another thread signals that a particular condition may now be true.</p><p>These mechanisms solve different synchronization problems, and choosing the right one depends on the situation.</p><h3>Can We Avoid Locks Altogether?</h3><p>Sometimes, the best way to solve shared-data problems is to avoid sharing mutable data in the first place.</p><p>For example:</p><ul><li><strong>Thread-local Data:</strong> Each thread works with its own independent copy of the data.</li><li><strong>Immutable Data:</strong> Data that cannot be modified after creation can safely be shared without worrying about concurrent modifications.</li><li><strong>Message Passing:</strong> Instead of allowing threads to modify the same shared memory, they exchange messages containing the data they need.</li></ul><p>Message passing is especially interesting because it introduces a different approach to concurrency, which we’ll encounter later when exploring other execution models.</p><h3>The Cost of Synchronization</h3><p>Locks solve race conditions, but they are not free.</p><p><strong>1. Performance Overhead</strong></p><p>When one thread holds a lock, other threads trying to acquire it may have to wait.</p><p>If the critical section is too large or many threads compete for the same lock, execution can become effectively sequential, reducing the benefits of multithreading.</p><p><strong>2. More Complex Code</strong></p><p>You need to make sure every access to shared data is properly protected. Missing a lock in even one place can reintroduce race conditions.</p><p><strong>3. Deadlocks</strong></p><p>Synchronization can introduce another serious problem.</p><p>Imagine:</p><ul><li>Thread A holds Lock 1 and waits for Lock 2.</li><li>Thread B holds Lock 2 and waits for Lock 1.</li></ul><p>Neither thread can continue because each is waiting for a resource held by the other.</p><p>Both threads remain stuck indefinitely.</p><p>This is called a <strong>Deadlock</strong>, and it’s one of the most important problems to understand when working with concurrent programs.</p><p><strong>Practical rule:</strong> Keep critical sections as small as possible and hold locks for the shortest time necessary.</p><p>Synchronization helps threads work safely together, but good concurrency design also means knowing when not to share data at all.</p><p>Conclusion</p><p>Every app you use, from a tiny command to a full-featured application, follows the same journey: a program sits on disk, the operating system loads it into memory, and the CPU executes it one instruction at a time. That running program is a process, an isolated box of resources, and inside it live threads, the actual lines of execution that share the box’s memory while keeping their own stack and registers.</p><p>Because a core can run only one thread at a time, the scheduler switches between threads so quickly that everything appears to run at once. That is concurrency. When multiple cores run threads at the very same instant, that is parallelism. Both help in different ways: concurrency keeps programs responsive while they wait, and parallelism speeds up heavy computation.</p><p>This is why the main thread matters so much. In any program with a user interface, one thread is responsible for drawing and responding to input, so slow work placed on it freezes everything, no matter how many idle cores are available. The fix is simple in principle: keep the main thread free, and move slow work elsewhere.</p><p>But sharing memory comes at a price. When threads touch the same data without coordination, you get race conditions: wrong results that appear randomly and are hard to reproduce. Locks solve this, but misused locks create deadlocks, where threads wait on each other forever. The safest strategy is to share less: prefer immutable data, confine data to a single thread, and pass messages instead of sharing state. When sharing is unavoidable, lock as little as possible, for as short a time as possible, and always in a consistent order.</p><p>Understanding these foundations won’t just help you write safer code. It gives you a mental model that applies to every language and framework, so whenever you meet a new concurrency tool, you’ll know which problem it is solving and what it costs you.</p><p>Finally , I hope the article was useful to you and your opinion is very important to me.</p><p><a href="https://www.linkedin.com/in/rwan-hossam-08ba39295">LinkedIn</a></p><p><a href="https://github.com/RwanHossamEldein">GitHub</a></p><p><a href="http://rwanhossam0@gmail.com/">Email</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65c17df54e02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Imagine developing one codebase that you can use to create separate Development and Production…]]></title>
            <link>https://medium.com/easy-flutter/imagine-developing-one-codebase-that-you-can-use-to-create-separate-development-and-production-73284d656e83?source=rss-e6594c14ec85------2</link>
            <guid isPermaLink="false">https://medium.com/p/73284d656e83</guid>
            <dc:creator><![CDATA[Rwan Hossam Eldein]]></dc:creator>
            <pubDate>Sat, 03 Oct 2026 14:36:07 GMT</pubDate>
            <atom:updated>2026-10-03T14:36:07.736Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZwIUn2Tpvg1oQmu2sEUmjQ.png" /></figure><p>Imagine developing one codebase that you can use to create separate Development and Production versions of your app.</p><p>And not only that you can also use the same codebase to build multiple apps for completely different brands, simply by changing things like the logo<strong>,</strong> colors<strong>, </strong>assets<strong>, </strong>and API endpoints.</p><p><strong>Sounds interesting? </strong><br>In this article, we’ll explore Branding<strong>, </strong>Flavors<strong>,</strong> and Multi-Branding in Flutter and see how they can help us build and manage multiple app versions efficiently.</p><h3>1. What Does Branding Mean?</h3><p>Every app has its own theme<strong>, </strong>colors<strong>, </strong>logo<strong>, </strong>icons<strong>, </strong>app name<strong>, </strong>and assets that make it visually different and recognizable from other apps.</p><p>These elements together form the app’s Branding the visual identity that makes the app unique and represents its brand.</p><h3>2. Flavors In Flutter</h3><p>Flavors allow us to create different versions of the same application from a single codebase, where each version can have its own configuration and environment</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AcFVigTNRv81ASi4lzKy3A.png" /></figure><p>Imagine you have an app that is currently running in Production with real users.</p><p>Now, you receive a change to an existing feature, or you need to add a new feature.</p><p>Of course, we wouldn’t deploy the changes directly to Production and start testing them with real users and the Production Database, because any bug could affect the users’ experience or even compromise important data.</p><p>That’s why we need separate environments where we can safely develop and test our changes, such as:</p><p><strong>Development → Staging → Production</strong></p><p>Each environment has its own configuration and is usually connected to a separate Backend and Database.</p><p>And this is where Flavors come in.</p><p>In Flutter, we use Flavors to create different versions of the same app, where each version has the appropriate configuration for the environment we’re working with.</p><p>This allows us to use the same codebase while running the app with different configurations depending on the environment, without affecting Production or real users during development and testing.</p><h3>3.Flutter Flavors Implementation</h3><p><strong>Let’s assume we want 3 flavors:</strong></p><ul><li>Development</li><li>Staging</li><li>Production</li></ul><h3>1- Flavors in Android</h3><p>Before we dive deeper into this part, we need to understand what a product flavor and a flavor dimension are .</p><h4>Flavor Dimensions</h4><p>Flavor Dimensions are the categories based on which we want to differentiate our project.</p><p>For example, imagine we have a fabric store. The store owner might organize the products based on different categories, such as material<strong>,</strong> color, or price.</p><p>If the owner wants to organize the products based on material and color, then we can think of these as two different dimensions:</p><ul><li><strong>Material</strong> → Cotton, Silk</li><li><strong>Color</strong> → White, Blue, Black</li></ul><p>So, in this case, we have two dimensions, because we are differentiating the products based on two different criteria.</p><p>The same idea applies to our Flutter/Android project. We create a Flavor Dimension for each category based on which we want our application to be different.</p><h4>Product Flavors</h4><p>Product Flavors are the different options within a Flavor Dimension.</p><p>For example, in our fabric store, if material is a dimension, its product flavors could be:</p><ul><li><strong>Cotton</strong></li><li><strong>Silk</strong></li><li><strong>Linen</strong></li></ul><p>And if <strong>color</strong> is another dimension, its product flavors could be:</p><ul><li><strong>Red</strong></li><li><strong>Blue</strong></li><li><strong>Black</strong></li></ul><p>So, simply:</p><blockquote><strong>Flavor Dimension = the category</strong></blockquote><blockquote><strong>Product Flavor = the option inside that category</strong></blockquote><pre>If you have multiple Flavor Dimensions, the number of Product Flavors is the sum of the flavors in each dimension.<br>For example:<br>Dimension 1 → 2 flavors<br>Dimension 2 → 3 flavors<br><br>Total Product Flavors = 2 + 3 = 5<br><br>However, the number of possible Build Variants is calculated by multiplying the number of flavors in each dimension:<br>Build Variants = 2 × 3 = 6</pre><p><strong>let’s see how they are used in Android.</strong></p><p>For the practical steps, you can find them in the official documentation here: <a href="https://docs.flutter.dev/deployment/flavors"><strong>Documentation Link</strong></a></p><p>Although we are working with Flutter, the flavor configuration itself is handled by the native platform’s build system.</p><p>For Android, this means <strong>Gradle</strong> is responsible for defining the flavor dimensions and product flavors, and then combining them to create different <strong>Build Variants</strong>.</p><p>Flutter works on top of this system. When we run or build our application, Flutter communicates with the Android build system and tells it which flavor we want to use.</p><p>For example, suppose we have two dimensions:</p><ul><li><strong>Brand:</strong> Client A, Client B</li><li><strong>Environment:</strong> Dev, Prod</li></ul><p>Android can combine these flavors to create different configurations:</p><ul><li>Client A+ Dev</li><li>Client A+ Prod</li><li>Client B + Dev</li><li>Client B + Prod</li></ul><p>Each combination represents a different <strong>Build Variant</strong> with its own configuration.</p><p><strong>Flutter → Android → Gradle → Flavors → Build Variant → Final App</strong></p><p>Flutter contains the shared application code, while Gradle handles the Android-specific differences between the different app versions.</p><blockquote>Flutter uses the native platform’s build system to create and manage platform-specific flavors.</blockquote><h3>2- Flavors in IOS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c47kxLyRZI4LYgA6Me_fnA.png" /></figure><p>The first important thing to understand is that iOS does not use the same flavor system as Android.</p><p>In Android, we have concepts such as:</p><ul><li>Flavor Dimensions</li><li>Product Flavors</li><li>Build Variants</li></ul><p>These concepts are provided by the Android build system through <strong>Gradle</strong>.</p><p>On iOS, the same goal is achieved using different Xcode concepts, mainly:</p><ul><li><strong>Targets</strong></li><li><strong>Build Configurations</strong></li><li><strong>Schemes</strong></li></ul><p>So, although the terminology is different, the idea is similar:</p><blockquote><strong><em>We want to use one codebase to build different versions of the same application, each with its own configuration.</em></strong></blockquote><h3>What is Xcode?</h3><p>Xcode is Apple’s development environment and toolchain for building iOS applications.</p><blockquote>Xcode is not exactly the equivalent of Gradle.<br> Gradle is primarily a build system, while Xcode is Apple’s development environment that also provides the build system and project configuration tools.</blockquote><h3>Target</h3><p><strong><em>What am I building?</em></strong></p><h3>Configuration</h3><p>With which settings am I building it?</p><blockquote>Each configuration can contain a different set of build settings.</blockquote><h3>Scheme</h3><p>Which Target + Configuration should Xcode use?</p><blockquote>The Target identifies the app, while the Build Configuration defines how that app is built. A Scheme combines both.</blockquote><p>For the practical steps, you can find them in the official documentation here: <a href="https://docs.flutter.dev/deployment/flavors-ios"><strong>Documentation Link</strong></a></p><p>Conclusion</p><p>Flavors are a powerful way to manage multiple versions of the same application while keeping a single codebase.</p><p>Finally , I hope the article was useful to you and your opinion is very important to me.</p><p><a href="https://www.linkedin.com/in/rwan-hossam-08ba39295">LinkedIn</a></p><p><a href="https://github.com/RwanHossamEldein">GitHub</a></p><p><a href="http://rwanhossam0@gmail.com/">Email</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73284d656e83" width="1" height="1" alt=""><hr><p><a href="https://medium.com/easy-flutter/imagine-developing-one-codebase-that-you-can-use-to-create-separate-development-and-production-73284d656e83">Imagine developing one codebase that you can use to create separate Development and Production…</a> was originally published in <a href="https://medium.com/easy-flutter">Easy Flutter</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Notifications are an essential part of modern mobile applications.]]></title>
            <link>https://medium.com/easy-flutter/notifications-are-an-essential-part-of-modern-mobile-applications-f6193fa1d5ae?source=rss-e6594c14ec85------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6193fa1d5ae</guid>
            <dc:creator><![CDATA[Rwan Hossam Eldein]]></dc:creator>
            <pubDate>Sat, 29 Aug 2026 13:59:17 GMT</pubDate>
            <atom:updated>2026-08-30T09:52:53.599Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aNss0ZWR40Je4eVGnHL7xA.png" /></figure><p>Notifications are an essential part of modern mobile applications. They allow apps to communicate with users, remind them about important events, and keep them updated even when the app is not currently open.</p><p>In Flutter, notifications can come from different sources and can be handled in different ways depending on the application’s requirements. For example, an app may need to show a reminder locally on the user’s device, or receive a notification from a backend server using Firebase Cloud Messaging (FCM).</p><p>In this article, we will explore <strong>Notifications in Flutter</strong>. We will understand the different types of notifications, how they work, how to implement them in Flutter, and how to handle different notification states and interactions.</p><p>By the end of this article, you should have a clear understanding of how notifications work in Flutter and how to integrate them properly into a real-world application.</p><h3><strong>What is a Notification?</strong></h3><p>A notification is a message delivered to the user to inform them that an event has occurred or that some information requires their attention.</p><p>When we say <strong>notification</strong>, we may be referring to a specific type of notification or a specific way of delivering it. Notifications can come from different sources and can be displayed to the user in different ways depending on the purpose of the application.</p><h3>Notification Sources</h3><p>Notifications can come from two main sources:</p><h3>1. Server → User</h3><p>The server sends a notification to the user’s device to inform them about an event or update.</p><p><strong>Example:</strong></p><blockquote><em>“Your order has been shipped ”</em></blockquote><p>In this case, the event happens on the server, and the server sends a <strong>push notification</strong> to the user’s device.</p><h3>2. App → User</h3><p>The application can create a notification locally on the user’s device without requiring a server.</p><p><strong>Example:</strong></p><blockquote><em>“Don’t forget to study Flutter at 8 PM ”</em></blockquote><p>This is called a <strong>local notification</strong>. The app can schedule it on the device, and the operating system can display it at the scheduled time, even if the app is not currently open.</p><h4>The Basic Flow</h4><p><strong>Server → Push Notification → Device → User</strong></p><p><strong>App → Local Notification → Device → User</strong></p><h3>Notification Forms</h3><p>Notifications can also be classified based on <strong>how and where they are displayed to the user</strong>.</p><h4>1. System Notification</h4><p>A system notification is displayed by the <strong>Operating System</strong> using its built-in notification UI.</p><p>For example, it may appear as a banner, in the notification tray, or on the lock screen.</p><p>The appearance and behavior of the notification are mainly controlled by the OS.</p><h4>2. Notification Page</h4><p>A notification page is an <strong>in-app page that keeps a history of notifications</strong>.</p><p>Instead of disappearing after being displayed, notifications can be stored and shown to the user in a dedicated page.</p><p>This allows users to view previous notifications whenever they want.</p><h4>3. In-App Notification</h4><p>An in-app notification is a notification displayed <strong>inside the application using a custom UI</strong> instead of the standard system notification UI.</p><p>The developer has full control over its appearance and behavior.</p><p>For example, it can be displayed as:</p><ul><li>A custom banner</li><li>A Snackbar</li><li>A Dialog</li><li>A custom widget</li></ul><h3>Important Note</h3><p>The <strong>source</strong> of a notification and its <strong>form</strong> are two different concepts.</p><p>For example, a notification can come from a <strong>server</strong> and then be displayed as a <strong>system notification</strong>, stored in a <strong>notification history page</strong>, or shown as an <strong>in-app notification</strong>.</p><p>So we can think about notifications from two different perspectives:</p><p><strong>Source:</strong></p><p>Server → User</p><p>App/Device → User</p><p><strong>Form:</strong></p><p>System Notification</p><p>Notification Page</p><p>In-App Notification</p><h3>How Notifications Work</h3><p>Before understanding how notifications work, we first need to understand the different states of a mobile application.</p><h3>App States</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WlQ6gOhjIzifrf-tZHzmOw.png" /></figure><p>An application can be in one of the following states:</p><h4>1. Foreground</h4><p>The application is currently open and the user is actively interacting with it.</p><h4>2. Background</h4><p>The application is not currently visible to the user, but it is still running in the background.</p><h4>3. Terminated</h4><p>The application is not currently running.</p><blockquote><strong><em>Note:</em></strong><em> Uninstalling the application or logging out is not considered an app lifecycle state. Uninstalling is an </em><strong><em>installation state</em></strong><em>, while logging out is an </em><strong><em>authentication state</em></strong><em>.</em></blockquote><h3>Notification Flow</h3><p>The flow of a notification depends on two main things:</p><ul><li><strong>The source of the notification:</strong> Local or Push</li><li><strong>The way it is presented:</strong> System Notification, In-App Notification, or Notification History</li></ul><p>For example, a Local Notification can be presented as a system notification:</p><p><strong>App → Schedule Notification → OS → System Notification → User</strong></p><p>In this case, the app schedules the notification, and the Operating System is responsible for displaying it to the user at the scheduled time.</p><p>However, a Local event can also be handled inside the application:</p><p><strong>App → Event Occurs → In-App UI → User</strong></p><p>Or the application can store the notification and display it later in a notification history page:</p><p><strong>App → Event Occurs → Store Notification → Notification Page → User</strong></p><p>Therefore, the <strong>notification source</strong> and the <strong>notification presentation</strong> are separate concepts.</p><p>A notification being <strong>Local</strong> or <strong>Push</strong> does not by itself determine how the user will see it.</p><h4>1- Local Notification Flow</h4><p>A Local Notification is a notification that is scheduled or triggered locally by the app on the user’s device, without requiring a server to send the notification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9SRnqm7b_7ObbrthweAXLg.jpeg" /><figcaption>Local Notification Flow</figcaption></figure><h4>2- Push notification Flow</h4><p>A push notification is a notification initiated by a server or backend and sent to the user’s device via a push notification service such as FCM to alert the user about an event or update.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5hkxUv8u6V1ZteXbEEzP3g.jpeg" /><figcaption>Push notification Flow</figcaption></figure><h3>FCM Architecture</h3><ul><li>FCM = Firebase Cloud Messaging</li></ul><p>Firebase Cloud Messaging is a service provided by Firebase that allows a <strong>Backend</strong> to deliver messages to users’ devices.</p><p>A Push Notification is a concept, while FCM is one service that can be used to implement it.</p><p>Other services include:</p><ul><li><strong>FCM</strong> → Firebase</li><li><strong>APNs</strong> → Apple</li><li><strong>OneSignal</strong> → Third-party service</li></ul><p>So, when we study FCM, we are not studying the concept of Push Notifications from scratch. We are studying <strong>one implementation of Push Notification delivery</strong>.</p><h4>What is an FCM Registration Token?</h4><p><em>When an application uses Firebase Messaging, Firebase provides it with an FCM Registration Token.</em></p><p>The token identifies a specific <strong>app installation , messaging target</strong> that FCM can use to deliver messages.</p><h4>Why Do We Need the Token?</h4><p>Imagine that the application has one million users.</p><p>The Backend needs a way to determine which app installation should receive a particular push message.</p><p>The FCM Token provides the target that FCM can use for message delivery.</p><blockquote>User ID ≠ FCM Token</blockquote><blockquote>This distinction is extremely important.</blockquote><h4>User ID</h4><p>The <strong>User ID</strong> identifies the user inside the Backend system.</p><pre>User ID = 25</pre><h4>FCM Token</h4><p>The <strong>FCM Registration Token</strong> identifies an app installation , messaging target that FCM can use for delivery.</p><blockquote>Therefore, one user can have multiple app installations and multiple tokens</blockquote><blockquote>One User → Multiple App Installations → Multiple FCM Tokens</blockquote><p>Also, FCM tokens are not permanent identifiers. They can be refreshed or replaced, so the Backend needs to keep them up to date.</p><h4>How Does the Backend Know the Token?</h4><p>After the app obtains its current FCM Token, it sends the token to the Backend.</p><p>A simplified flow is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BOyxeCCterGZs867ld0FnQ.png" /></figure><p>The core idea is:</p><blockquote><strong><em>The Backend manages the relationship between users and app installations, while FCM provides the delivery mechanism for Push Messages. The Notification Page is application data, while the System Notification is one possible presentation of a delivered push message.</em></strong></blockquote><h3>How to Implement Notifications in Flutter</h3><p>Now that we understand the difference between notification sources, presentation forms, and the role of FCM, let’s move to the practical part.</p><p>In Flutter, notifications can be implemented in different ways depending on where the notification originates and how it should be presented.</p><p>We will cover three common approaches:</p><ol><li><strong>Push Notifications with FCM</strong> — receiving messages from a backend through Firebase Cloud Messaging and handling them on the device.</li><li><strong>In-App Notifications</strong> — retrieving notification data from the backend through an API and displaying it inside a dedicated Notifications Page.</li><li><strong>Local Notifications</strong> — creating or scheduling notifications directly on the user’s device without requiring a backend.</li></ol><h3><strong>1.Push Notifications with FCM</strong></h3><ul><li><strong>Step 1: Set Up Firebase</strong></li></ul><p>First, we need to create a Firebase project and connect it to our Flutter application.</p><p>For Flutter applications, the recommended approach is to use the <strong>FlutterFire CLI</strong>, which configures the Firebase services and generates the required configuration file.</p><p>After configuring Firebase, a firebase_options.dart file is generated. This file contains the Firebase configuration for the supported platforms.</p><p>initialize Firebase when the application starts:</p><pre>Future&lt;void&gt; main() async {<br> WidgetsFlutterBinding.ensureInitialized();<br> await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);<br> runApp(const MyApp()<br>);<br> }</pre><p>Now the Flutter application is connected to Firebase and can use Firebase services such as Firebase Cloud Messaging.</p><ul><li><strong>Step 2: Add Firebase Messaging</strong></li></ul><pre>//in the terminal run this command<br><br><br>flutter pub add firebase_messaging<br></pre><ul><li><strong>Step 3: Request Notification Permission</strong></li></ul><pre>final messaging = FirebaseMessaging.instance;<br><br>final settings = await messaging.requestPermission(<br>  alert: true,<br>  badge: true,<br>  sound: true,<br>);</pre><ul><li><strong>Step 4: Get the FCM Token</strong></li></ul><pre>final token = await FirebaseMessaging.instance.getToken();<br><br>print(&#39;FCM Token: $token&#39;);</pre><ul><li><strong>Step 5: Send the Token to Backend</strong></li></ul><pre>await api.sendFcmToken(token);</pre><ul><li><strong>Step 6: Handle Incoming Messages</strong></li></ul><pre>// foreground<br>FirebaseMessaging.onMessage.listen((RemoteMessage message) {<br> // Handle Handle Incoming Messages<br>});</pre><h3>2. In-App Notifications</h3><p>In-app notifications are usually retrieved from the Backend through an API and displayed inside a dedicated Notifications Page.</p><p>The Backend stores the notification data, while the Flutter application is responsible for fetching and presenting it.</p><p>A simplified flow looks like this:</p><pre>Backend=&gt; Database =&gt; Notifications API =&gt; Flutter =&gt; Notifications Page</pre><p>For example, Flutter may request the user’s notifications:</p><pre>final notifications = await api.getNotifications();</pre><p>The application can then display the returned data in a ListView.</p><p>Unlike FCM Push Notifications, this approach does not require a push notification service to display the notification history. It is simply application data retrieved from the Backend.</p><h3>3. Local Notifications</h3><p>Local Notifications are notifications created and scheduled directly by the application on the user’s device without requiring a backend or a push notification service such as FCM.</p><p>They are useful for use cases such as reminders, scheduled tasks, alarms, and other events that can be handled locally.</p><p>In Flutter, one of the commonly used packages for implementing local notifications is <a href="https://pub.dev/packages/flutter_local_notifications">flutter_local_notifications</a>.</p><ul><li><strong>Step 1: Add the Package</strong></li></ul><p>First, add the flutter_local_notifications package to the pubspec.yaml file</p><p>The package provides an API that allows the Flutter application to interact with the notification system provided by the operating system.</p><ul><li><strong>Step 2: Create the Notification Plugin</strong></li></ul><p>Create an instance of FlutterLocalNotificationsPlugin:</p><pre>final FlutterLocalNotificationsPlugin<br>    flutterLocalNotificationsPlugin =<br>    FlutterLocalNotificationsPlugin();</pre><p>It is usually better to keep notification-related logic inside a dedicated service or class rather than placing everything inside main.dart.</p><p>For example:</p><pre>class NotificationService {<br>  final FlutterLocalNotificationsPlugin _notifications =<br>      FlutterLocalNotificationsPlugin();<br>}</pre><p>This keeps notification logic separated from the UI and makes the code easier to maintain.</p><p><strong>- Step 3: Initialize the Plugin</strong></p><p>Before showing any notification, the plugin needs to be initialized.</p><p>For Android, we provide the application icon that will be used by the notification:</p><pre>const AndroidInitializationSettings androidSettings =<br>    AndroidInitializationSettings(&#39;@mipmap/ic_launcher&#39;);</pre><p>Then we create the platform-specific initialization settings:</p><pre>const InitializationSettings initializationSettings =<br>    InitializationSettings(<br>  android: androidSettings,<br>);</pre><p>Finally, initialize the plugin:</p><pre>await flutterLocalNotificationsPlugin.initialize(<br>  initializationSettings,<br>);</pre><p>We can put this inside an initialization method:</p><pre>Future&lt;void&gt; initialize() async {<br>  const androidSettings =<br>      AndroidInitializationSettings(&#39;@mipmap/ic_launcher&#39;);<br>const settings = InitializationSettings(<br>    android: androidSettings,<br>  );<br>  await flutterLocalNotificationsPlugin.initialize(<br>    settings,<br>  );<br>}</pre><p>Then call it before runApp():</p><pre>Future&lt;void&gt; main() async {<br>  WidgetsFlutterBinding.ensureInitialized();<br>final notificationService = NotificationService();<br>  await notificationService.initialize();<br>  runApp(const MyApp());<br>}</pre><p>The initialization prepares the plugin to communicate with the operating system’s notification APIs.</p><ul><li><strong>Step 4: Request Notification Permission</strong></li></ul><p>We can request it using:</p><pre>final androidImplementation =<br>    flutterLocalNotificationsPlugin<br>        .resolvePlatformSpecificImplementation&lt;<br>            AndroidFlutterLocalNotificationsPlugin&gt;();<br>await androidImplementation?.requestNotificationsPermission();</pre><p>The exact permission behavior depends on the Android version and platform configuration.</p><p>This step is important because creating a notification does not guarantee that the user will actually see it if notification permission has not been granted.</p><ul><li><strong>Step 5: Configure Notification Details</strong></li></ul><p>Before displaying a notification, we need to define how it should behave.</p><p>For Android, this includes creating a <strong>Notification Channel</strong>.</p><pre>const AndroidNotificationDetails androidDetails =<br>    AndroidNotificationDetails(<br>  &#39;reminders_channel&#39;,<br>  &#39;Reminders&#39;,<br>  channelDescription: &#39;Notifications for reminders&#39;,<br>  importance: Importance.high,<br>  priority: Priority.high,<br>);<br>//The first parameter is the channel ID:reminders_channel<br>//The second is the channel name:Reminders</pre><p>Then create the platform-independent NotificationDetails:</p><pre>const NotificationDetails notificationDetails =<br>    NotificationDetails(<br>  android: androidDetails,<br>);<br></pre><p>The channel can also define properties such as notification importance, sound, and other Android notification behavior.</p><ul><li><strong>Step 6: Show an Immediate Notification</strong></li></ul><p>Now we can display a notification immediately using the show() method:</p><pre>final notificationId = DateTime.now().millisecondsSinceEpoch ~/ 1000;<br>    await plugin.show(<br>      id: notificationId,<br>      title: title,<br>      body: body,<br>      notificationDetails: details,<br>    );</pre><p>For example, we can create a reusable method:</p><pre>Future&lt;void&gt; showNotification() async {<br>  const androidDetails = AndroidNotificationDetails(<br>    &#39;reminders_channel&#39;,<br>    &#39;Reminders&#39;,<br>    channelDescription: &#39;Notifications for reminders&#39;,<br>    importance: Importance.high,<br>    priority: Priority.high,<br>  );<br>const details = NotificationDetails(<br>    android: androidDetails,<br>  );<br>  await flutterLocalNotificationsPlugin.show(<br>    0,<br>    &#39;Study Reminder&#39;,<br>    &#39;Don&#39;t forget to study Flutter!&#39;,<br>    details<br>  );<br>}</pre><p>Calling:</p><pre>showNotification();</pre><p>will immediately request the operating system to display the notification.</p><p>The important point here is that <strong>Flutter is not drawing the notification UI itself</strong>. The Flutter application requests the notification, while the operating system is responsible for displaying it.</p><h3>Conclusion</h3><p>Notifications are an important part of building modern mobile applications. They allow applications to communicate with users, keep them informed, and provide timely updates and reminders.</p><p>As we have seen, notifications are not limited to a single type or implementation. They can come from different sources and be presented in different ways.</p><p>Finally , I hope the article was useful to you and your opinion is very important to me.</p><p><a href="https://www.linkedin.com/in/rwan-hossam-08ba39295">LinkedIn</a></p><p><a href="https://github.com/RwanHossamEldein">GitHub</a></p><p><a href="http://rwanhossam0@gmail.com/">Email</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6193fa1d5ae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/easy-flutter/notifications-are-an-essential-part-of-modern-mobile-applications-f6193fa1d5ae">Notifications are an essential part of modern mobile applications.</a> was originally published in <a href="https://medium.com/easy-flutter">Easy Flutter</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Every technology has its own architecture.]]></title>
            <link>https://medium.com/easy-flutter/every-technology-has-its-own-architecture-571a80f935ef?source=rss-e6594c14ec85------2</link>
            <guid isPermaLink="false">https://medium.com/p/571a80f935ef</guid>
            <dc:creator><![CDATA[Rwan Hossam Eldein]]></dc:creator>
            <pubDate>Sat, 01 Aug 2026 13:48:01 GMT</pubDate>
            <atom:updated>2026-08-01T13:48:01.458Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*behcwAAd8pAdsXD6E68JrQ.png" /></figure><p>Every technology has its own architecture. Whether it’s Clean Architecture, MVVM, MVC, or others, they all aim for the same goal: making software easier to understand, maintain, and evolve.</p><p>But have you ever stopped and asked yourself:</p><p><strong>Why do these architectures look the way they do?</strong></p><p>Who decided to separate the code into layers? Why do we inject dependencies instead of creating objects directly? Why do experienced developers keep recommending certain practices while avoiding others?</p><p>The answer is simple: <strong>architectures weren’t created by chance.</strong></p><p>They are the result of years of solving real-world software problems. Developers repeatedly encountered code that was difficult to maintain, tightly coupled, hard to test, and nearly impossible to extend. Over time, they discovered principles that consistently led to better software. Later, recurring solutions to common design problems became what we now call <strong>Design Patterns</strong>, and many <strong>software architectures</strong> were built around these same ideas.</p><p>So before learning any architecture or memorizing design patterns, it’s worth understanding the foundation they all stand on: <strong>Software Design Principles</strong>.</p><h3>What are Software Design Principles?</h3><p>Software Design Principles are guidelines — not strict rules — that help developers make better design decisions. They are based on years of experience solving real-world software problems and are intended to produce code that is easier to understand, maintain, test, and extend.</p><p>Think of them as engineering principles rather than programming rules. They don’t tell you exactly what to write, but they help you choose the better design when more than one solution is possible.</p><h3>Why do we even need them?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HRFnlkZ4Fj9EokDSp8gYqQ.png" /></figure><h3>Coupling &amp; Cohesion</h3><p>When discussing software design, you’ll often hear two terms mentioned together: <strong>Coupling</strong> and <strong>Cohesion</strong>.</p><p>Although they’re different concepts, they complement each other.</p><p>Think of them as two questions you should ask whenever you design a class:</p><ul><li><strong>How much does this class depend on other classes?</strong> → <strong>Coupling</strong></li><li><strong>Does this class have a single, well-defined responsibility?</strong> → <strong>Cohesion</strong></li></ul><p>Good software usually aims for <strong>low coupling</strong> and <strong>high cohesion</strong>.</p><h4>1. What is Coupling?</h4><p><strong>Coupling</strong> measures how dependent one class or module is on another.</p><p>The more a class knows about or relies on the implementation details of other classes, the higher the coupling becomes.</p><blockquote>Imagine a new employee who can’t complete any task without asking the manager, the accountant, and the HR department. If any one of them changes the way they work, the employee also has to change.</blockquote><p>The same idea applies to software. When a class depends heavily on other classes, even a small change in one place can force changes elsewhere.</p><pre>class UserService {<br>  final EmailService emailService;<br><br>  UserService(this.emailService);<br><br>  void registerUser() {<br>    emailService.send();<br>  }<br>}</pre><p>Here, UserService depends directly on EmailService. This dependency is called coupling.</p><p>Suppose the company decides to replace EmailService with SMSService. If UserService must also be modified, the classes are tightly coupled.</p><h4>2.Tight Coupling vs. Loose Coupling</h4><p>Not all dependencies are bad. The real question is <strong>how</strong> a class depends on another.</p><h4>Tight Coupling</h4><p>A class is <strong>tightly coupled</strong> when it depends directly on a specific implementation.</p><pre>class UserService {<br>  final EmailService emailService;<br><br>  UserService(this.emailService);<br>}</pre><p>In this example, UserService knows exactly which notification service it uses. If the application later switches from email to SMS or push notifications, UserService must also be modified.</p><p>This makes the code harder to maintain and extend.</p><h4>Loose Coupling</h4><p>Instead of depending on a concrete implementation, a class can depend on an abstraction, such as an interface or an abstract class.</p><pre>abstract class NotificationService {<br>  void send();<br>}<br><br>class EmailService implements NotificationService {<br>  @override<br>  void send() {}<br>}<br><br>class SMSService implements NotificationService {<br>  @override<br>  void send() {}<br>}<br><br>class UserService {<br>  final NotificationService notificationService;<br><br>  UserService(this.notificationService);<br>}</pre><p>Now UserService doesn&#39;t care whether notifications are sent by email, SMS, or any future service. It only knows that it can call send().</p><p>As long as the new implementation follows the same abstraction, UserService doesn&#39;t need to change.</p><h4>Benefits of Loose Coupling</h4><p><strong>Loose coupling makes software:</strong></p><ul><li>Easier to maintain.</li><li>Easier to test.</li><li>Easier to extend with new features.</li><li>Less likely to break when requirements change.</li></ul><p>This is one of the main reasons why concepts such as Dependency Injection, interfaces, and the Repository Pattern are widely used. Their goal is to reduce unnecessary coupling between different parts of the application.</p><h4>Other Types of Coupling</h4><ul><li><strong>Content Coupling (Worst)</strong> — A class directly modifies the internal data of another class.</li><li><strong>Common Coupling</strong> — Multiple classes share the same global variable or shared state.</li><li><strong>Control Coupling</strong> — A class passes a flag or parameter to another class to control its behavior .</li><li><strong>Stamp Coupling</strong> — A class passes an entire object to another class even though only a small part of that object is needed.</li><li><strong>Data Coupling (Best)</strong> — A class passes only the exact data that another class actually needs.</li></ul><h4>3.What is Cohesion?</h4><p>While <strong>Coupling</strong> focuses on the relationship between different classes, <strong>Cohesion</strong> focuses on how well the responsibilities inside a single class or module are related.</p><p>In other words, Cohesion asks:</p><blockquote><em>Does this class have one clear purpose, or does it try to handle multiple unrelated responsibilities?</em></blockquote><p>A good design usually aims for <strong>high cohesion</strong>, where every part of a class contributes to the same responsibility.</p><h4>High Cohesion Example</h4><pre>class UserService {<br><br>  void login() {}<br><br>  void logout() {}<br><br>  void register() {}<br>}<br>//All methods are related to user authentication, so this class has high cohesion.</pre><h4>Low Cohesion Example</h4><pre>class UserService {<br><br>  void login() {}<br><br>  void printInvoice() {}<br><br>  void calculateSalary() {}<br><br>  void uploadImage() {}<br><br>  void playMusic() {}<br>}<br>// This class handles multiple unrelated responsibilities. It has low cohesion because its methods do not belong together.</pre><h4>4. Types of Cohesion</h4><p>There are different levels of cohesion, from the weakest to the strongest:</p><h4>1. Coincidental Cohesion (Worst)</h4><p>The class contains unrelated responsibilities with no meaningful connection.</p><pre>print()<br>login()<br>calculateAge()<br>playMusic()</pre><h4>2. Logical Cohesion</h4><p>Functions are grouped because they are similar in category, but each function has a different purpose.</p><p>Example:</p><p>A class handling different types of input:</p><pre>keyboardInput()<br>mouseInput()<br>voiceInput()</pre><p>Adding a new input type would require modifying the same class, which can make the design harder to extend.</p><h4>3. Temporal Cohesion</h4><p>Functions are grouped because they happen at the same time.</p><p>Example:</p><pre>initialize()<br>connectDatabase()<br>loadConfig()<br>startLogger()</pre><h3>4. Procedural Cohesion</h3><p>Functions are grouped because they must be executed in a specific order.</p><p>Example:</p><pre>readFile()<br>validate()<br>print()</pre><p>Each function has a different responsibility, but they are connected by the sequence of execution.</p><h4>5. Communicational Cohesion</h4><p>Functions work on the same data.</p><p>Example:</p><pre>readEmployee()<br>updateEmployee()<br>saveEmployee()</pre><p>All operations are related because they operate on Employee data.</p><h4>6. Sequential Cohesion</h4><p>The output of one operation becomes the input of another.</p><p>Example:</p><pre>readData()<br>processData()<br>saveData()</pre><p>The operations are connected through data flow.</p><h4>7. Functional Cohesion (Best)</h4><p>All parts of the class work together to achieve one clear goal.</p><p>Example:</p><pre>class PaymentProcessor {  <br>bool validateCard() {<br>    // Validate card information<br>  }<br>void chargeCard() {<br>    // Deduct money from the card<br>  }<br>  void generateReceipt() {<br>    // Generate payment receipt<br>  }<br>}</pre><p>Every method contributes to one responsibility: processing a payment.</p><blockquote>The goal is not to make every class as small as possible. The goal is to make every class responsible for one meaningful concept.</blockquote><h3>DRY (Don’t Repeat Yourself)</h3><p><strong>DRY is one of the most well-known software design principles. Its main idea is simple:</strong></p><p>Every piece of knowledge or business logic should have a single, clear representation in the codebase.</p><p>In other words, avoid duplicating the same logic in multiple places because duplicated logic becomes harder to maintain.</p><p>For example:</p><pre>double calculateTax(double price) {<br>  return price * 0.14;<br>}<br><br>double calculateDiscountTax(double price) {<br>  return price * 0.14;<br>}</pre><p>Here, the tax calculation logic is duplicated.</p><p>If the tax rate changes in the future, we have to update it in multiple places, which increases the chance of mistakes.</p><p>A better approach:</p><pre>double calculateTax(double price) {<br>  return price * 0.14;<br>}<br><br>double finalPrice(double price) {<br>  return price - 50 + calculateTax(price);<br>}<br>// Now the tax calculation exists in one place, so any future change only needs to happen once.</pre><p>DRY Doesn’t Mean Removing Every Duplicate Line A common mistake is thinking that DRY means:</p><blockquote>If two pieces of code look similar, they must be combined.</blockquote><p>That’s not always true.</p><p>Two functions can have the same implementation today but represent different business concepts.</p><p>Example:</p><pre>bool validateUsername(String text) {<br>  return text.isNotEmpty;<br>}<br><br>bool validateCoupon(String text) {<br>  return text.isNotEmpty;<br>}</pre><p>They look identical, but they represent different rules.</p><p>If we immediately combine them:</p><pre>class Validator {<br>static bool validate(String text) { return text.isNotEmpty; } }</pre><p>we may create unnecessary coupling.</p><p>Later, if username validation changes but coupon validation doesn’t, changing one shared method will affect both.</p><p>The goal of DRY is not to remove all duplication. The goal is to remove meaningful duplication.</p><blockquote>Before applying DRY, ask yourself: “Are these two pieces of code duplicated because they represent the same idea, or are they just similar by coincidence?”</blockquote><h3>KISS (Keep It Simple, Stupid)</h3><p>KISS is a principle that encourages developers to keep their solutions as simple as possible.</p><p>The idea is:</p><blockquote>Don’t add unnecessary complexity. The simplest solution that solves the problem is usually the best one.</blockquote><p>Simple code is easier to understand, maintain, debug, and modify by other developers.</p><p>For example:</p><p>imagine a function that handles many different responsibilities:</p><pre>void processOrder() {<br><br>  // Validate user<br>  // Calculate price<br>  // Apply discount<br>  // Process payment<br>  // Send notification<br>  // Generate invoice<br><br>}</pre><p>Although this function may work, it becomes difficult to understand and modify because it is responsible for too many things.</p><p>A better approach is to split it into smaller functions, where each function has one clear responsibility:</p><pre>void processOrder() {<br>  validateUser();<br>  calculatePrice();<br>  processPayment();<br>  sendNotification();<br>}<br>// Now each part is easier to understand, test, and change.</pre><p><strong>KISS Doesn’t Mean Always Choosing the Shortest Code</strong></p><p>A common misunderstanding is that simple code means fewer lines of code.</p><p>That’s not always true.</p><p>Sometimes adding a small abstraction or creating a separate class makes the code easier to understand, even if it increases the number of lines.</p><p>The goal is not to write the least amount of code.</p><p>The goal is to write the <strong>clearest code with the least unnecessary complexity</strong>.</p><blockquote><em>Good software design is not about making code clever. It is about making code understandable.</em></blockquote><h3>YAGNI (You Aren’t Gonna Need It)</h3><p><strong>YAGNI</strong> means:</p><blockquote><em>Don’t build something until you actually need it.</em></blockquote><p>This principle encourages developers to avoid adding features, abstractions, or code that have no current requirement.</p><p>Adding unnecessary code increases complexity and makes the system harder to understand and maintain.</p><p>For example</p><p>imagine an API login response that currently returns only the user’s name.</p><p>Instead of creating only what is needed:</p><pre>class User {<br>  String name;<br>}</pre><p>A developer might predict future requirements and add extra fields:</p><pre>class User {<br>  String name;<br>  String address;<br>  String phone;<br>}</pre><p>This is unnecessary because these fields are not used yet.</p><p>Adding them can lead to:</p><ul><li>More complexity.</li><li>More code to maintain.</li><li>More assumptions about future requirements.</li></ul><p>A better approach is to add new fields when the application actually needs them.</p><blockquote><em>YAGNI doesn’t mean you should ignore future changes. It means you shouldn’t build features based only on assumptions.</em></blockquote><h3>Law of Demeter (LoD)</h3><p>The <strong>Law of Demeter (LoD)</strong>, also known as the <strong>Principle of Least Knowledge</strong>, is a design principle that aims to reduce coupling between objects.</p><p>Its main idea:</p><blockquote><em>Talk only to your immediate friends.</em></blockquote><p>A class should know as little as possible about the internal structure of other objects.</p><p>Imagine we have:</p><pre>class Customer {<br>  Address address;<br>}</pre><pre>class Address {<br>  String city;<br>}</pre><p>Now we want to get the customer’s city.</p><p>A common approach:</p><pre>print(customer.address.city);</pre><p>The problem is that Customer now knows that:</p><ul><li>It has an Address.</li><li>Address contains a city.</li></ul><p>The Customer class depends on the internal structure of another object.</p><p>The problem becomes worse with longer chains:</p><pre>print(customer.address.country.capital.name);</pre><p>This is called a <strong>Train Wreck</strong>.</p><p>Every additional dot means more knowledge about internal details and more coupling.</p><h3>The Better Approach</h3><p>Instead of exposing the internal structure, let the object provide what we need:</p><pre>class Customer {</pre><pre>  Address address;</pre><pre>  String getCity() {<br>    return address.city;<br>  }<br>}</pre><pre>print(customer.getCity());</pre><p>Now, if the structure of Address changes, only Customer needs to handle that change.</p><h3>General Rule of Law of Demeter</h3><p>A method should communicate only with:</p><ul><li>Methods of the same object (this).</li><li>Methods of objects passed as parameters.</li><li>Methods of objects created inside the method.</li><li>Methods of direct fields of the class.</li></ul><p>Avoid chains like:</p><pre>customer.getAddress().getCountry().getCapital().getName();</pre><p>because the code becomes dependent on many internal details.</p><h3>Law of Demeter (LoD)</h3><p>The <strong>Law of Demeter (LoD)</strong>, also known as the <strong>Principle of Least Knowledge</strong>, is a design principle that aims to reduce coupling between objects.</p><p>Its main idea:</p><blockquote><em>Talk only to your immediate friends.</em></blockquote><p>A class should know as little as possible about the internal structure of other objects.</p><p>Imagine we have:</p><pre>class Customer {<br>  Address address;<br>}<br>class Address {<br>  String city;<br>}</pre><p>Now we want to get the customer’s city.</p><p>A common approach:</p><pre>print(customer.address.city);</pre><p>The problem is that Customer now knows that:</p><ul><li>It has an Address.</li><li>Address contains a city.</li></ul><p>The Customer class depends on the internal structure of another object.</p><p>The problem becomes worse with longer chains:</p><pre>print(customer.address.country.capital.name);</pre><p>This is called a <strong>Train Wreck</strong>.</p><p>Every additional dot means more knowledge about internal details and more coupling.</p><h4>The Better Approach</h4><p>Instead of exposing the internal structure, let the object provide what we need:</p><pre>class Customer<br>{ <br> <br>Address address;<br>  String getCity() {<br>    return address.city;<br>  }<br>}<br>print(customer.getCity());</pre><p>Now, if the structure of Address changes, only Customer needs to handle that change.</p><h4>General Rule of Law of Demeter</h4><p>A method should communicate only with:</p><ul><li>Methods of the same object (this).</li><li>Methods of objects passed as parameters.</li><li>Methods of objects created inside the method.</li><li>Methods of direct fields of the class.</li></ul><p>Avoid chains like:</p><pre>customer.getAddress().getCountry().getCapital().getName();</pre><p>because the code becomes dependent on many internal details.</p><h4>Don’t Overuse the Law of Demeter</h4><p>Like any principle, LoD should not be applied blindly.</p><p>If applied excessively, you may create many unnecessary methods just to access simple data.</p><p>For example:</p><p>Instead of:</p><pre>user.getProfile().getAddress().getCity();</pre><p>You might create:</p><pre>user.getCity();<br>user.getCountry();<br>user.getZipCode();</pre><p>Now the class contains many methods with no real behavior.</p><p>This can lead to <strong>Overengineering</strong> and sometimes a <strong>Middle Man Anti-Pattern</strong>.</p><p>The Law of Demeter is most useful when dealing with:</p><ul><li>Complex business logic.</li><li>Objects with complicated relationships.</li><li>Code where reducing dependencies improves maintainability.</li></ul><p>However, with simple DTOs or models, a short access chain may be completely acceptable:</p><pre>response.user.profile.name;</pre><h3>Composition over Inheritance</h3><p>Inheritance is a powerful feature in object-oriented programming, but using it everywhere can lead to rigid and difficult-to-maintain designs.</p><p>The idea behind <strong>Composition over Inheritance</strong> is:</p><blockquote><em>Prefer composing objects together instead of creating deep inheritance hierarchies.</em></blockquote><p>In simpler words:</p><ul><li><strong>Inheritance</strong> → “is-a” relationship</li><li><strong>Composition</strong> → “has-a” relationship</li></ul><p>A class should have objects that provide behavior instead of inheriting behavior it may not actually need.</p><h4>The Problem with Inheritance</h4><p>Imagine we have a base class:</p><pre>class Vehicle {void move() {<br>    print(&quot;Moving&quot;);<br>  }<br>}<br>class Car extends Vehicle {}</pre><p>This makes sense because:</p><blockquote><em>A Car </em><strong><em>is a</em></strong><em> Vehicle.</em></blockquote><p>The car can naturally inherit the behavior of a vehicle.</p><p>However, inheritance becomes problematic when the relationship is not truly correct.</p><p>Example:</p><pre>class Bird {<br>void fly() {}<br>}<br>class Penguin extends Bird {<br>}</pre><p>A Penguin is a bird, but it cannot fly.</p><p>By inheriting from Bird, the Penguin gets behavior that it should not have.</p><p>This creates a bad design because the child class inherits something it cannot properly use.</p><h4>The Composition Approach</h4><p>Instead of forcing classes to inherit behaviors, we can separate behaviors into independent components.</p><pre>class FlyBehavior {<br>void fly() {<br>    print(&quot;Flying&quot;);<br>  }<br>}<br><br>class SwimBehavior {<br>  void swim() {<br>    print(&quot;Swimming&quot;);<br>  }<br>}<br><br>class WalkBehavior {<br>  void walk() {<br>    print(&quot;Walking&quot;);<br>  }<br>}</pre><p>Now classes can choose the behaviors they actually need.</p><pre>class Bird {<br><br>final FlyBehavior flyBehavior;<br><br>  Bird(this.flyBehavior);<br><br>  void fly() {<br>    flyBehavior.fly();<br>  }<br>}</pre><p>Here, Bird does not inherit from FlyBehavior.</p><p>It <strong>has a</strong> FlyBehavior object and uses it when needed.</p><h4>Why Composition is Often Better?</h4><p>Composition gives us more flexibility:</p><ul><li>We can change behavior without changing the inheritance hierarchy.</li><li>We avoid forcing classes to inherit unnecessary behavior.</li><li>We can reuse behaviors across different classes.</li><li>The code becomes easier to extend.</li></ul><p>A good rule of thumb:</p><blockquote><em>Use inheritance when there is a clear </em><strong><em>is-a</em></strong><em> relationship.<br> Use composition when you want to add or change behaviors.</em></blockquote><h3>Dependency Injection (DI)</h3><p>One of the best ways to reduce coupling is <strong>Dependency Injection (DI)</strong>.</p><p>Before understanding Dependency Injection, let’s first define a <strong>dependency</strong>.</p><p>A dependency is simply any object or service that another class needs in order to do its job.</p><p>For example:</p><pre>class Engine {<br>void start() {<br>    print(&quot;Engine started&quot;);<br>  }<br>}<br>class Car {<br>  final Engine engine;<br>  Car(this.engine);<br>  void drive() {<br>    engine.start();<br>    print(&quot;Car moving&quot;);<br>  }<br>}<br></pre><p>Here, Car depends on Engine. Without an engine, the car cannot drive.</p><p>The problem begins when a class creates its own dependencies:</p><pre>class Car {<br>final Engine engine = Engine();<br>}</pre><p>Although this works, it introduces several design problems:</p><ul><li>Strong coupling.</li><li>Harder testing.</li><li>Harder maintenance.</li><li>Violates the Single Responsibility Principle because the class is responsible for both creating and using the dependency.</li></ul><p>Instead, the dependency can be provided from outside:</p><pre>class Car {<br>final Engine engine;<br>  Car(this.engine);<br>}</pre><p>This is called <strong>Dependency Injection</strong>.</p><p>Instead of creating the dependency, the class simply receives it from another object.</p><p>As a result, the class becomes easier to test, easier to extend, and less tightly coupled.</p><blockquote>Dependency Injection is one of the most common techniques used to achieve loose coupling, which is why many modern software architectures rely on it.</blockquote><blockquote>Dependency Injection has several forms, such as Constructor Injection, Setter Injection, and Method Injection. It is also closely related to concepts like Inversion of Control (IoC) and IoC Containers. These topics deserve a dedicated article and are beyond the scope of this introduction.</blockquote><h3>Conclusion</h3><p>Software design principles are not strict rules that you must follow blindly. They are lessons learned from decades of building, maintaining, and improving software systems.</p><p>Every principle exists because developers encountered a problem — whether it was tightly coupled code, classes with too many responsibilities, duplicated logic, or designs that became difficult to extend. Over time, these principles proved to be effective ways to write software that is easier to understand, maintain, test, and evolve.</p><p>Finally , I hope the article was useful to you and your opinion is very important to me.</p><p><a href="https://www.linkedin.com/in/rwan-hossam-08ba39295">LinkedIn</a></p><p><a href="http://rwanhossam0@gmail.com/">Email</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=571a80f935ef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/easy-flutter/every-technology-has-its-own-architecture-571a80f935ef">Every technology has its own architecture.</a> was originally published in <a href="https://medium.com/easy-flutter">Easy Flutter</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Are Computers Stupid? (And the Secret That Makes Them Seem Smart!)]]></title>
            <link>https://medium.com/@RwanHossam/why-are-computers-stupid-and-the-secret-that-makes-them-seem-smart-10b6582b51bd?source=rss-e6594c14ec85------2</link>
            <guid isPermaLink="false">https://medium.com/p/10b6582b51bd</guid>
            <dc:creator><![CDATA[Rwan Hossam Eldein]]></dc:creator>
            <pubDate>Tue, 21 Jul 2026 18:13:45 GMT</pubDate>
            <atom:updated>2026-07-21T20:07:09.306Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p4NpWT6G5AbxNwPk-Tn4sw.png" /></figure><p><strong>Why Are Computers Stupid? (And the Secret That Makes Them Seem Smart!)</strong></p><h3>INTRODUCTION</h3><p>Imagine you’re looking for a specific person in a room of ten people. You can probably find them within seconds.</p><p>Now imagine searching for one person among one billion people using the exact same approach. Suddenly, what once felt instant becomes painfully slow. The problem isn’t that computers are slow — it’s that the method no longer scales.</p><p>As software systems grew, developers faced challenges far beyond simple searching. Applications started processing millions of users, billions of records, and massive streams of data every second.</p><p>Three fundamental problems quickly emerged:</p><ol><li><strong>Huge Amounts of Data</strong></li></ol><p>Operations that worked perfectly for small datasets became inefficient as data grew.</p><p><strong>2. Limited Resources</strong></p><p>Memory and processing power are finite. Solving a problem isn’t enough — we want to solve it using as little time and memory as possible.</p><p><strong>3. Chaos &amp; Unpredictability</strong></p><p>Data isn’t always sorted, complete, or predictable. Real-world applications constantly deal with changing inputs, unexpected cases, and enormous workloads.</p><p>These challenges raised an important question: <strong>Can we solve the same problem in a smarter way?</strong></p><p>That question led to one of the most important fields in computer science: Algorithms.</p><h3>The Birth of Algorithms</h3><p>People quickly realized that computers weren’t the problem. Computers could perform billions of operations every second without getting tired. The real challenge was <strong>telling them <em>how</em> to solve a problem efficiently</strong>.</p><p>A computer doesn’t think. It doesn’t analyze situations, make intuitive decisions, or discover shortcuts on its own. It simply follows the instructions it’s given — exactly as they are written.</p><p>This raised a new challenge: If computers can only follow instructions, then those instructions must be carefully designed.</p><p>Instead of asking,<strong> “Can the computer solve this?” </strong>We should start asking,</p><p><strong>“What’s the smartest sequence of steps we can give the computer?”</strong></p><p>That sequence of steps became known as an algorithm.</p><p><strong>This is where the concept of an algorithm was born.</strong></p><h4>An algorithm is a finite, well-defined sequence of instructions designed to solve a problem or perform a specific task.</h4><ul><li>Finite → It must eventually stop.</li><li>Well-defined → Every step should be clear and unambiguous.</li><li>Sequence → The order of steps matters.</li><li>Specific Task → Every algorithm has a goal.</li></ul><h3>What Makes an Algorithm “Good”?</h3><p>Now that we know what an algorithm is, an important question naturally comes to mind:</p><p><strong>Does every sequence of steps qualify as an algorithm?</strong></p><p>The answer is <strong>no</strong>.</p><p>Imagine someone tells you:</p><blockquote><em>“Go get me a book.”</em></blockquote><p><strong>Is that an algorithm? Not really.</strong></p><p>The instruction is too vague. Which book? Where should you look? What if you can’t find it? What should you do next?</p><p>Now compare it with these instructions:</p><ol><li>Go to the library.</li><li>Walk to the computer science section.</li><li>Look for a book titled <em>Algorithms</em>.</li><li>If you find it, bring it back.</li><li>Otherwise, report that it wasn’t found.</li><li>Stop.</li></ol><p>This is an algorithm because every step is clearly defined and leads toward a specific goal.</p><p>To be considered a proper algorithm, it should satisfy several important characteristics.</p><h4>1. Finiteness</h4><ul><li>An algorithm must always come to an end.</li><li>It cannot continue forever without stopping.</li></ul><p><strong>Good example: </strong>Repeat until the target is found.</p><p><strong>Bad example: </strong>Repeat forever.</p><h4>2. Definiteness</h4><ul><li>Every instruction must be clear and unambiguous.</li><li>The computer should never have to guess what a step means.</li></ul><p><strong>Bad: </strong><em>Search quickly.</em></p><p><strong>Good: </strong><em>Compare the target with the current element.</em></p><h4>3. Input</h4><ul><li>Most algorithms require one or more inputs.</li><li>These inputs may be numbers, strings, arrays, graphs, or any other type of data that the algorithm processes.</li></ul><h4>4. Output</h4><ul><li>Every algorithm should produce at least one meaningful result.</li></ul><p>For example:</p><ul><li>A sorted array</li><li>A search result</li><li>The largest value</li><li>A shortest path</li></ul><p>Without an output, the algorithm has no measurable purpose.</p><h4>5. Effectiveness</h4><ul><li>Each instruction must be simple enough to be carried out exactly as described.</li></ul><p>An instruction like:<strong>“Find the best answer magically.”</strong></p><p>cannot be executed. But: <strong>“Compare two numbers.” </strong>is a valid, executable step.</p><h4>6. Correctness</h4><ul><li>A good algorithm must produce the correct result for every valid input.</li><li>Speed alone is not enough.</li></ul><p>An algorithm that computes 2 + 2 = 5 is incorrect, no matter how fast it runs.</p><blockquote>Now suppose two algorithms are both correct. How do we decide which one is better?</blockquote><h3>Measuring Algorithm Efficiency (Time &amp; Space Complexity)</h3><p>When computers first became more powerful, it was easy to assume that faster hardware could solve every performance problem.</p><p>For a while, that seemed true. Faster processors and larger memory allowed programs to run more quickly.</p><p>However, as applications began processing millions — and later billions — of pieces of data, computer scientists realized something important:</p><p>A faster computer cannot always compensate for an inefficient algorithm.</p><p>Two programs running on the same machine can produce the same result, yet one may finish in seconds while the other takes hours. The difference isn’t the hardware — it’s the algorithm.</p><p>This led to a fundamental question:</p><p><strong>How do we measure the efficiency of an algorithm?</strong></p><p>To answer that, computer scientists evaluate algorithms using two primary resources:</p><ul><li>Time Complexity — How much time an algorithm requires as the input size grows.</li><li>Space Complexity — How much memory an algorithm consumes as the input size grows.</li></ul><blockquote>A good algorithm isn’t the one that runs fastest on today’s computer. It’s the one that continues to perform well as the problem grows.</blockquote><h3>Understanding Big O Notation</h3><p>Imagine two algorithms solving exactly the same problem. The first takes 1 second to process 100 items. The second also takes 1 second to process the same 100 items. At first glance, they seem equally efficient. But <strong>what happens if the input grows from 100 items to 1,000,000 items?</strong></p><p>Suddenly, one algorithm still performs well, while the other becomes painfully slow.</p><p><strong>This reveals an important truth:</strong></p><blockquote>The real question isn’t how fast an algorithm is today. It’s how well it scales as the input size grows.</blockquote><p><strong>That’s exactly what Big O Notation helps us understand.</strong></p><h4>What is Big O Notation?</h4><p>Big O Notation is a mathematical way of describing how an algorithm’s running time or memory usage grows asymptotically as the size of the input increases.</p><p>Instead of measuring execution time in seconds or milliseconds, Big O focuses on the growth rate of an algorithm.</p><p>This allows us to compare algorithms fairly, regardless of the programming language, hardware, or operating</p><h4>Introduce n</h4><p>Before exploring different Big O complexities, we first need to understand a symbol you’ll see everywhere: n In algorithm analysis, n represents the size of the input.</p><p><strong>For example:</strong></p><ul><li>Searching through 10 names → n = 10</li><li>Searching through 1,000 names → n = 1,000</li><li>Searching through 1,000,000 names → n = 1,000,000</li></ul><p>As n increases, the amount of work an algorithm performs also changes.</p><h4>Big O describes how that work grows.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TgbY-hIuLHfTcO9N4BIDiA.png" /><figcaption><strong>A comparison infographic shows Big O complexities using one consistent search example.</strong></figcaption></figure><h3>Algorithm Design Techniques</h3><p>By now, we understand what an algorithm is, how to evaluate its efficiency, and why choosing the right algorithm matters. But this raises another interesting question:</p><p><strong>Where do algorithms come from?</strong></p><p><strong>Do computer scientists invent a completely new algorithm every time they face a new problem?</strong></p><p><strong>The answer is no.</strong></p><p>Over the years, computer scientists discovered that many seemingly different problems could be solved using the same way of thinking. Instead of creating a brand-new solution for every problem, they developed a set of general problem-solving strategies known as Algorithm Design Techniques.</p><p>You can think of them as blueprints.</p><p>Just as architects use different blueprints to design houses, bridges, and skyscrapers, computer scientists use different algorithm design techniques depending on the nature of the problem they’re trying to solve.</p><p>Each technique follows a different philosophy, and each excels in different situations.</p><p>Let’s explore the four most common techniques.</p><h3>1. Brute Force Technique</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FBISHsmkwUfjAI6S9yljrQ.png" /></figure><h4>The Idea</h4><p>The Brute Force technique is the most straightforward way to solve a problem.</p><p>Instead of trying to be clever or finding shortcuts, it simply checks every possible solution until it finds the correct one.</p><p><strong>In other words: If you’re not sure which solution is correct, try them all.</strong></p><h4>How It Works</h4><p>Instead of eliminating possibilities or making assumptions, Brute Force explores every possible option until the solution is found.</p><p>It sacrifices efficiency for simplicity and reliability.</p><h4>Advantages</h4><ul><li>Extremely simple to understand.</li><li>Easy to implement.</li><li>Often guarantees finding the correct solution.</li></ul><h4>Disadvantages</h4><ul><li>Can be very slow for large inputs.</li><li>Performs unnecessary work by checking every possibility.</li><li>Doesn’t take advantage of patterns or properties in the data.</li></ul><h4>Common Algorithms That Use This Technique</h4><ul><li>Linear Search</li><li>Naive String Matching</li><li>Exhaustive Password Search</li></ul><h4>When Should You Use It?</h4><p>Brute Force is a good choice when:</p><ul><li>The input size is small.</li><li>Simplicity is more important than speed.</li><li>No efficient algorithm is known.</li><li>You need a baseline solution before optimizing it.</li></ul><h4>Key Takeaway</h4><blockquote>- Brute Force doesn’t try to be smart.</blockquote><blockquote>- It succeeds by being <strong>thorough</strong>.</blockquote><blockquote>- If a valid solution exists, Brute Force will eventually find it — but sometimes at the cost of time.</blockquote><p>Brute Force solves problems by checking <strong>everything</strong>. But what if checking everything isn’t necessary? What if we could split one difficult problem into several smaller, easier problems, solve them independently, and then combine the results? That idea leads us to our next design technique: <strong>Divide and Conquer</strong>.</p><h3>2. Divide and Conquer Technique</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WlpsGpMZaJ5UJKtTY1OQRA.png" /></figure><h4>The Idea</h4><p>Imagine you’re given a huge puzzle with thousands of pieces.Would you try to solve the entire puzzle at once? <strong>Probably not.</strong></p><p>Most people naturally break the problem into smaller parts. They might finish the corners first, then the edges, and finally connect the remaining pieces.</p><p>Instead of tackling one overwhelming problem, they solve several smaller and easier ones.</p><p>This is exactly the idea behind <strong>Divide and Conquer</strong>. Rather than solving a large problem directly, we:</p><ol><li><strong>Divide</strong> the problem into smaller subproblems.</li><li><strong>Conquer</strong> each subproblem by solving it independently. Sometimes this is done recursively, meaning the same process is repeated until the problems become simple enough to solve directly.</li><li><strong>Combine</strong> the smaller solutions to produce the final answer.</li></ol><p>In other words:</p><blockquote><strong><em>If a problem is too big, break it into smaller pieces and solve each piece separately.</em></strong></blockquote><h4>Advantages</h4><ul><li>Much faster than Brute Force for many problems.</li><li>Works extremely well with recursive algorithms.</li><li>Makes large and complex problems easier to manage.</li></ul><h4>Disadvantages</h4><ul><li>Not every problem can be divided effectively.</li><li>Combining the results may introduce extra work.</li><li>Recursive solutions may consume additional memory due to the call stack.</li></ul><h4>Common Algorithms That Use This Technique</h4><ul><li>Binary Search</li><li>Merge Sort</li><li>Quick Sort</li></ul><h4>When Should You Use It?</h4><p>Divide and Conquer is a great choice when:</p><ul><li>The problem can naturally be split into independent smaller parts.</li><li>Solving smaller problems is easier than solving one large problem.</li><li>The partial solutions can be combined efficiently.</li></ul><h4>Key Takeaway</h4><blockquote>Divide and Conquer doesn’t try every possibility.</blockquote><blockquote>Instead, it <strong>reduces the size of the problem step by step</strong>, making large problems much easier and faster to solve.</blockquote><p>Divide and Conquer makes smart decisions by breaking problems into smaller pieces. But sometimes, we don’t even need to explore every smaller problem. What if we simply chose the best option available at each step, hoping those choices would lead to the best overall solution? That idea introduces our next design technique: <strong>Greedy Algorithms</strong></p><h3><strong>3. </strong>Greedy Technique</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7d0pV-FGqGbb_qb_prd4sw.png" /></figure><h3>The Idea</h3><p>Imagine you’re climbing a mountain. At every step, you simply choose the path that seems to take you <strong>closer to the summit</strong>. You don’t stop to analyze every possible route, and you don’t backtrack to compare different options. You make the best decision <strong>at the current moment</strong> and continue moving forward. This is exactly how the <strong>Greedy Technique</strong> works.</p><p>Instead of exploring every possible solution, a greedy algorithm makes the <strong>best local choice</strong> at each step, hoping that these choices will eventually lead to the best overall solution.</p><p><strong>In other words:</strong></p><blockquote><strong><em>Make the best decision now and trust that it will lead to the best final result.</em></strong></blockquote><blockquote>note: Greedy algorithms don’t always guarantee the optimal solution</blockquote><h4>How It Works</h4><p>A Greedy algorithm repeatedly follows the same pattern:</p><ol><li>Consider the available choices.</li><li>Select the option that looks best at the current step.</li><li>Never reconsider that decision.</li><li>Continue until the problem is solved.</li></ol><p>Unlike Backtracking or Dynamic Programming, a Greedy algorithm <strong>doesn’t go back</strong> to change earlier decisions.</p><h4>Advantages</h4><ul><li>Usually very fast.</li><li>Simple to implement.</li><li>Requires little memory.</li><li>Works perfectly for many optimization problems.</li></ul><h4>Disadvantages</h4><ul><li>Choosing the best local option doesn’t always produce the best global solution.</li><li>Only works correctly for problems that satisfy specific mathematical properties.</li></ul><h4>Common Algorithms That Use This Technique</h4><ul><li>Dijkstra’s Shortest Path Algorithm</li><li>Prim’s Minimum Spanning Tree</li><li>Kruskal’s Minimum Spanning Tree</li><li>Huffman Coding</li><li>Activity Selection</li></ul><h4>When Should You Use It?</h4><p>A Greedy algorithm is a good choice when:</p><ul><li>The problem has the <strong>Greedy Choice Property</strong> (a locally optimal choice leads to a globally optimal solution).</li><li>A fast solution is more important than exploring every possibility.</li><li>The problem can be solved through a sequence of independent decisions.</li></ul><h4>Key Takeaway</h4><blockquote>Greedy algorithms are <strong>fast because they don’t look back</strong>. They make the best decision available at each step and move forward. Sometimes that leads to the optimal solution. Sometimes it doesn’t. Knowing when Greedy works is just as important as knowing how it works.</blockquote><p>Greedy algorithms avoid looking back. But what if the best decision can’t be determined by looking only at the current step? Some problems contain overlapping subproblems, where the same calculations are repeated again and again. Instead of recomputing those results, what if we could remember them and reuse them? That idea leads us to one of the most powerful design techniques in computer science:<strong> Dynamic Programming</strong></p><h3>4. Dynamic Programming</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MvOKA7DKu2CaP6MsUbtf2w.png" /></figure><h3>The Idea</h3><p>Imagine you’re solving a difficult math problem. Along the way, you calculate an important value. A few minutes later, you realize you need exactly the same calculation again. Would you solve it from scratch?Probably not.</p><p>Instead, you’d simply look at your previous answer and reuse it. This simple idea is the foundation of <strong>Dynamic Programming</strong>. Rather than solving the same subproblem over and over again, a Dynamic Programming algorithm <strong>stores previously computed results and reuses them whenever they are needed</strong>.</p><blockquote><strong><em>Don’t solve the same problem twice. Solve it once, remember the answer, and reuse it.</em></strong></blockquote><h4>How It Works</h4><p>Dynamic Programming is effective when a problem has two important characteristics:</p><h4>1. Overlapping Subproblems</h4><p>The same smaller problems are solved repeatedly. Instead of recomputing them every time, the algorithm stores their results.</p><h4>2. Optimal Substructure</h4><p>The optimal solution to the larger problem can be built from the optimal solutions of its smaller subproblems.</p><ul><li>When both properties exist, Dynamic Programming can dramatically reduce the amount of work performed.</li></ul><h4>Two Common Approaches</h4><p>Dynamic Programming can be implemented in two main ways:</p><h4>Memoization (Top-Down)</h4><ul><li>Start with the original problem and solve smaller subproblems only when needed.</li><li>Each result is stored after it is computed, so it never has to be calculated again.</li></ul><h4>Tabulation (Bottom-Up)</h4><ul><li>Start with the smallest subproblems first.</li><li>Store their solutions in a table, then use those values to build the final answer step by step.</li></ul><p>Both approaches avoid repeated computations — the difference lies only in the order in which the solutions are generated.</p><h4>Advantages</h4><ul><li>Eliminates repeated calculations.</li><li>Can dramatically improve performance.</li><li>Ideal for optimization problems with overlapping subproblems.</li></ul><h4>Disadvantages</h4><ul><li>Requires additional memory to store intermediate results.</li><li>Identifying whether a problem is suitable for Dynamic Programming is not always straightforward.</li></ul><h4>Common Algorithms That Use This Technique</h4><ul><li>Fibonacci Sequence</li><li>0/1 Knapsack Problem</li><li>Coin Change</li><li>Longest Common Subsequence (LCS)</li><li>Edit Distance</li></ul><h4>When Should You Use It?</h4><p>Dynamic Programming is a great choice when:</p><ul><li>The problem contains <strong>overlapping subproblems</strong>.</li><li>The final solution can be built from smaller optimal solutions.</li><li>Avoiding repeated computations significantly improves performance.</li></ul><h4>Key Takeaway</h4><p>Dynamic Programming isn’t about solving problems differently.</p><p>It’s about <strong>solving them more efficiently</strong>.</p><p>Instead of repeating the same work, it remembers previous results and reuses them whenever possible.</p><p>By trading a little extra memory for a significant reduction in computation, Dynamic Programming transforms many expensive recursive solutions into highly efficient algorithms.</p><h3>5. Backtracking</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jSjb_4tHMzX_KGSUN0bDSA.png" /></figure><h4>The Idea</h4><p>Imagine you’re solving a maze. You choose a path and keep moving forward. Suddenly, you reach a dead end. Instead of starting over from the beginning, you simply go back to the last decision point and try a different path. This is exactly how <strong>Backtracking</strong> works.</p><p>It builds a solution step by step. Whenever it realizes that the current path cannot lead to a valid solution, it <strong>backtracks</strong> to the previous decision and explores another possibility.</p><blockquote><strong><em>Try a solution. If it fails, go back and try a different one.</em></strong></blockquote><h4>How It Works</h4><p>A Backtracking algorithm follows these steps:</p><ul><li>Make a choice.</li><li>Continue building the solution.</li><li>If the current path becomes invalid, undo the last choice.</li><li>Try the next possible option.</li><li>Repeat until a valid solution is found or all possibilities have been explored.</li></ul><h4>Advantages</h4><ul><li>Guarantees finding a valid solution if one exists.</li><li>Avoids exploring impossible paths to completion.</li><li>Well suited for constraint satisfaction problems.</li></ul><h4>Disadvantages</h4><ul><li>Can still be slow for very large search spaces.</li><li>Worst-case time complexity is often exponential.</li></ul><h4>Common Algorithms That Use This Technique</h4><ul><li>Sudoku Solver</li><li>N-Queens Problem</li><li>Maze Solving</li><li>Permutations and Combinations</li></ul><h4>Key Takeaway</h4><blockquote>Backtracking explores one solution at a time.</blockquote><blockquote>Whenever it discovers that the current path cannot possibly lead to a valid answer, it steps back and tries another path instead.</blockquote><p>Backtracking stops exploring a path when it knows that the path is invalid. But what if a path is valid, yet it can never become the best solution? That question leads us to another optimization technique:<strong>Branch and Bound</strong></p><h3>6. Branch and Bound</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eFD3NPxZme0aZOPS2vk5yQ.png" /></figure><h4>The Idea</h4><p>Imagine you’re planning a road trip and your goal is to find the shortest possible route. As you explore different routes, you estimate the remaining distance. If you discover that a route has already become longer than the best one you’ve found so far, there’s no reason to continue exploring it. Instead, you immediately discard that route and move on to another. This is the main idea behind Branch and Bound. Rather than exploring every possible solution, it eliminates branches that cannot possibly produce a better result than the current best solution.</p><blockquote>If a solution can no longer become the best one, stop exploring it.</blockquote><h4>How It Works</h4><ul><li>A Branch and Bound algorithm repeatedly:</li><li>Explores a possible solution.</li><li>Estimates its best achievable outcome.</li><li>Compares that estimate with the current best solution.</li><li>Discards the branch if it can no longer outperform the current best.</li><li>Continues exploring only promising branches.</li></ul><h4>Advantages</h4><ul><li>Explores significantly fewer possibilities than exhaustive search.</li><li>Guarantees the optimal solution for many optimization problems.</li><li>Can dramatically reduce computation time.</li></ul><h4>Disadvantages</h4><ul><li>More difficult to design and implement.</li><li>Performance depends heavily on how accurately the bounds are estimated.</li></ul><h4>Common Algorithms That Use This Technique</h4><ul><li>Traveling Salesman Problem (TSP)</li><li>0/1 Knapsack Problem (Branch and Bound approach)</li><li>Job Scheduling</li><li>Integer Programming</li></ul><h4>Key Takeaway</h4><blockquote>Branch and Bound doesn’t stop because a solution is wrong.</blockquote><blockquote>It stops because the solution can never become the best.</blockquote><blockquote>By eliminating unpromising branches early, it focuses computational effort only on the most promising candidates.</blockquote><p>At this point, we’ve explored six of the most common algorithm design techniques.</p><p>Each technique approaches problems from a different perspective:</p><ul><li><strong>Brute Force</strong> tries every possibility.</li><li><strong>Divide and Conquer</strong> breaks large problems into smaller independent ones.</li><li><strong>Greedy</strong> makes the best decision at each step.</li><li><strong>Dynamic Programming</strong> stores and reuses previous results.</li><li><strong>Backtracking</strong> explores solutions by undoing wrong decisions.</li><li><strong>Branch and Bound</strong> eliminates solutions that cannot outperform the current best.</li></ul><p>No single technique is universally better than the others. The right choice depends on the nature of the problem you’re trying to solve.</p><p>These techniques are not algorithms themselves — they are <strong>ways of thinking</strong>. Many of the algorithms we use every day are simply applications of one or more of these design strategies.</p><p>Now that we understand the ideas behind these techniques, it’s time to see them in action by exploring some of the most famous algorithms in computer science.</p><h3>Categories of Algorithms</h3><p>Not all algorithms solve the same kind of problems. Some are designed to <strong>search</strong> for information, others <strong>sort</strong> data, while some work with <strong>graphs</strong>, <strong>strings</strong>, or even <strong>artificial intelligence</strong>. To make studying algorithms easier, computer scientists group them into categories based on the type of problems they solve. Let’s take a quick look at some of the most common categories.</p><h4>1. Searching Algorithms</h4><p>Searching algorithms are used to find a specific element within a collection of data. Whether you’re looking for a contact on your phone, a product in an online store, or a file on your computer, a searching algorithm is working behind the scenes.</p><p><strong>Common Examples</strong></p><ul><li>Linear Search</li><li>Binary Search</li><li>Jump Search</li><li>Interpolation Search</li><li>Exponential Search</li></ul><h4>2. Sorting Algorithms</h4><p>Sorting algorithms arrange data in a specific order, such as ascending or descending. Sorting makes many other operations especially searching much faster and more efficient.</p><p><strong>Common Examples</strong></p><ul><li>Bubble Sort</li><li>Selection Sort</li><li>Insertion Sort</li><li>Merge Sort</li><li>Quick Sort</li><li>Heap Sort</li><li>Counting Sort</li><li>Radix Sort</li></ul><h4>3. Graph Algorithms</h4><p>Graph algorithms work with networks of connected nodes.</p><p>They are widely used in maps, navigation systems, social networks, computer networks, and routing applications.</p><p><strong>Common Examples</strong></p><ul><li>Breadth-First Search (BFS)</li><li>Depth-First Search (DFS)</li><li>Dijkstra’s Algorithm</li><li>Bellman-Ford Algorithm</li><li>Prim’s Algorithm</li><li>Kruskal’s Algorithm</li><li>Floyd-Warshall Algorithm</li></ul><h4>4. String Algorithms</h4><p>String algorithms process and analyze textual data.</p><p>They are commonly used in search engines, text editors, DNA analysis, and plagiarism detection.</p><p><strong>Common Examples</strong></p><ul><li>Knuth-Morris-Pratt (KMP)</li><li>Rabin-Karp</li><li>Boyer-Moore</li><li>Z Algorithm</li><li>Trie-based Searching</li></ul><blockquote>These categories represent only a small portion of the vast world of algorithms.</blockquote><blockquote>As you continue your journey in computer science, you’ll discover many more specialized algorithms designed for optimization, machine learning, cryptography, computational geometry, and countless other fields.</blockquote><blockquote>The important thing isn’t memorizing every algorithm it’s understanding which category a problem belongs to and why a particular algorithm is the right tool for solving it.</blockquote><h3>Where Are Algorithms Used?</h3><p>Algorithms are everywhere.</p><p>Every time you use a smartphone, browse the internet, or watch a video online, algorithms are working behind the scenes.</p><p>Some common applications include:</p><ul><li><strong>Search Engines</strong> — Finding the most relevant web pages.</li><li><strong>Navigation Apps</strong> — Calculating the fastest route.</li><li><strong>Social Media</strong> — Recommending posts, videos, and friends.</li><li><strong>E-commerce Platforms</strong> — Suggesting products based on your interests.</li><li><strong>Banking Systems</strong> — Detecting fraudulent transactions.</li><li><strong>Artificial Intelligence</strong> — Training models and making predictions.</li><li><strong>Compression Software</strong> — Reducing file sizes efficiently.</li><li><strong>Cybersecurity</strong> — Encrypting and protecting sensitive data.</li></ul><p>Although users rarely notice them, algorithms play a central role in nearly every modern software system.</p><h3>Choosing the Right Algorithm</h3><p>One of the biggest misconceptions is that there is always a single “best” algorithm. In reality, the best algorithm depends on the problem you’re trying to solve. An algorithm that performs exceptionally well in one situation may perform poorly in another. Choosing the right algorithm is often just as important as implementing it correctly.</p><h3>What Should You Consider?</h3><p>Before selecting an algorithm, ask yourself a few important questions.</p><h4>1. What type of problem am I solving?</h4><p>Different problems require different categories of algorithms.</p><ul><li>Need to find an element? → Searching Algorithms.</li><li>Need to organize data? → Sorting Algorithms.</li><li>Need the shortest route? → Graph Algorithms.</li><li>Need to process text? → String Algorithms.</li></ul><p>The nature of the problem is always the first clue.</p><h4>2. How large is the input?</h4><p>Some algorithms work well with small datasets but become impractical as the data grows.</p><p>For example, an algorithm with <strong>O(n²)</strong> complexity may perform well for hundreds of elements but struggle with millions.</p><h4>3. Is the data already sorted?</h4><p>This single question can completely change your choice.</p><p>For example:</p><ul><li>Sorted data → Binary Search.</li><li>Unsorted data → Linear Search.</li></ul><p>The structure of the input often determines the most efficient solution.</p><h4>4. Is speed or memory more important?</h4><p>Sometimes you need the fastest possible execution.</p><p>Other times, memory is limited, and using less space becomes the priority.</p><p>Many algorithms improve speed by consuming additional memory, while others save memory at the cost of extra computation.</p><p>This is known as the <strong>time-space tradeoff</strong>.</p><h4>5. Do I need the optimal solution?</h4><p>Some algorithms always produce the best possible answer.</p><p>Others provide a solution that is “good enough” but much faster.</p><p>Understanding whether your problem requires an exact or approximate solution is an important part of algorithm selection.</p><h3>The Most Important Rule</h3><blockquote>There is no universally best algorithm. There is only the best algorithm for a particular problem and its constraints.</blockquote><p>That’s why experienced programmers spend time analyzing the problem before writing code.</p><h3>Final Thought</h3><p>Learning algorithms isn’t about memorizing dozens of solutions. It’s about recognizing patterns, understanding the problem, and selecting the strategy that fits best. The more problems you solve, the more natural this decision becomes.</p><p>Finally , I hope the article was useful to you and your opinion is very important to me.</p><p><a href="https://www.linkedin.com/in/rwan-hossam-08ba39295">LinkedIn</a></p><p><a href="http://rwanhossam0@gmail.com/">Email</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10b6582b51bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is Data Structure Really Important in Our Code?]]></title>
            <link>https://medium.com/@RwanHossam/is-data-structure-really-important-in-our-code-3e51c2b861ad?source=rss-e6594c14ec85------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e51c2b861ad</guid>
            <dc:creator><![CDATA[Rwan Hossam Eldein]]></dc:creator>
            <pubDate>Thu, 02 Jul 2026 10:44:50 GMT</pubDate>
            <atom:updated>2026-07-02T10:44:50.085Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i-tNw1WI7z9iHSha2RbUTQ.png" /></figure><h3>1. Introduction</h3><p>We all know that Data Structures is that super important course we’re all told to take. We hear it organizes our code and makes things efficient. But honestly, before I started diving into this topic to write this article, I had so many doubts. I didn’t truly appreciate its value.</p><p>What I eventually realized was that I just needed to organize the messy thoughts in my own head first to actually see how it works. And funny enough… that is exactly what Data Structures do for our code.</p><p>“So, in this article, let’s untangle the mess together and look at where these structures are actually hiding in our everyday code.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eCMeivoOfqUdhh8ijREbdw.png" /></figure><h4>What is a Data Structure?</h4><p>Data Structure is a way of organizing and storing data in memory so that we can access, modify, and manage it efficiently.</p><blockquote>The main goal of a Data Structure is NOT to save memory.</blockquote><blockquote>Its primary goal is to organize data so that operations like Access, Search, Insert, Delete, and Update can be performed efficiently.</blockquote><blockquote>Some Data Structures use more memory in exchange for faster performance, while others save memory but may be slower.</blockquote><h4>Why code works fine with small data but crashes with big data?</h4><p>Think of your brain: remembering 5 simple tasks is effortless. Remembering 100 takes some focus. But trying to hold 10,000 distinct pieces of information all at once without a proper system? Your brain will just freeze.</p><p>Computers work exactly the same way.</p><p>When your dataset is small, almost any code works perfectly. Your application runs fast, and everything seems fine. But the real test begins when your code meets Big Data. If you choose the wrong data structure or handle data inefficiently, your program won’t just slow down — it will crash.</p><p>Here are the most common “screams” you will hear from the computer’s memory when your code fails to scale:</p><ul><li>Memory Limit Exceeded (MLE)</li><li>Segmentation Fault</li><li>Stack Overflow</li><li>Recursion Depth Exceeded</li></ul><h3>2. The Language of Efficiency: Big O Notation</h3><p>Imagine you wrote a simple program to find a student’s name in a list of 10 students. It runs instantly. But when you test the exact same code with a list of 1,000,000 students, the program drags and slows down.</p><p>Naturally, developers started asking: Why is it slower if it’s the exact same code?</p><p>At first, a common misconception appeared: “Let’s measure the code’s speed in seconds” But this triggered a much bigger problem. If you run the code on a super-fast gaming PC, it takes 0.01 seconds. If you run it on an old, weak laptop, it takes 5 seconds. This meant that actual clock time wasn’t a fair measure of the code’s efficiency , it was just a measure of how expensive your computer is!</p><p>So, is the computer hardware the main issue?</p><p>To test this, developers took two different programs and ran them on the exact same computer:</p><p>Program 1: Had a single loop going through an array.</p><p>Program 2: Had two nested loops (a loop inside a loop).</p><p>The performance difference was massive! Program 2 was drastically slower, even though the hardware didn’t change.</p><p>The Shift in Thinking: Enter the “Growth Rate” This is where computer scientists realized the real question isn’t: “How many seconds does this program take?” The real question is: “How does the execution time grow as the data size increases?”</p><p>This concept is called the Growth Rate. Instead of counting seconds, we started counting the number of operations the CPU has to perform.</p><p>Preparing for the Absolute Worst: The Worst Case Scenario To be safe, developers always calculate efficiency based on the Worst Case Scenario — the absolute maximum effort the program will ever have to make.</p><p>Let’s look at your code:</p><pre>String[] students = {&quot;Ahmed&quot;, &quot;Sara&quot;, &quot;John&quot;, ...}; // Size = n<br>String target = &quot;John&quot;;<br><br>for(int i = 0; i &lt; n; i++) {<br>    if(students[i].equals(target)) {<br>        System.out.println(&quot;Found!&quot;);<br>        break;<br>    }<br>}</pre><ul><li>If “Ahmed” (the very first item) is the one you’re looking for, the loop runs exactly 1 time. That’s the Best Case.</li><li>If “Sara” (in the middle) in/2 operations. Average Case.</li><li>But what if “John” is the very last student in a list of 1,000,000? Or worse, what if “John” isn’t in the list at all? Your loop will have to check every single student, running exactly <strong>$n$ times</strong>.</li></ul><blockquote>That maximum effort — where the number of operations grows in a direct, 1-to-1 relationship with the data size (n) is what we call <strong>Worst Case Complexity</strong>, and we write it as: <strong>O(n)</strong></blockquote><h4>The Two Dimensions of Efficiency: Time vs. Space</h4><p>Now that we know we should measure the <strong>Growth Rate</strong> instead of clock seconds, computer scientists split this growth into two distinct categories:</p><h4>1. Time Complexity (Code effort)</h4><p>It is <strong>not</strong> about how many minutes the code takes. It is about <strong>how the number of operations grows</strong> as the input data (n) grows.</p><ul><li><em>The Question it asks:</em> “If I give this code 10 times more data, will it do 10 times more work O(n), or 100 times more work O(n²)?”</li></ul><h4>2. Space Complexity (Memory)</h4><p>It is about <strong>how much extra memory (RAM) your code allocates</strong> as the input data (n) grows.</p><ul><li><em>The Question it asks:</em> “If I process a larger dataset, does my program need to create a whole new copy of that data in memory, or can it do the job using the same amount of memory it started with?”</li></ul><blockquote>Imagine you are a chef preparing a meal:</blockquote><blockquote>Time Complexity is how many steps you have to take to finish the recipe. If you double the guests, do you have to chop double the vegetables?</blockquote><blockquote>Space Complexity is how many pots and pans you clutter your kitchen with. Do you need a new pan for every single guest, or can you cook everything in one big pot?</blockquote><h3>3. Data Structures Categories</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*77BajGgAP9LHKOS7GOUI-g.png" /></figure><p>Before we dive into the code, we need to understand how computers view data. Data structures aren’t just one big pile; they are categorized based on how they are built and how they occupy memory.</p><p>Here is the grand hierarchy:</p><h4>3.1 Primitive Data Structures (The Building Blocks)</h4><p>These are the most basic, fundamental data types predefined by the programming language. They hold a single, simple value and operate directly at the machine level.</p><ul><li>int: For integers (whole numbers like 5, 100).</li><li>float / double: For fractional numbers (like 3.14, 99.9).</li><li>char: For single characters (like ‘A’, ‘z’).</li><li>boolean: For true/false values.</li></ul><h4>3.2 Non-Primitive Data Structures (The Engineered Structures)</h4><p>These are more complex structures. They don’t just hold one value; they <strong>group multiple values together</strong> and organize them in a specific way.</p><p>Non-primitive structures are divided into two main branches:</p><h4>3.2.1 Linear Data Structures (Sequential)</h4><p>In these structures, data elements are arranged sequentially or linearly. Every element is attached to its previous and next adjacent element in a straight line.</p><p>✅ The data is arranged in a sequence.</p><p>✅ There is a beginning and an end.</p><p>✅ The elements can be iterated over one by one.</p><p>✅ Each element is connected to the next in some way.</p><h4>Examples</h4><h4><strong>1-Array</strong></h4><p>It is a collection of elements of the same data type stored in contiguous memory locations.</p><pre>[10][20][30][40][50]</pre><p>When you create an array of 5 integers, the computer reserves 5 boxes right next to each other in the RAM.</p><p><strong>Types of Arrays</strong></p><p>Arrays aren’t all the same. They are classified based on two things: Size and Dimensions.</p><h4><strong>A. Based on Size (Static vs. Dynamic)</strong></h4><ol><li><strong>Static Arrays</strong></li></ol><ul><li>The Concept: You must define the size of the array when you create it, and it can never change. If you create an array of size 5, you can never add a 6th item.</li><li><strong>Pros:</strong> Super fast and uses memory efficiently.</li><li><strong>Cons:</strong> Inflexible. If you don’t use all the space, memory is wasted. If you need more space, you can’t expand.</li></ul><pre>public class Main {<br>    public static void main(String[] args) {<br><br>        String[] students = new String[5];<br><br>        students[0] = &quot;Ahmed&quot;;<br>        students[1] = &quot;Menna&quot;;<br>        students[2] = &quot;Ali&quot;;<br>        students[3] = &quot;Sara&quot;;<br>        students[4] = &quot;Mona&quot;;<br><br>        for (int i = 0; i &lt; students.length; i++) {<br>            System.out.println(students[i]);<br>        }<br>    }<br>}</pre><p><strong>2. Dynamic Arrays (Vectors / Lists)</strong></p><ul><li><strong>The Concept:</strong> An array that <strong>grows and shrinks automatically</strong> as you add or remove items.</li><li><strong>How it works under the hood (The Secret):</strong> When a dynamic array gets full, the computer secretly creates a <em>new, bigger array</em> (usually double the size), copies all old elements into it, and deletes the old small array!</li></ul><pre>import java.util.ArrayList;<br><br>public class Main {<br>    public static void main(String[] args) {<br><br>        ArrayList&lt;String&gt; students = new ArrayList&lt;&gt;();<br>        students.add(&quot;Mona&quot;);<br>        students.add(&quot;Ahmed&quot;);<br>        students.add(&quot;Menna&quot;);<br>        students.add(&quot;Ali&quot;);<br>        students.add(&quot;Sara&quot;);<br>      <br><br>        System.out.println(students);<br>    }<br>}</pre><h4>B. Based on Dimensions</h4><ul><li>One-Dimensional Array (1D Array) : Data is stored in a single row. Like a simple shopping list.</li></ul><pre>int[] scores = {90, 85, 77};</pre><ul><li><strong>Multi-Dimensional Array (2D, 3D… Arrays) :</strong></li></ul><p><strong>2D Array (The Matrix):</strong> Data is arranged in rows and columns.</p><pre>int[][] matrix = new int[3][3];</pre><p><strong>A 3D array: </strong>is an array of 2D arrays. It stores data in layers, where each layer contains rows and columns.</p><pre>int[][][] numbers = new int[2][3][4];</pre><h4>2- Linked Lists</h4><p>If an Array is like a row of locked mailboxes next to each other, a linked list is like a Treasure Hunt.</p><p>You start with a clue that leads you to the first location. At that location, you find the treasure <em>and</em> a note telling you where the next location is. The locations are scattered all over the place, but they are all connected by these notes.</p><p>In computer science, a Linked List is a linear data structure where elements are <strong>not stored in contiguous memory locations</strong>. Instead, they are scattered in memory and linked together using <strong>Pointers</strong> (addresses).</p><h4><strong>Anatomy of a Linked List:</strong></h4><p>Every element in a Linked List is called a Node. Each Node consists of two parts:</p><p>1- Data: The actual value you want to store (like an integer or string).</p><p>2-Next (Pointer): A reference or address that points to the next Node in the chain.</p><ul><li>Head: The very first Node in the list (your entry point).</li><li>Tail: The very last Node, and its Next pointer points to Null (signaling the end of the chain).</li></ul><h4>Types of Linked Lists</h4><p><strong>A. Singly Linked List :</strong> The simplest type. Each node points only to the next node. You can only move forward, never backward.</p><ul><li>Analogy: A one-way street.</li></ul><pre>class Node {<br>    int data;<br>    Node next;<br><br>    Node(int data) {<br>        this.data = data;<br>        this.next = null;<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br><br>        Node first = new Node(10);<br>        Node second = new Node(20);<br>        Node third = new Node(30);<br><br>        first.next = second;<br>        second.next = third;<br><br>        Node current = first;<br><br>        while (current != null) {<br>            System.out.println(current.data);<br>            current = current.next;<br>        }<br>    }<br>}<br>// 10 → 20 → 30 → null</pre><p><strong>B. Doubly Linked List :</strong>Each node has two pointers: one pointing to the next node, and another pointing to the previous node.</p><ul><li>Analogy: A two-way highway. It takes more memory (for the extra pointer) but allows you to navigate backward and forward easily.</li></ul><pre>class Node {<br>    int data;<br>    Node prev;<br>    Node next;<br><br>    Node(int data) {<br>        this.data = data;<br>        this.prev = null;<br>        this.next = null;<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br><br>        Node first = new Node(10);<br>        Node second = new Node(20);<br>        Node third = new Node(30);<br><br>        // Connect forward<br>        first.next = second;<br>        second.next = third;<br><br>        // Connect backward<br>        second.prev = first;<br>        third.prev = second;<br><br>        // Traverse forward<br>        System.out.println(&quot;Forward:&quot;);<br><br>        Node current = first;<br>        while (current != null) {<br>            System.out.println(current.data);<br>            current = current.next;<br>        }<br><br>        // Traverse backward<br>        System.out.println(&quot;Backward:&quot;);<br><br>        current = third;<br>        while (current != null) {<br>            System.out.println(current.data);<br>            current = current.prev;<br>        }<br>    }<br>}<br>//null ← 10 ⇄ 20 ⇄ 30 → null</pre><p><strong>C. Circular Linked List :</strong>The last node (Tail) doesn’t point to Null; instead, it points back to the first node (Head), creating a closed loop.</p><ul><li><em>Analogy:</em> A multiplayer board game where the turns go in a continuous circle.</li></ul><pre>class Node {<br>    int data;<br>    Node next;<br><br>    Node(int data) {<br>        this.data = data;<br>        this.next = null;<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br><br>        Node first = new Node(10);<br>        Node second = new Node(20);<br>        Node third = new Node(30);<br><br>        first.next = second;<br>        second.next = third;<br>        third.next = first; // Makes the list circular<br><br>        Node current = first;<br><br>        for (int i = 0; i &lt; 6; i++) {<br>            System.out.println(current.data);<br>            current = current.next;<br>        }<br>    }<br>}<br><br></pre><pre>      +----+<br>      |    |<br>      ↓    |<br>10 → 20 → 30<br>↑           |<br>└───────────┘</pre><h4>3- The Stack: Last In, First Out (LIFO)</h4><p>Imagine a stack of dinner plates in a cafeteria.</p><ul><li>When a clean plate is washed, where is it placed? On the very top of the stack.</li><li>When a customer wants a plate, which one do they take? The top one (which was the last one added).</li></ul><p>If you try to pull a plate from the bottom, the whole stack will crash!</p><p>In computer science, a Stack is a linear data structure that follows a strict rule for adding and removing elements: LIFO (Last In, First Out). The last element you put into the stack is the first one that comes out.</p><pre>import java.util.Stack;<br><br>public class Main {<br>    public static void main(String[] args) {<br><br>        Stack&lt;String&gt; books = new Stack&lt;&gt;();<br><br>        books.push(&quot;Book A&quot;);<br>        books.push(&quot;Book B&quot;);<br>        books.push(&quot;Book C&quot;);<br><br>        System.out.println(books);<br><br>        books.pop();<br><br>        System.out.println(books);<br>    }<br>}</pre><h4>Core Operations (The only things a Stack can do):</h4><p>Unlike Arrays, you cannot access elements in the middle of a Stack. You only interact with the Top:</p><ul><li>push(): Adds an element to the top of the stack.</li><li>pop(): Removes (and returns) the element from the top of the stack.</li><li>peek() or top(): Looks at the top element without removing it.</li><li>isEmpty(): Checks if the stack is completely empty.</li></ul><h4>4-The Queue: First In, First Out (FIFO)</h4><p>As applications grew more complex, computer scientists realized that a simple straight line wasn’t enough for every situation. This led to the creation of four distinct types of Queues:</p><p><strong>A. Simple Queue (Linear Queue)</strong></p><p>This is the standard queue we discussed. Elements are inserted at the back (<strong>Rear</strong>) and removed from the front (<strong>Front</strong>) in a strict straight line.</p><ul><li><strong>The Major Flaw:</strong> Once the queue is full and you remove elements from the front, those memory slots become permanently empty and useless. The pointers only move forward, which causes a massive waste of memory.</li></ul><pre>import java.util.LinkedList;<br>import java.util.Queue;<br><br>public class Main {<br>    public static void main(String[] args) {<br><br>        Queue&lt;String&gt; customers = new LinkedList&lt;&gt;();<br><br>        customers.offer(&quot;Ahmed&quot;);<br>        customers.offer(&quot;Menna&quot;);<br>        customers.offer(&quot;Ali&quot;);<br><br>        System.out.println(customers);<br><br>        customers.poll();<br><br>        System.out.println(customers);<br>    }<br>}</pre><p><strong>B. Circular Queue (The Smart Loop)</strong></p><p>This type was invented to solve the memory wasting problem of the Simple Queue.</p><ul><li><strong>How it works:</strong> The last position of the queue is connected straight back to the first position, forming a circle.</li><li><strong>The Benefit:</strong> When you remove elements from the front, the vacated slots are recycled. Once the Rear pointer reaches the end of the array, it simply wraps around to the beginning to fill those empty spaces. It is highly efficient for memory management.</li></ul><pre>class CircularQueue {<br><br>    int[] queue;<br>    int front = -1;<br>    int rear = -1;<br>    int size;<br><br>    CircularQueue(int size) {<br>        this.size = size;<br>        queue = new int[size];<br>    }<br><br>    void enqueue(int value) {<br><br>        if ((rear + 1) % size == front) {<br>            System.out.println(&quot;Queue is Full&quot;);<br>            return;<br>        }<br><br>        if (front == -1)<br>            front = 0;<br><br>        rear = (rear + 1) % size;<br>        queue[rear] = value;<br>    }<br><br>    void dequeue() {<br><br>        if (front == -1) {<br>            System.out.println(&quot;Queue is Empty&quot;);<br>            return;<br>        }<br><br>        System.out.println(&quot;Removed: &quot; + queue[front]);<br><br>        if (front == rear) {<br>            front = rear = -1;<br>        } else {<br>            front = (front + 1) % size;<br>        }<br>    }<br><br>    void display() {<br><br>        if (front == -1) {<br>            System.out.println(&quot;Empty&quot;);<br>            return;<br>        }<br><br>        int i = front;<br><br>        while (true) {<br>            System.out.print(queue[i] + &quot; &quot;);<br>            if (i == rear)<br>                break;<br><br>            i = (i + 1) % size;<br>        }<br><br>        System.out.println();<br>    }<br>}<br><br>public class Main {<br><br>    public static void main(String[] args) {<br><br>        CircularQueue q = new CircularQueue(5);<br><br>        q.enqueue(10);<br>        q.enqueue(20);<br>        q.enqueue(30);<br>        q.enqueue(40);<br>        q.enqueue(50);<br><br>        q.dequeue();<br>        q.dequeue();<br><br>        q.enqueue(60);<br>        q.enqueue(70);<br><br>        q.display();<br>    }<br>}</pre><p><strong>C. Priority Queue (The Emergency Room)</strong></p><p>This type completely breaks the “first come, first served” rule. Instead, it operates on a <strong>“most important, served first”</strong> basis.</p><ul><li><strong>How it works:</strong> Every element enters the queue with an assigned <strong>priority value</strong>. When you remove an element, the one with the highest priority is served first, regardless of when it arrived. If two elements have the same priority, they follow the standard FIFO order.</li><li><strong>Real-World Analogy:</strong> A hospital emergency room. A patient with a critical injury is treated immediately, ahead of someone who arrived earlier with a minor cold.</li></ul><pre>import java.util.PriorityQueue;<br><br>public class Main {<br><br>    public static void main(String[] args) {<br><br>        PriorityQueue&lt;Integer&gt; numbers = new PriorityQueue&lt;&gt;();<br><br>        numbers.offer(30);<br>        numbers.offer(10);<br>        numbers.offer(20);<br><br>        while (!numbers.isEmpty()) {<br>            System.out.println(numbers.poll());<br>        }<br>    }<br>}</pre><p><strong>D. Deque (Double-Ended Queue)</strong></p><p>Pronounced as “Deck”, this is a highly flexible, hybrid queue.</p><ul><li><strong>How it works:</strong> Elements can be inserted or deleted from <strong>both ends</strong> (both Front and Rear).</li><li><strong>The Benefit:</strong> It acts like a wildcard. You can restrict its features to make it behave exactly like a Stack or like a standard Simple Queue depending on your needs.</li></ul><pre>import java.util.ArrayDeque;<br>import java.util.Deque;<br><br>public class Main {<br><br>    public static void main(String[] args) {<br><br>        Deque&lt;String&gt; books = new ArrayDeque&lt;&gt;();<br><br>        books.addFirst(&quot;Java&quot;);<br>        books.addLast(&quot;Python&quot;);<br>        books.addFirst(&quot;C++&quot;);<br>        books.addLast(&quot;Flutter&quot;);<br><br>        System.out.println(books);<br>    }<br>} <br>// [C++, Java, Python, Flutter]</pre><h4>3.2.2 Non-Linear Data Structures</h4><p>Unlike Arrays, Stacks, and Queues where data is arranged sequentially in a straight line, Non-Linear Data Structures arrange elements hierarchically or in interconnected networks.</p><p>Think of it this way: Linear structures are like reading a book line-by-line. Non-linear structures are like exploring a map or a family tree.</p><h4>There are two main types:</h4><ol><li><strong>Trees:</strong></li></ol><p>A Tree is a hierarchical data structure consisting of nodes connected by edges. It starts with a single root node, and every child node has exactly one parent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JGFkX2nzai8FKhHprg6e7w.png" /><figcaption>A structured infographic showing major tree data structure categories</figcaption></figure><p><strong>2. Graphs :</strong></p><p>A Graph is a non-linear data structure consisting of vertices (nodes) connected by edges. Unlike trees, graphs can have cycles and multiple paths between nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FIf5_rPHKoDH-iIY3LXDHg.png" /></figure><h3>4. The Invisible Hero: Where are they hiding in your code?</h3><p>You might be thinking, “Okay, this is great theory, but I’ve been writing code for months and I’ve never built a Linked List or a Graph from scratch!” That’s because you don’t have to.</p><p>Language creators already built them for you! Every time you use a built-in feature in your favorite programming language, you are actually calling these Data Structures behind the scenes.</p><p><strong>Let’s look at where these invisible heroes are hiding in your daily code:</strong></p><ol><li><strong>The Arrays &amp; Vectors</strong></li></ol><p>You use these every single day. Whenever you need a simple list of items, you are using an Array or its dynamic cousin under the hood:</p><ul><li><strong>In Python:</strong> Standard lists (like my_list = [1, 2, 3]) are actually dynamic arrays.</li><li><strong>In Java: </strong>ArrayList is a dynamic array that automatically resizes when it gets full.</li><li><strong>In JavaScript:</strong> Standard arrays [] behave like dynamic arrays with extra superpowers.</li></ul><p><strong>2. The Stacks &amp; Queues</strong></p><p>You rarely type the word “Stack” or “Queue” in standard web development, but your environment is completely run by them:</p><ul><li><strong>The Call Stack (JavaScript/Python/Java)</strong>: When you call functionA() which calls functionB(), the computer keeps track of where to go back using a hidden Stack in memory. If you get a recursion error, that’s a Stack Overflow!</li><li><strong>The JS Event Loop (Queue):</strong> JavaScript handles asynchronous tasks (like fetching data from an API) using something called the Callback Queue. It follows the strict FIFO rule to execute your code in order.</li></ul><p><strong>3. The Trees (The Hidden Sorters)</strong></p><p>Whenever you want your data to be perfectly unique, sorted, or grouped, a tree is usually working in the dark:</p><ul><li><strong>In Java / C++:</strong> When you use a TreeSet or a std::map, the language doesn&#39;t use an array. It builds a <strong>Self-Balancing Red-Black Tree</strong> in your RAM so that searching for any item always takes strict $O(\log n)$ time.</li><li><strong>In Databases (SQL):</strong> When you add an “Index” to a database table to make searches faster, the database engine creates a <strong>B-Tree</strong> (a special type of tree) to map your data.</li></ul><p><strong>4. The Graphs (The Heavy Lifters)</strong></p><p>You won’t find a primitive Graph type in most standard libraries because they are highly specialized, but they are the core of major packages:</p><ul><li><strong>Networking &amp; Routers:</strong> The internet protocols running on your machine use graph algorithms to route data packets through the fastest path.</li><li><strong>Git Version Control</strong>: Every git commit, branch, and merge you make creates a directed graph (specifically a DAG — Directed Acyclic Graph) of your project’s history!</li></ul><blockquote>The Takeaway: As a developer, you don’t always need to reinvent the wheel and build these structures from scratch. Your real job is to understand how they work so you can pick the right built-in tool for the right job.</blockquote><h3>Final Thoughts</h3><p>Data Structures are not just theoretical concepts to pass a technical interview; they are the literal skeleton of every modern software application. Writing code without understanding them is like building a house without knowing what bricks are made of.</p><p>By mastering these fundamentals, you are transitioning from someone who just writes code to a true software craftsman who designs efficient, scalable systems.</p><h4>Finally , I hope the article was useful to you and your opinion is very important to me.</h4><p><a href="http://linkedin.com/in/rwan-hossam-08ba39295">LinkedIn</a></p><p><a href="http://rwanhossam0@gmail.com/">Email</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e51c2b861ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Security Fundamentals: Understanding the Foundation Before Building Secure Apps]]></title>
            <link>https://medium.com/@RwanHossam/security-fundamentals-understanding-the-foundation-before-building-secure-apps-abaf9c6bad57?source=rss-e6594c14ec85------2</link>
            <guid isPermaLink="false">https://medium.com/p/abaf9c6bad57</guid>
            <dc:creator><![CDATA[Rwan Hossam Eldein]]></dc:creator>
            <pubDate>Fri, 24 Apr 2026 16:39:21 GMT</pubDate>
            <atom:updated>2026-04-24T16:40:49.604Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cu3aNCj4kyGIFYGBBApqYQ.png" /></figure><p>After exploring networking fundamentals, it becomes clear that every mobile app relies heavily on data exchange — requests, responses, APIs, and connections that happen constantly behind the scenes.</p><p>But here’s the real question:<br><strong>What protects all of this communication?</strong></p><p>Security is not just an advanced topic or something to “add later.” It’s a fundamental layer that should be understood before writing a single secure line of code.</p><p>In mobile development, especially when working with frameworks like Flutter, you are constantly dealing with sensitive data — user credentials, tokens, personal information, and API communication. Without a solid understanding of security basics, it’s easy to unintentionally introduce vulnerabilities.</p><p>This is where concepts like authentication, authorization, encryption, and hashing come into play. These are not just theoretical ideas — they directly impact how safe your app is in real-world scenarios.</p><p>Organizations like OWASP highlight that most security issues don’t happen because developers don’t care about security, but because they don’t fully understand these core concepts.</p><p>In this article, we’ll break down the essential security fundamentals in a simple and practical way — focusing on how they apply to mobile apps, and specifically how you can use them as a Flutter developer to build more secure applications from the ground up.</p><h3>1️⃣Introduction</h3><p>Imagine you are building a house. You wouldn’t only focus on the walls and rooms — you would also think about how to lock the doors, secure the windows, and know who is entering your home.</p><p>This is exactly how you should think when building an application or a system.</p><p>Security is not just about making your app “work.” It’s about protecting your data, your users, and your services from being exposed, misused, or disrupted.</p><p>Organizations like OWASP emphasize that many vulnerabilities happen not because developers ignore security, but because they don’t think about it from the beginning.</p><h3>2️⃣CIA Triad</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/0*jeetv86OgmAhdt51.png" /></figure><p>Before you can secure anything, you need to understand <strong>what you are protecting</strong>.</p><p>This is exactly what the <strong>CIA Triad</strong> answers.</p><p>The CIA Triad is the fundamental framework of security. Almost every security decision comes down to one simple question:</p><p><strong>“Which of the three does this protect?”</strong></p><h3>🔵 C — Confidentiality</h3><p>Confidentiality means ensuring that data is only accessible to authorized users.</p><p>In simple terms:<br>If you send a private message to a friend, only that friend should be able to read it.</p><h4>How do we achieve it?</h4><ul><li>Authentication (verifying identity)</li><li>Access Control (who can access what)</li><li>Encryption (protecting data during storage and transmission)</li></ul><h3>🟣 I — Integrity</h3><p>Integrity means ensuring that data is not altered or tampered with.</p><h4>Real-life example:</h4><p>You send a signed document.<br>If someone changes the content without changing the signature, the integrity is broken.</p><h4>Technical example:</h4><p>An app sends a request:</p><pre>{ &quot;amount&quot;: 100, &quot;to&quot;: &quot;Ahmed&quot; }</pre><p>An attacker intercepts and modifies it:</p><pre>{ &quot;amount&quot;: 10000, &quot;to&quot;: &quot;Hacker&quot; }</pre><p>This is a clear integrity violation.</p><h4>How do we protect it?</h4><ul><li>Hashing → creates a fingerprint of the data</li><li>Digital Signatures → verifies authenticity and integrity</li><li>Checksums → ensures data hasn’t changed during transfer</li></ul><h3>🟢 A — Availability</h3><p>Availability ensures that systems and services are accessible when users need them.</p><h4>Real-life example:</h4><p>An ATM machine — the money exists, but if the machine is out of service, you can’t access it.</p><h4>Technical example:</h4><p>A DDoS attack floods the server with millions of requests, causing it to crash.<br>The app becomes unavailable → Availability is compromised.</p><h4>How do we protect it?</h4><ul><li>Rate Limiting → controlling request volume</li><li>Load Balancers → distributing traffic</li><li>Firewalls → blocking malicious traffic</li></ul><p>In real-world systems, these three principles can conflict with each other.</p><p>For example:</p><ul><li>Applying very strong encryption everywhere may reduce performance</li><li>Reduced performance can impact availability</li></ul><p>This is why security is not about maximizing one aspect — <br>it’s about <strong>balancing all three</strong>.</p><h3>3️⃣Cryptography — Symmetric Encryption</h3><h4>What is Cryptography?</h4><p>Cryptography is the science of transforming data into an unreadable format to protect it from unauthorized access.</p><p>In simple terms:<br>Even if someone intercepts your data, they <strong>can’t understand it</strong>.</p><h4>What is Symmetric Encryption?</h4><p>Symmetric Encryption is a method where the <strong>same key</strong> is used for both:</p><ul><li>Encrypting the data</li><li>Decrypting the data</li></ul><h4>Simple Analogy</h4><p>Think of it like a locked box:</p><ul><li>You lock it with a key</li><li>The same key is used to open it</li></ul><p>So anyone who has the key can access what’s inside.</p><h3>How It Works</h3><ol><li>Plain data (<strong>plaintext</strong>) is taken</li><li>It is encrypted using a <strong>secret key</strong></li><li>It becomes unreadable (<strong>ciphertext</strong>)</li><li>The receiver uses the <strong>same key</strong> to decrypt it</li></ol><h3>Example</h3><pre>Plaintext:  &quot;Hello&quot;<br>Key:        &quot;secret123&quot;</pre><pre>Encrypted → &quot;Xk29#@!&quot;</pre><p>Without the key, the data is meaningless.</p><h3>Why is it Important?</h3><ul><li>Very <strong>fast and efficient</strong></li><li>Suitable for encrypting <strong>large amounts of data</strong></li><li>A core part of secure communication</li></ul><h3>The Main Problem</h3><p>The biggest challenge in symmetric encryption is:</p><p><strong>How do you safely share the key?</strong></p><p>If an attacker gets the key:</p><ul><li>They can decrypt everything</li><li>The entire system becomes compromised</li></ul><p>This is why symmetric encryption is usually combined with other techniques like asymmetric encryption.</p><h3>Common Algorithms</h3><p>🔸 AES (Advanced Encryption Standard) — widely used and secure</p><p>🔸 DES (Data Encryption Standard) — outdated and less secure today</p><h3>Flutter Perspective</h3><p>As a Flutter developer, you typically don’t implement encryption algorithms from scratch — but you rely on them all the time.</p><h4>🔹 Secure API Communication</h4><p>When your app uses HTTPS:</p><ul><li>Data is encrypted before transmission</li><li>Symmetric encryption is used for performance</li></ul><h4>🔹 Local Data Protection</h4><pre>import &#39;package:flutter_secure_storage/flutter_secure_storage.dart&#39;;</pre><pre>final storage = FlutterSecureStorage();</pre><pre>// Store sensitive data securely<br>await storage.write(key: &#39;token&#39;, value: &#39;user_token_here&#39;);</pre><p>Behind the scenes, encryption (often symmetric) is used to protect this data.</p><h3>4️⃣Cryptography — Asymmetric Encryption</h3><h3>The Core Idea</h3><p>Unlike symmetric encryption, <strong>asymmetric encryption</strong> uses two different keys:</p><ul><li><strong>Public Key</strong> → used for encryption (can be shared with anyone)</li><li><strong>Private Key</strong> → used for decryption (kept secret)</li></ul><p>So instead of one shared key, we now have a <strong>pair of keys that work together</strong>.</p><h3>Real-Life Analogy</h3><p>Think of a mailbox in the street:</p><ul><li>The slot where anyone can drop letters → <strong>Public Key</strong></li><li>The key used to open the mailbox → <strong>Private Key</strong></li></ul><p>Anyone can send you a message, but only you can read it.</p><h3>How It Works</h3><p>Let’s say you want to send a secure message to a server:</p><ol><li>The server shares its <strong>Public Key</strong></li><li>You use it to encrypt your message</li><li>You send the encrypted message</li><li>The server decrypts it using its <strong>Private Key</strong></li></ol><p>Even if someone intercepts the message, they can’t read it without the private key.</p><h3>Common Algorithms</h3><h4>🔸 RSA</h4><ul><li>The most widely known algorithm</li><li>Based on the difficulty of factoring large prime numbers</li><li>Key sizes:</li><li>2048-bit → standard secure level</li><li>4096-bit → stronger but slower</li></ul><h4>🔸 ECC (Elliptic Curve Cryptography)</h4><ul><li>More modern and efficient</li><li>Provides the same security with much smaller keys</li><li>Example:</li><li>256-bit ECC ≈ 3072-bit RSA in security strength</li></ul><h3>The Main Drawback</h3><p>Asymmetric encryption is <strong>computationally slow</strong></p><p>That’s why it is not used to encrypt large amounts of data directly.</p><h3>Digital Signatures</h3><p>Asymmetric encryption is not only for encryption — it is also used for <strong>authentication and integrity</strong>.</p><h4>How it works:</h4><ul><li><strong>Private Key → used to sign data</strong></li><li><strong>Public Key → used to verify the signature</strong></li></ul><h3>Example</h3><p>A server wants to prove that a response is really from it:</p><ol><li>The server creates a hash of the data</li><li>It encrypts the hash using its <strong>Private Key</strong> → this is the signature</li><li>It sends:</li></ol><ul><li>The data</li><li>The signature</li></ul><h3>On the client side:</h3><ol><li>The app decrypts the signature using the server’s <strong>Public Key</strong></li><li>It computes its own hash of the received data</li><li>It compares both hashes</li></ol><p>If they match:</p><ul><li>✔️ Data is authentic</li><li>✔️ Data was not modified</li><li>✔️ It came from the real server</li></ul><h3>Key Insight</h3><p>Asymmetric encryption helps solve two critical problems:</p><ul><li>Secure key exchange</li><li>Identity verification (via digital signatures)</li></ul><p>It plays a key role in:</p><ul><li>Authentication</li><li>Integrity</li><li>Secure communication systems</li></ul><h3>5️⃣Hashing</h3><h4>The Core Idea</h4><p>Hashing is the process of converting any data into a <strong>fixed-size fingerprint</strong>.</p><ul><li>This fingerprint is called a <strong>hash</strong></li><li>It is <strong>one-way</strong> → you cannot reverse it back to the original data</li></ul><p>Think of it like a digital fingerprint — <br>it uniquely represents the data, but you can’t reconstruct the original from it.</p><h4>Properties of a Good Hash Function</h4><p><strong>1. One-Way</strong></p><p>It is <strong>impossible</strong> to reverse the hash back to the original plaintext.</p><p><strong>2. Deterministic</strong></p><p>The same input always produces the same output.</p><pre>&quot;hello&quot; → &quot;2cf24dba...&quot;<br>&quot;hello&quot; → &quot;2cf24dba...&quot; (always)</pre><p><strong>3. Avalanche Effect</strong></p><p>A tiny change in input → a completely different hash.</p><pre>&quot;hello&quot; → &quot;2cf24dba5fb0a...&quot;<br>&quot;Hello&quot; → &quot;185f8db32921...&quot;  ← totally different</pre><p><strong>4. Fixed Size</strong></p><p>No matter the input size, the output length is always the same.</p><pre>&quot;hi&quot; → 64 characters  <br>&quot;a 1000-page book&quot; → 64 characters  </pre><p><strong>5. Collision Resistance</strong></p><p>It should be extremely hard to find two different inputs that produce the same hash.</p><h4>Main Use Cases</h4><h4>1. Password Storage</h4><p><strong>❌ Wrong approach:</strong></p><pre>username=&quot;sara&quot;, password=&quot;123456&quot;</pre><p>If the database is leaked → all passwords are exposed.</p><p><strong>✅ Correct approach:</strong></p><pre>username=&quot;sara&quot;, password_hash=&quot;ef92b778...&quot;</pre><h4>Login Process:</h4><ol><li>User enters password</li><li>App hashes it</li><li>Compare with stored hash</li><li>Match → access granted</li></ol><p>Even if the database is stolen, passwords remain protected.</p><h4>2. File Integrity Verification</h4><p>When downloading a file:</p><ul><li>Website provides:</li></ul><pre>SHA-256 = &quot;abc123...&quot;</pre><ul><li>You hash the downloaded file:</li><li>Same hash → file is safe</li><li>Different → file was modified</li></ul><h4>3. API Integrity (Preview)</h4><p>Hashing is also used in secure communication (like TLS) to ensure data hasn’t been altered.</p><h3>Problem: Rainbow Tables</h3><p>Attackers use precomputed tables like:</p><pre>&quot;123456&quot;   → &quot;e10adc39&quot;<br>&quot;password&quot; → &quot;5f4dcc3b&quot;</pre><p>If they find your hash in the database, they can look it up and recover the password.</p><h3>Solution: Salt</h3><p>Before hashing, you add a <strong>random value (salt)</strong>:</p><pre>Password: &quot;123456&quot;<br>Salt:     &quot;xK9#mP2&quot;<br>Combined: &quot;123456xK9#mP2&quot;<br>Hash:     &quot;9f2b4c...&quot;</pre><ul><li>Even if two users have the same password → hashes are different</li><li>Rainbow table attacks become ineffective</li></ul><h3>Why bcrypt is Best for Passwords</h3><ul><li>Automatically adds salt</li><li>Designed to be <strong>slow</strong> → harder for attackers to brute-force</li><li>Built specifically for password security</li></ul><h3>Flutter Perspective</h3><p>As a Flutter developer, hashing is typically handled on the backend — <br>but you should still understand it to avoid common mistakes.</p><h4>🔹 Example (Dart hashing)</h4><pre>import &#39;dart:convert&#39;;<br>import &#39;package:crypto/crypto.dart&#39;;</pre><pre>void main() {<br>  var bytes = utf8.encode(&quot;hello&quot;);<br>  var hash = sha256.convert(bytes);<br>  print(hash);<br>}</pre><blockquote><em>Important: Never implement password hashing manually on the client.<br>Always rely on secure backend implementations (like bcrypt).</em></blockquote><p>Hashing plays a critical role in ensuring <strong>integrity and security</strong>, and it works closely with other concepts like encryption and authentication that we’ve discussed.</p><h3>6️⃣TLS/SSL</h3><h3>What is TLS?</h3><p><strong>Transport Layer Security (TLS)</strong> is the protocol that secures communication between your app and the server.</p><ul><li><strong>SSL</strong> is the older version (now deprecated)</li><li>The lock icon in your browser means TLS is active</li></ul><h3>The Problem Without TLS</h3><pre>App → [HTTP] → Server</pre><p>Data inside the request:</p><pre>password=123456&amp;user=ahmed</pre><p>Anyone on the same network (like public WiFi) can:</p><ul><li>Read the data</li><li>Steal passwords</li><li>Modify requests</li></ul><p>This is called a <strong>Man-in-the-Middle (MITM) attack</strong>.</p><h3>With TLS (HTTPS)</h3><pre>App → Server<br>Xk29#@!$%^...</pre><ul><li>Data is encrypted</li><li>No one can read or change it</li><li>Only the server can understand it</li></ul><h3>What Happens Behind the Scenes?</h3><p>Before sending any data, your app and the server do a quick “handshake”:</p><ol><li>Your app says:<br><em>“I want a secure connection”</em></li><li>The server replies:<br><em>“Here’s my identity (certificate + public key)”</em></li><li>They agree on a <strong>secret key</strong></li><li>From now on:</li></ol><ul><li>All data is encrypted using that key</li></ul><p>That’s it. After this, communication becomes secure.</p><h3>What Does TLS Actually Protect?</h3><p>TLS covers key security goals:</p><ul><li><strong>Confidentiality</strong> → no one can read the data</li><li><strong>Integrity</strong> → data cannot be modified</li><li><strong>Authentication</strong> → you’re talking to the real server</li></ul><h3>Your Role as a Flutter Developer</h3><p>Here’s the most important part</p><h3>You don’t implement TLS manually</h3><p>TLS is handled automatically by:</p><ul><li>The operating system</li><li>Networking libraries (like Dio / http)</li></ul><h3>What You SHOULD Do</h3><h4>1. Always use HTTPS</h4><pre>final response = await dio.get(&quot;https://api.example.com&quot;);</pre><h4>2. Never disable certificate validation</h4><pre>// Dangerous — allows fake servers<br>client.badCertificateCallback = (cert, host, port) =&gt; true;</pre><h4>3. Use secure storage for sensitive data</h4><p>Even with TLS:</p><ul><li>If tokens are stored insecurely → risk remains</li></ul><h4>4. Certificate Pinning</h4><p>For high-security apps, you can restrict your app to trust only a specific server:</p><blockquote><em>“I only trust this exact server identity.”</em></blockquote><p>This helps protect against advanced MITM attacks.</p><h3>7️⃣ JWT <strong>(JSON Web Token)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Kc55awQKf1FoPrF-.png" /></figure><h4>What is JWT?</h4><p><strong>JWT (JSON Web Token)</strong> is a method used to securely transmit information between the client (Your app) and the server.</p><p>After a user logs in successfully:</p><ul><li>The server generates a JWT</li><li>The client stores it</li><li>The client sends it with every request</li></ul><p>It acts like a <strong>proof of authentication</strong></p><h4>JWT Structure</h4><p>A JWT looks like this:</p><pre>eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOiIxMjMifQ.abc123</pre><p>It is made of 3 parts separated by dots:</p><pre>Header.Payload.Signature</pre><h3>1. Header</h3><pre>{<br>  &quot;alg&quot;: &quot;HS256&quot;,<br>  &quot;typ&quot;: &quot;JWT&quot;<br>}</pre><p>It defines:</p><ul><li>The algorithm used</li><li>The token type</li></ul><h3>2. Payload</h3><pre>{<br>  &quot;userId&quot;: &quot;123&quot;,<br>  &quot;email&quot;: &quot;sara@example.com&quot;,<br>  &quot;role&quot;: &quot;admin&quot;,<br>  &quot;exp&quot;: 1716239022<br>}</pre><p>These are called <strong>claims</strong> — the data inside the token.</p><h3>⚠️ Important:</h3><ul><li>Payload is <strong>NOT encrypted</strong></li><li>It is only <strong>Base64 encoded</strong></li><li>Anyone can read it</li></ul><p>Never store passwords or sensitive secrets here.</p><h3>3. Signature</h3><p>The signature ensures the token was not modified:</p><pre>HMAC-SHA256(<br>  Base64(Header) + &quot;.&quot; + Base64(Payload),<br>  Secret Key<br>)</pre><p>Only the server knows the secret key</p><h3>How Token Verification Works</h3><p>When the server receives a JWT:</p><ol><li>It reads Header + Payload</li><li>Recalculates the signature using its secret key</li><li>Compares it with the received signature</li><li>If they match → token is valid</li></ol><h3>Authentication Flow</h3><pre>1. User logs in<br>  <br>2. Server returns:<br>   - Access Token<br>   - Refresh Token<br>  <br>3. App sends Access Token with requests<br>   <br>4. If expired → use Refresh Token<br>  <br>5. Get new Access Token</pre><h3>Where to Store JWT in Flutter?</h3><p>SharedPreferences: Not secure (not encrypted)</p><p>Flutter Secure Storage: Secure (uses device keystore)</p><p>🔹 Recommended Flutter storage:</p><pre>final storage = FlutterSecureStorage();</pre><pre>await storage.write(key: &quot;token&quot;, value: jwtToken);</pre><h3>8️⃣OAuth2</h3><h3>What is OAuth2?</h3><p><strong>OAuth2 (Open Authorization 2)</strong> is a protocol that allows an application to access your data on another service <strong>without knowing your password</strong>.</p><p>In simple words:</p><blockquote><em>“You give permission to an app to access specific data — without giving it your login credentials.”</em></blockquote><h3>Real-Life Example</h3><p>Imagine a Fitness app wants access to your Google Calendar.</p><h3>Old (Unsafe) Approach:</h3><p>The app asks for:</p><ul><li>Google email</li><li>Google password</li></ul><p><strong>Problem:</strong></p><ul><li>The app now knows your password</li><li>Very high security risk</li></ul><h3>OAuth2 Approach:</h3><ol><li>The app redirects you to Google</li><li>Google asks you:</li></ol><blockquote>“Do you allow this app to access your calendar?”</blockquote><p>3. You approve</p><p>4. Google gives the app a <strong>limited token</strong></p><p>The app never sees your password.</p><h3>Key Components of OAuth2</h3><ol><li>Resource Owner (The user)</li><li>Client (The app)</li><li>Authorization Server (Issues tokens)</li><li>Resource Server (Holds data)</li></ol><h3>Authorization Code Flow (Most Common)</h3><p>This is the most secure flow used in real applications:</p><pre>1. App opens Google Login page<br>   <br>2. User logs in on Google (not inside the app)<br>   <br>3. Google returns Authorization Code<br>   <br>4. App sends code to backend<br>   <br>5. Backend exchanges it for Access Token<br>   <br>6. App uses Access Token to access APIs</pre><p>Notice:</p><ul><li>Password is never shared with the app</li><li>Everything is controlled by Google</li></ul><h3>PKCE — Important for Mobile Apps</h3><p>Mobile apps (like Flutter apps) don’t always have a secure backend,in the OAuth2 flow Someone might steal the Authorization Code while he’s coming back</p><p>so OAuth2 uses <strong>PKCE (Proof Key for Code Exchange)</strong>.</p><h3>Why PKCE?</h3><p>It protects the login flow from interception attacks.</p><h3>How PKCE works (simplified)</h3><pre>1. App creates a random secret (code verifier)<br>2. App creates a hashed version (code challenge)<br>3. Sends challenge during login<br>4. Receives authorization code<br>5. Uses original verifier to get the token</pre><p>Even if someone intercepts the request:</p><ul><li>They cannot exchange the code without the verifier</li></ul><h4>What does it mean, simply put?</h4><p>PKCE = Make sure the same application that started the login process is the one that completed it.</p><p>Flutter packages do this automatically, like this:</p><ul><li>flutter_appauth</li><li>openid_client</li></ul><h3>OAuth2 vs Authentication</h3><p>Here is a very important concept</p><h4>OAuth2 is NOT Authentication</h4><p>OAuth2 is only:</p><p><strong>Authorization (what the app is allowed to do)</strong></p><p>It does NOT answer:</p><ul><li>“Who are you?”</li></ul><h4>Example:</h4><p>OAuth2 says:</p><blockquote><em>“This app can read your calendar”</em></blockquote><p>But it does NOT say:</p><blockquote><em>“This is Sara”</em></blockquote><h3>OAuth2 + OpenID Connect</h3><p>To solve this, we use:</p><p><strong>OpenID Connect (OIDC)</strong></p><p>It is built on top of OAuth2 and adds:</p><ul><li>Authentication (identity layer)</li></ul><h3>9️⃣OWASP Top 10</h3><p>Before building secure applications, it’s important to understand the most common security mistakes developers make.</p><p>This is exactly what OWASP provides.</p><p>OWASP (Open Web Application Security Project) is a well-known organization that publishes a list of the Top 10 most critical security risks in modern applications.</p><p>These are not theoretical problems — they are real-world issues that happen in production systems.</p><h4>Why does this matter to you as a Flutter Developer?</h4><p>Even though many of these vulnerabilities happen on the backend, you are still part of the attack surface.</p><p>Bad decisions in the mobile app can make these vulnerabilities easier to exploit.</p><p>Conclusion</p><p>Security is not a single feature you add at the end of development — it is a mindset you apply from the very beginning.</p><p>From understanding the CIA Triad, to using encryption and hashing, to securing communication with TLS, and managing identity with JWT and OAuth2 — every layer plays a role in protecting your application.</p><p>As a Mobile App developer, your responsibility is not to implement complex cryptography from scratch, but to:</p><ul><li>Use secure tools correctly</li><li>Avoid common mistakes</li><li>Understand how systems work behind the scenes</li></ul><h4>Because in real-world applications:</h4><blockquote>A small mistake in security can lead to a very big problem.</blockquote><p>In the next part, we’ll dive into Mobile Security Concepts</p><p>Finally , I hope the article was useful to you and your opinion is very important to me.</p><p><a href="https://www.linkedin.com/in/rwan-hossam-08ba39295/?lipi=urn%3Ali%3Apage%3Ad_flagship3_profile_view_base_contact_details%3BIbbswjEVRYW%2BvApQg1zwHg%3D%3D">LinkedIn</a></p><p><a href="http://rwanhossam0@gmail.com/">Email</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abaf9c6bad57" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mobile applications today handle some of the most sensitive data in our lives — personal…]]></title>
            <link>https://medium.com/@RwanHossam/introduction-21c70c2599f1?source=rss-e6594c14ec85------2</link>
            <guid isPermaLink="false">https://medium.com/p/21c70c2599f1</guid>
            <dc:creator><![CDATA[Rwan Hossam Eldein]]></dc:creator>
            <pubDate>Wed, 04 Mar 2026 16:47:27 GMT</pubDate>
            <atom:updated>2026-03-05T13:49:03.113Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0JcBgUSU-CdJTJIcexIqQw.png" /></figure><p>Mobile applications today handle some of the most sensitive data in our lives — personal information, authentication tokens, payment details, and private messages. As developers, we are not just building features and user interfaces; we are building systems that users trust with their data.</p><p>Security in mobile apps is no longer optional. A single vulnerability can expose user data, damage a company’s reputation, and compromise trust. And interestingly, many security issues don’t start with complex cryptography problems — they start with something much simpler: networking.</p><p>Before we talk about encryption algorithms, authentication flows, or secure storage, we need to understand how mobile apps communicate with servers in the first place. Every login request, every API call, and every piece of data sent or received travels through a network.</p><p>That’s why this journey into Mobile App Security begins with networking foundations. Because if we don’t understand how data moves, we can’t properly secure it.</p><h3>1️⃣How Mobile Apps Communicate with Servers</h3><h4>🔹Client vs Server</h4><p>The client is usually the mobile app or browser making requests, while the server is where the data or resources are stored and sent back to the client.</p><h4>🔹 Meaning of protocol</h4><p>Before we dive into the differences between HTTP and HTTPS, it’s important to understand what they actually are. HTTP and HTTPS are both protocols — a protocol is essentially a set of rules that allows two sides, the client and the server, to communicate with each other.</p><blockquote>Think of a protocol like a phone call etiquette — <br>both sides know:<br>- who speaks first<br>- how to respond<br>- when the conversation ends</blockquote><pre>http.get(Uri.parse(&#39;https://api.example.com/users&#39;))<br>// You&#39;re using a protocol — a set of rules that tells your app:<br>// how to format the request, where to send it,<br>// and how to understand the response.</pre><h4>🔹Request &amp; Response Cycle</h4><p>Before diving deeper, let’s ask a simple question: What are the components of a Request &amp; Response?</p><blockquote>Client → “I want data” → Server<br>Client ← “Here is the data” ← Server</blockquote><pre>// In Flutter, a simple request might look like:<br>http.get(&#39;https://api.example.com/users&#39;)</pre><p>1️⃣<strong>HTTP Request Components</strong></p><p>When the client sends a request, it contains several parts:</p><ul><li><strong>URL (What you want)</strong></li></ul><p>The address of the resource you are requesting: <a href="https://api.example.com/users">https://api.example.com/users</a></p><ul><li><strong>Method (What you want to do)</strong></li></ul><p>Defines the action:</p><p>- GET → Retrieve data</p><p>- POST → Send data</p><p>-DELETE → Remove data</p><ul><li><strong>Headers (Additional information)</strong></li></ul><p>Metadata about the request, such as authentication tokens:</p><pre>Authorization: Bearer token123<br>Content-Type: application/json</pre><ul><li><strong>Body (The data itself)</strong></li></ul><p>For requests like POST or PUT, this contains the data you are sending:</p><pre>{<br>  &quot;username&quot;: &quot;sara&quot;,<br>  &quot;password&quot;: &quot;123&quot;<br>}</pre><p>2️⃣<strong>HTTP Response Components</strong></p><p>After the server processes the request, it sends back a response consisting of:</p><p>1- Status Code → Indicates if the request was successful or not</p><pre>200 → OK<br>401 → Who are you? (missing/invalid token)     ← security!<br>403 → I know you, but you can&#39;t do this        ← security!<br>404 → Not found<br>500 → Server error</pre><p>2- Headers → Additional information about the response</p><p>3- Body → The actual data requested or the result of the action</p><pre>{<br>  &quot;id&quot;: 1,<br>  &quot;username&quot;: &quot;sara&quot;,<br>  &quot;email&quot;: &quot;sara@example.com&quot;<br>}</pre><p>Now here’s the important question: When this request travels through the network, is it safe? Can anyone intercept it?</p><p>That’s exactly what we’ll explore next — HTTP vs HTTPS.</p><h3>2️⃣HTTP vs HTTPS</h3><p>When the client sends a request to the server, that request travels through a network — which you can imagine as a road between the two sides.</p><p>If this road is not protected, anyone positioned along the way could potentially see or even modify the data being transmitted. This type of attack is known as a Man-in-the-Middle (MITM) attack.</p><p>This is where HTTPS comes in.</p><p>With plain HTTP, the data is sent in readable text (plain text). Anyone intercepting the traffic can view sensitive information such as passwords, tokens, or personal data.</p><p>With HTTPS, the communication is encrypted before it travels across the network. This encryption is achieved using TLS (Transport Layer Security).</p><p>TLS ensures that:</p><ul><li>The data is encrypted before being sent</li><li>Only the intended server can decrypt it</li><li>The integrity of the data is preserved</li><li>The server’s identity is verified through a digital certificate</li></ul><blockquote>In simple terms: HTTP sends data openly. HTTPS locks the data before sending it.</blockquote><pre>HTTP:<br>username=sara&amp;password=123<br><br>HTTPS:<br>Encrypted data: XJH23JKH89JSD</pre><p>But how does TLS verify the server’s identity?<br>This is where SSL Certificates come in — <br>and this is where things get really interesting <br>from a security perspective.</p><h3>3️⃣What Happens During an HTTPS Request?</h3><h4>🔹 How Your Device Finds the Server</h4><p>When you write a request in your app like:</p><pre>https://api.example.com/users</pre><p>Your mobile device doesn’t actually understand names like api.example.com.</p><p>It only understands IP addresses, such as:</p><pre>192.168.1.1</pre><p>So how does your app know which IP address to contact?</p><p>This is where DNS (Domain Name System) comes in. DNS acts like a phonebook for the internet.</p><p>Think of it this way:</p><ul><li>You don’t remember everyone’s phone number; you remember names:</li></ul><pre>&quot;mohammed&quot; → dialer → &quot;0101252345678&quot;</pre><ul><li>Similarly, your app uses a domain name:</li></ul><pre>&quot;api.example.com&quot; → DNS → &quot;192.168.1.1&quot;</pre><p>DNS translates the human-readable domain name into the IP address the server uses, allowing your request to reach the correct destination.</p><h4>🔹DNS Spoofing / DNS Hijacking</h4><p>Now, here’s the important security question:</p><p><strong>What happens if someone changes the IP address returned by DNS?</strong></p><ul><li>Your request could be sent to a malicious server instead of your real server.</li><li>Sensitive information like passwords, tokens, or personal data could be stolen.</li></ul><p>This attack is known as <strong>DNS Spoofing</strong> or <strong>DNS Hijacking</strong>, and it’s one of the reasons why HTTPS and <strong>certificate validation</strong> are so important.</p><h4>🔹 How HTTPS and SSL Certificates Protect You?</h4><p>This is where HTTPS and SSL/TLS certificates play a crucial role:</p><p><strong>1- Server Identity Verification</strong></p><p>When your app connects to the server via HTTPS, the server provides a digital certificate.</p><p>The certificate proves the server’s identity. Even if a hacker redirects your request to a fake server, your app will check the certificate.</p><p><strong>2-Certificate Validation</strong></p><ul><li>The client verifies:</li></ul><p>-Is the certificate issued by a trusted Certificate Authority (CA)?</p><p>-Does the certificate match the domain name I intended to reach?</p><ul><li>If it doesn’t match, the connection is terminated.</li></ul><p><strong>3-Secure Data Transmission</strong></p><ul><li>Once the certificate is verified, a secure TLS connection is established.</li><li>All data is encrypted, so even if someone intercepts it, they cannot read or modify it.</li></ul><p><strong>💡 In simple terms:</strong></p><ul><li>DNS Spoofing tries to redirect your app to a malicious server</li><li>SSL/TLS certificates ensure your app only talks to the real server</li><li>TLS encryption ensures the data cannot be stolen or tampered with</li></ul><h4>🔹 Certificate Pinning</h4><p>Even with HTTPS and SSL certificates, there’s still a small risk: what if a hacker somehow tricks your app into trusting a fake certificate? For example, using a compromised Certificate Authority or performing a sophisticated MITM attack.</p><p>This is where Certificate Pinning comes in.</p><p><strong>What is Certificate Pinning?</strong></p><p>Certificate Pinning is a technique where your mobile app only trusts a specific certificate or public key.</p><ul><li>Instead of trusting any certificate issued by a trusted CA, your app “pins” the expected certificate for your server.</li><li>If the server presents a different certificate, even if it’s valid according to the CA, your app rejects the connection.</li></ul><p><strong>Why is it important?</strong></p><ul><li>Protects against compromised CAs</li><li>Prevents MITM attacks where attackers try to impersonate your server</li><li>Adds an extra layer of security on top of HTTPS</li></ul><p>Example in Flutter :</p><pre>// Using dio package<br>(dio.httpClientAdapter as DefaultHttpClientAdapter)<br>  .onHttpClientCreate = (client) {<br>    client.badCertificateCallback = (cert, host, port) {<br>      // Only accept our known certificate<br>      return cert.pem == yourPinnedCertificate;<br>    };<br>    return client;<br>};</pre><h3>Conclusion</h3><p>In this first part, we covered the foundations of how mobile apps communicate with servers:</p><ul><li>Mobile apps request and receive data via APIs (Client ↔ Server).</li><li>HTTPS encrypts data using TLS, protecting it from eavesdropping and tampering.</li><li>DNS translates domain names into IP addresses, and SSL/TLS certificates ensure you’re talking to the real server.</li><li>Certificate Pinning adds an extra layer of security by trusting only your app’s expected server certificate.</li><li>Understanding how data moves across networks is the first step in securing mobile apps.</li></ul><p>In the next part, we’ll dive into Security Fundamentals, exploring authentication, sensitive data handling, and common mobile app vulnerabilities.</p><p><strong>Finally , I hope the article was useful to you and your opinion is very important to me.</strong></p><p><a href="https://www.linkedin.com/in/rwan-hossam-08ba39295/?lipi=urn%3Ali%3Apage%3Ad_flagship3_profile_view_base_contact_details%3BS%2FOPJ7JdSqyHCSdzaJhbzw%3D%3D">LinkedIn</a></p><p><a href="http://rwanhossam0@gmail.com/">Email</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21c70c2599f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[In my latest training, I captured a lot of amazing information about quantum computing, which…]]></title>
            <link>https://medium.com/@RwanHossam/in-my-latest-training-i-captured-a-lot-of-amazing-information-about-quantum-computing-which-c865e1f71176?source=rss-e6594c14ec85------2</link>
            <guid isPermaLink="false">https://medium.com/p/c865e1f71176</guid>
            <dc:creator><![CDATA[Rwan Hossam Eldein]]></dc:creator>
            <pubDate>Tue, 02 Sep 2025 13:15:17 GMT</pubDate>
            <atom:updated>2025-09-02T13:15:17.523Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BImcV889zp0DZXwh5Dysdw.png" /></figure><h3>In my latest training, I captured a lot of amazing information about quantum computing, which helped me discover this fascinating field of science. In this article, we will talk about what a quantum computer is, the difference between a classical computer and a quantum computer, and the fields where quantum computers can make an impact.</h3><p>The classical computer became a reality in 1947 with the invention of the transistor and in order to increase its functions, it was necessary to add more processors within the same physical space, and this was achieved through a process called <strong>miniaturization</strong>.</p><p>In 1965, <strong>Moore’s Law</strong> appeared, which states that :</p><p>“ the number of transistors per square inch on integrated circuits had doubled every year since the integrated circuit was invented’’</p><p>From this, the concept of miniaturization emerged: for example, if a processor had 2 transistors, within a year it was expected to have 4 transistors in the same physical space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*mL0dpILqMHS09lmwLc9q7g.jpeg" /><figcaption>Moore predicted that by 2020 we would reach the quantum level, where a transistor could be reduced to the size of a single atom. At that point, it would no longer be possible to shrink classical computers any further, and we would need to start working with the principles of quantum mechanics. However, in reality, this limit was reached much earlier, and Moore’s Law effectively came to an end around 2012–2015.</figcaption></figure><p>But today, companies are no longer able to manufacture new processors at the same pace predicted by Moore’s Law. To reduce the size of a transistor now, we would need to reduce the number of atoms it contains. A transistor stores information in the form of electric charges, which are distributed randomly across its atoms, and we measure the average of these charges. However, the fewer the charges, the less accurate this average becomes.</p><h3>From Bit to Qubit: Revolutionizing the Way We Store Data</h3><p>In a classical computer, data is stored using a unit called a bit, which can be either 0 or 1.</p><h4>So… is it possible to store data in a way that allows it to be both 0 and 1 at the same time?!</h4><p>In a classical computer:<br>Data is stored in a unit called a bit, which can be either 0 or 1.<br>In a quantum computer:<br>Data is stored in a unit called a qubit, which can be in a state of 0 and 1 at the same time!<br>This is due to a very important property called superposition.</p><h4>So, how does a qubit stay in this state?</h4><p>The qubit exists within a carefully controlled closed system.<br>If we give it a certain amount of energy (for example, half the energy it needs to transition from 0 to 1), it won’t completely transition. Instead of being either 0 or 1, the qubit exists in a blended state — a probability distribution between 0 and 1.<br>We express this state with this equation:</p><h4>|ψ⟩ = a|0⟩ + b|1⟩</h4><p>|ψ⟩: is the complete state of the qubit</p><p>|0⟩ and |1⟩: are the two possible states (0 or 1)</p><p>a and b: are coefficients representing the probability of the qubit being in each state.</p><p>This equation means that the qubit is in a mixture of both states. When we measure it ( actually see it), the wave collapses and it chooses only one state: either 0 or 1. Depending on the values ​​a and b. This is precisely what <strong>superposition</strong> means.</p><h3>Beyond Superposition: The Power of Entanglement</h3><p>But superposition isn’t the only trick a qubit has. Another mind-bending quantum property is called entanglement. Imagine two qubits becoming deeply linked, or entangled. In this state, what happens to one qubit instantly influences the other, no matter how far apart they are. This spooky action at a distance, as Einstein called it, allows qubits to be interconnected in ways classical bits never can. This is crucial for quantum computers because it lets them process complex, interconnected information at an incredible speed.</p><h3>Where Quantum Computers Will Make Their Mark</h3><p>While they won’t replace your laptop’s quantum computers can revolutionize a lot of fields:</p><ul><li><strong>Drug Discovery and Materials Science:</strong> They could simulate complex molecules atom-by-atom, helping us design new life-saving drugs, create more efficient batteries, or discover novel materials.</li><li><strong>Cryptography and Optimization:</strong> Quantum algorithms could break current encryption standards , but they could also create ultra-secure quantum communication. They could also solve complex logistical problems, like finding the most efficient routes for a global shipping fleet.</li><li><strong>Artificial Intelligence:</strong> They have the potential to significantly speed up machine learning processes, helping AI find patterns in data that are currently impossible to see.</li></ul><h3>Current Challenges in Quantum Computing</h3><p>Although quantum computers hold incredible potential, they still face serious challenges:</p><ul><li>Decoherence and Noise Qubits are extremely sensitive to their environment. Even tiny vibrations or temperature changes can cause them to lose their quantum state, making calculations unreliable.</li><li>Scalability Current quantum computers only work with tens or a few hundreds of qubits. For solving real-world problems like breaking encryption or simulating complex molecules, we need millions of stable qubits.</li><li>Error Correction Unlike classical computers, quantum computers need sophisticated error correction methods to keep computations accurate. These methods themselves require many extra qubits, which makes building practical systems even harder.</li></ul><p>Conclusion</p><p>Quantum computers are not meant to replace classical computers. Instead, they will complement them, tackling problems that classical systems cannot solve efficiently.</p><p>Finally , I hope the article was useful to you and your opinion is very important to me.</p><p><a href="https://www.linkedin.com/in/rwan-hossam-08ba39295?lipi=urn%3Ali%3Apage%3Ad_flagship3_profile_view_base_contact_details%3BA8oYyJFjTomRSTEsGDNSDg%3D%3D">LinkedIn</a></p><p><a href="http://rwanhossam0@gmail.com/">Email</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c865e1f71176" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“A good architecture allows decisions to be deferred.” — Robert C. Martin]]></title>
            <link>https://medium.com/@RwanHossam/a-good-architecture-allows-decisions-to-be-deferred-robert-c-martin-1628383582d5?source=rss-e6594c14ec85------2</link>
            <guid isPermaLink="false">https://medium.com/p/1628383582d5</guid>
            <dc:creator><![CDATA[Rwan Hossam Eldein]]></dc:creator>
            <pubDate>Fri, 18 Jul 2025 20:05:36 GMT</pubDate>
            <atom:updated>2025-07-18T20:05:36.530Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9UnhLbgY0zLCaU6cuKKRFQ.jpeg" /></figure><h4>“A good architecture allows decisions to be deferred.” — Robert C. Martin</h4><p>In large projects, you don’t have to make every decision upfront — because, in reality, you rarely see the full picture from the beginning.</p><h4>A good architecture gives you the flexibility to:</h4><ul><li>Delay the selection of certain tools or technologies.</li><li>Easily change the system later.</li><li>Try different solutions before settling on a final solution.</li></ul><h4>In this article, we will explore what Clean Architecture is, why it matters, and how to apply it in a real-world project.</h4><h3>What is Clean Architecture?</h3><p>Clean Architecture is a software design philosophy that organizes code into layers to promote separation of concerns, maintainability, and testability. It was introduced by Robert C. Martin (Uncle Bob) and follows the principle that the core business logic should be independent of external frameworks, databases, or UI.</p><h4>Main objective:</h4><p>If you decide to change the database, switch the UI framework, or even migrate to a different platform — the core logic of your app should remain untouched, because it’s decoupled from those external components.</p><h3>Why is Clean Architecture Important?</h3><h4>1-Maintainability</h4><p>Changes in one part of the system (like the database or UI) won’t break other parts.</p><h4>2-Scalability</h4><p>You can add new features without rewriting or breaking the existing logic.</p><h4>3-Testability</h4><p>You can test business logic in isolation — without real databases or APIs.</p><h4>4-Team Collaboration</h4><p>Multiple teams can work independently on different layers.</p><h4>5-Long-Term Flexibility</h4><p>You avoid being locked into a specific framework, tool, or database.</p><h3>Understanding the Layers of Clean Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*ZIERbPv6JIqTP-ae90cYaw.jpeg" /></figure><p>Our project is divided into three main layers, each one of them contains of three folders.</p><h4>1-Peresentation layer</h4><p>it contains :</p><p>1-UI (User Interface) — Screens, layouts, and styles</p><p>2-Widgets — Reusable components like buttons, cards, lists, etc.</p><p>3-State Management — Tools to manage UI state and behavior (e.g., Bloc, Provider, Riverpod).</p><h4>2-Domain/Business Layer</h4><p>it contains :</p><p>1-Entities :These are the core data models of your application</p><p>2-Use Cases :These represent specific actions or operations the app can perform using the entities</p><p>3-Repositories(Abstract Interfaces):These define contracts that the Data Layer must implement. They act as a bridge between the business logic and the external data sources, but without knowing how or where the data is stored.</p><h4>3- Data Layer</h4><p>it contains :</p><p>1-models : These are data structures that represent the raw format of the data (e.g., from a REST API or a database).</p><p>They are often converted or mapped into domain entities to keep the Domain Layer clean and independent.</p><p>2-Repositories (Implementations) : These classes implement the abstract repositories from the Domain Layer and handle the actual data operations.</p><p>3-Data Sources : These are responsible for the actual communication with external systems (e.g., remote APIs, local databases).</p><p>You might have RemoteDataSource for API calls and LocalDataSource for shared preferences.</p><h3>Simple Practical Example:</h3><h4>Folder structure for the Register page using Clean Architecture</h4><pre>lib/<br>├── core/<br>│   └── connection/<br>│   └── errors/<br>│   └── database/<br><br>├── features/<br>│   ├── register/<br>│   │   ├── data/<br>│   │   │   ├── models/<br>│   │   │   │   └── user_register_model.dart<br>│   │   │   ├── datasources/<br>│   │   │   │   └── register_remote_data_source.dart<br>│   │   │   └── repositories/<br>│   │   │       └── register_repository_impl.dart<br>│   │   │<br>│   │   ├── domain/<br>│   │   │   ├── entities/<br>│   │   │   │   └── user_register.dart<br>│   │   │   ├── usecases/<br>│   │   │   │   └── register_user.dart<br>│   │   │   └── repositories/<br>│   │   │       └── register_repository.dart<br>│   │   │<br>│   │   ├── presentation/<br>│   │   │   ├── bloc/<br>│   │   │   │   ├── register_bloc.dart<br>│   │   │   │   ├── register_event.dart<br>│   │   │   │   └── register_state.dart<br>│   │   │   ├── screens/<br>│   │   │   │   └── register_screen.dart<br>│   │   │   └── widgets/<br>│   │   │       ├── register_form.dart<br>│   │   │       └── custom_register_button.dart<br><br>├── main.dart</pre><h4>1-Domain Layer</h4><p>🔹entities/user_register.dart</p><pre>class UserRegister {<br>  final String name;<br>  final String email;<br>  final String password;<br><br>  const UserRegister({<br>    required this.name,<br>    required this.email,<br>    required this.password,<br>  });<br>}</pre><p>🔹repositories/register_repository.dart</p><pre>import &#39;../entities/user_register.dart&#39;;<br><br>abstract class RegisterRepository {<br>  Future&lt;void&gt; registerUser(UserRegister user);<br>}</pre><p>🔹usecases/register_user.dart</p><pre>import &#39;../entities/user_register.dart&#39;;<br>import &#39;../repositories/register_repository.dart&#39;;<br><br>class RegisterUser {<br>  final RegisterRepository repository;<br><br>  RegisterUser(this.repository);<br><br>  Future&lt;void&gt; call(UserRegister user) async {<br>    return await repository.registerUser(user);<br>  }<br>}</pre><h4>2-Data Layer</h4><p>🔹models/user_model.dart(This is the model we receive from the API and pass to the UserRegister entity.)</p><pre>import &#39;../../domain/entities/user_register.dart&#39;;<br><br>class UserModel extends UserRegister {<br>  const UserModel({<br>    required super.name,<br>    required super.email,<br>    required super.password,<br>  });<br><br>  factory UserModel.fromJson(Map&lt;String, dynamic&gt; json) {<br>    return UserModel(<br>      name: json[&#39;name&#39;],<br>      email: json[&#39;email&#39;],<br>      password: json[&#39;password&#39;],<br>    );<br>  }<br><br>  Map&lt;String, dynamic&gt; toJson() {<br>    return {<br>      &#39;name&#39;: name,<br>      &#39;email&#39;: email,<br>      &#39;password&#39;: password,<br>    };<br>  }<br>}</pre><p>🔹datasources/register_remote_data_source.dart(This file is responsible for dealing with the API directly)</p><pre>import &#39;../models/user_model.dart&#39;;<br>import &#39;package:http/http.dart&#39; as http;<br>abstract class RegisterRemoteDataSource {<br>  Future&lt;void&gt; register(UserModel user);<br>}<br><br>class RegisterRemoteDataSourceImpl implements RegisterRemoteDataSource {<br>  @override<br>  Future&lt;void&gt; register(UserModel user) async {<br>   <br>    final response = await http.post(<br>      Uri.parse(&#39;https://your-api-url.com/register&#39;),<br>      body: user.toJson(),<br>    );<br><br>    if (response.statusCode != 200) {<br>      throw Exception(&#39;Registration failed&#39;);<br>    }<br>  }<br>}</pre><p>🔹repositories/register_repository_impl.dart(It is the part that connects the data source and the domain repository)</p><pre>import &#39;../../domain/entities/user_register.dart&#39;;<br>import &#39;../../domain/repositories/register_repository.dart&#39;;<br>import &#39;../datasources/register_remote_data_source.dart&#39;;<br>import &#39;../models/user_model.dart&#39;;<br><br>class RegisterRepositoryImpl implements RegisterRepository {<br>  final RegisterRemoteDataSource remoteDataSource;<br><br>  RegisterRepositoryImpl(this.remoteDataSource);<br><br>  @override<br>  Future&lt;void&gt; registerUser(UserRegister user) async {<br>    final userModel = UserModel(<br>      name: user.name,<br>      email: user.email,<br>      password: user.password,<br>    );<br><br>    await remoteDataSource.register(userModel);<br>  }<br>}</pre><h4>3-Presentation Layer</h4><p>🔹presentation/bloc/register_event.dart</p><pre>abstract class RegisterEvent {}<br><br>class RegisterButtonPressed extends RegisterEvent {<br>  final String name;<br>  final String email;<br>  final String password;<br><br>  RegisterButtonPressed({<br>    required this.name,<br>    required this.email,<br>    required this.password,<br>  });<br>}</pre><p>🔹presentation/bloc/register_state.dart</p><pre>abstract class RegisterState {}<br><br>class RegisterInitial extends RegisterState {}<br><br>class RegisterLoading extends RegisterState {}<br><br>class RegisterSuccess extends RegisterState {}<br><br>class RegisterFailure extends RegisterState {<br>  final String error;<br><br>  RegisterFailure(this.error);<br>}</pre><p>🔹presentation/bloc/register_bloc.dart</p><pre>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br>import &#39;register_event.dart&#39;;<br>import &#39;register_state.dart&#39;;<br>import &#39;../../domain/usecases/register_user.dart&#39;;<br><br>class RegisterBloc extends Bloc&lt;RegisterEvent, RegisterState&gt; {<br>  final RegisterUser registerUser;<br><br>  RegisterBloc({required this.registerUser}) : super(RegisterInitial()) {<br>    on&lt;RegisterButtonPressed&gt;((event, emit) async {<br>      emit(RegisterLoading());<br>      try {<br>        await registerUser(UserRegister(<br>  name: event.name,<br>  email: event.email,<br>  password: event.password,<br>));<br>        emit(RegisterSuccess());<br>      } catch (e) {<br>        emit(RegisterFailure(e.toString()));<br>      }<br>    });<br>  }<br>}</pre><p>🔹presentation/screens/register_screen.dart</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br>import &#39;../bloc/register_bloc.dart&#39;;<br>import &#39;../bloc/register_event.dart&#39;;<br>import &#39;../bloc/register_state.dart&#39;;<br>import &#39;../widgets/register_form.dart&#39;;<br><br>class RegisterScreen extends StatelessWidget {<br>  const RegisterScreen({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(title: const Text(&#39;Register&#39;)),<br>      body: BlocConsumer&lt;RegisterBloc, RegisterState&gt;(<br>        listener: (context, state) {<br>          if (state is RegisterSuccess) {<br>            ScaffoldMessenger.of(context).showSnackBar(<br>              const SnackBar(content: Text(&#39;Registration Successful&#39;)),<br>            );<br>          } else if (state is RegisterFailure) {<br>            ScaffoldMessenger.of(context).showSnackBar(<br>              SnackBar(content: Text(state.error)),<br>            );<br>          }<br>        },<br>        builder: (context, state) {<br>          if (state is RegisterLoading) {<br>            return const Center(child: CircularProgressIndicator());<br>          }<br>          return const RegisterForm();<br>        },<br>      ),<br>    );<br>  }<br>}</pre><p>🔹presentation/widgets/register_form.dart</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br>import &#39;../bloc/register_bloc.dart&#39;;<br>import &#39;../bloc/register_event.dart&#39;;<br><br>class RegisterForm extends StatefulWidget {<br>  const RegisterForm({super.key});<br><br>  @override<br>  State&lt;RegisterForm&gt; createState() =&gt; _RegisterFormState();<br>}<br><br>class _RegisterFormState extends State&lt;RegisterForm&gt; {<br>  final _nameController = TextEditingController();<br>  final _emailController = TextEditingController();<br>  final _passwordController = TextEditingController();<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Padding(<br>      padding: const EdgeInsets.all(16.0),<br>      child: Column(<br>        children: [<br>          TextField(controller: _nameController, decoration: const InputDecoration(labelText: &#39;Name&#39;)),<br>          TextField(controller: _emailController, decoration: const InputDecoration(labelText: &#39;Email&#39;)),<br>          TextField(controller: _passwordController, obscureText: true, decoration: const InputDecoration(labelText: &#39;Password&#39;)),<br>          const SizedBox(height: 20),<br>          ElevatedButton(<br>            onPressed: () {<br>              BlocProvider.of&lt;RegisterBloc&gt;(context).add(<br>                RegisterButtonPressed(<br>                  name: _nameController.text,<br>                  email: _emailController.text,<br>                  password: _passwordController.text,<br>                ),<br>              );<br>            },<br>            child: const Text(&#39;Register&#39;),<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><p>Finally , I hope the article was useful to you and your opinion is very important to me.</p><p><a href="https://www.linkedin.com/in/rwan-hossam-08ba39295?lipi=urn%3Ali%3Apage%3Ad_flagship3_profile_view_base_contact_details%3B2XdLbb8oQnS%2FukucjzryZQ%3D%3D">LinkedIn</a></p><p><a href="http://rwanhossam0@gmail.com/">Email</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1628383582d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>