<?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 RAJAT MANGLA on Medium]]></title>
        <description><![CDATA[Stories by RAJAT MANGLA on Medium]]></description>
        <link>https://medium.com/@mangla.1?source=rss-cac9ccad0f30------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*3NdU7QqrG327mSeZEEEoEw.jpeg</url>
            <title>Stories by RAJAT MANGLA on Medium</title>
            <link>https://medium.com/@mangla.1?source=rss-cac9ccad0f30------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 08:10:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mangla.1/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[The Byte vs Rune Trap in Go String Matching]]></title>
            <link>https://medium.com/@mangla.1/the-byte-vs-rune-trap-in-go-string-matching-15546011823c?source=rss-cac9ccad0f30------2</link>
            <guid isPermaLink="false">https://medium.com/p/15546011823c</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[fuzzy-matching]]></category>
            <dc:creator><![CDATA[RAJAT MANGLA]]></dc:creator>
            <pubDate>Mon, 11 May 2026 15:27:51 GMT</pubDate>
            <atom:updated>2026-05-11T15:27:51.883Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>Case-insensitive string matching looks trivial in Go. It isn’t — not once Unicode enters the picture.</strong></blockquote><p>Most Go developers have written something like this at least once:</p><pre>idx := strings.Index(strings.ToLower(text), strings.ToLower(query))</pre><p>It’s readable. It works in tests. It ships to production. Then one day a user pastes a unit symbol or a name with an unfamiliar character, and your neatly highlighted substring is suddenly off by a character — or pointing into the middle of a multi-byte sequence.</p><p>This article is about why that happens and the pattern that prevents it.</p><h3>The mental model you need first</h3><p>Three facts underpin everything:</p><ul><li>A Go string is a sequence of <strong>bytes</strong>.</li><li>A rune is a <strong>Unicode code point</strong> — the unit of human-readable text.</li><li>s[a:b] slices by <strong>byte offsets</strong>, not rune positions.</li></ul><p>When you transform text — ToLower, ToUpper, normalization — byte lengths can change. A character that takes two bytes might become one, or three. If you compute an index in the <em>transformed</em> string and use it to slice the <em>original</em>, those offsets no longer align.</p><p>That’s the trap: <strong>byte offsets are not text boundaries</strong>.</p><h3>What the naive approach actually does wrong</h3><pre>func highlight(text, query string) string {<br>    if text == &quot;&quot; { return &quot;&quot; }<br>    if query == &quot;&quot; { return &quot;{&quot; + text + &quot;}&quot; }<br><br>    idx := strings.Index(strings.ToLower(text), strings.ToLower(query))<br>    if idx &lt; 0 { return &quot;{&quot; + text + &quot;}&quot; }<br><br>    end := idx + len(query)<br>    if end &gt; len(text) { end = len(text) }<br><br>    return &quot;{&quot; + text[:idx] + &quot;}&quot; + text[idx:end] + &quot;{&quot; + text[end:] + &quot;}&quot;<br>}</pre><p>The bug lives here:</p><pre>idx := strings.Index(strings.ToLower(text), strings.ToLower(query))</pre><p>strings.Index returns a byte offset in the <strong><em>lowercased</em></strong><em> copy</em>. The code then uses that offset to slice the <em>original</em>. For ASCII, byte positions happen to survive lowercasing intact. For Unicode, they don&#39;t.</p><p>A concrete example — the Turkish dotted I (İ, U+0130):</p><pre>text:     &quot;İax&quot;<br>query:    &quot;x&quot;<br>expected: &quot;{İa}x&quot;<br><br><br>Original &quot;İax&quot;:<br>C4 B0  61  78<br>[ İ  ] [a] [x]<br>pos 0  pos 2  pos 3<br><br>After ToLower(&quot;İax&quot;):<br>69  61  78<br>[i] [a] [x]<br>pos 0 pos 1 pos 2</pre><p>This is where the byte math breaks down. İ occupies two bytes in UTF-8 (C4 B0). Lowercasing it produces i — a single byte (69).</p><p>The byte layout shrinks:</p><ul><li>strings.Index finds x at byte offset <strong>2</strong> in the lowercased string</li><li>But byte offset 2 in the <em>original</em> string lands in the middle of İ&#39;s two-byte sequence — not at a, not at x. Go panics or produces a garbled slice.</li></ul><h3>The robust pattern</h3><p>Stop working in byte space. Work in rune space instead:</p><pre>func highlight(text, query string) string {<br>    if text == &quot;&quot; { return &quot;&quot; }<br><br>    wrap := func(s string) string { return &quot;{&quot; + s + &quot;}&quot; }<br>    if query == &quot;&quot; { return wrap(text) }<br><br>    textRunes := []rune(text)<br>    queryRunes := []rune(query)<br>    queryLen := len(queryRunes)<br><br>    if queryLen &gt; len(textRunes) { return wrap(text) }<br><br>    start := -1<br>    for i := 0; i &lt;= len(textRunes)-queryLen; i++ {<br>        if strings.EqualFold(string(textRunes[i:i+queryLen]), query) {<br>            start = i<br>            break<br>        }<br>    }<br><br>    if start == -1 { return wrap(text) }<br><br>    var sb strings.Builder<br>    if start &gt; 0 {<br>        sb.WriteString(wrap(string(textRunes[:start])))<br>    }<br>    sb.WriteString(string(textRunes[start : start+queryLen]))<br>    if start+queryLen &lt; len(textRunes) {<br>        sb.WriteString(wrap(string(textRunes[start+queryLen:])))<br>    }<br><br>    return sb.String()<br>}</pre><p>Three things this gets right:</p><ul><li><strong>Matching via </strong><strong>strings.EqualFold</strong> — Unicode-aware case folding, handles dotted İ, and everything else the standard covers. It doesn&#39;t give you a start index though, which is why we scan windows — EqualFold answers <em>are these equal</em>, not <em>where does this match start</em>.</li><li><strong>Position tracking in rune space</strong> — the loop index i is a rune index, never a byte offset, so it can never land mid-sequence.</li><li><strong>Output slicing on rune boundaries</strong> — slicing textRunes[a:b] then converting back to string guarantees clean boundaries every time.</li></ul><h3>Lock it in with a test table</h3><p>Two Unicode rows are cheap insurance against the most common regression: someone simplifying the logic back to byte-index arithmetic, all tests passing, Unicode silently broken.</p><pre>func TestHighlight(t *testing.T) {<br>    cases := []struct {<br>        name, text, query, expected string<br>    }{<br>        {&quot;ASCII basic&quot;, &quot;Cheese Pizza&quot;, &quot;pizza&quot;, &quot;{Cheese }Pizza&quot;},<br>        {&quot;German sharp S&quot;, &quot;straßenax&quot;, &quot;x&quot;, &quot;{straßena}x&quot;},<br>        {&quot;Unicode dot I&quot;, &quot;İaX&quot;, &quot;x&quot;, &quot;{İa}X&quot;},<br>    }<br><br>    for _, tc := range cases {<br>        t.Run(tc.name, func(t *testing.T) {<br>            got := highlight(tc.text, tc.query)<br>            if got != tc.expected {<br>                t.Errorf(&quot;got %q, want %q&quot;, got, tc.expected)<br>            }<br>        })<br>    }<br>}</pre><p>The ASCII case passes with either approach. The Unicode cases won’t pass with byte-index logic — which is exactly the point.</p><p>This bug class is invisible in typical test suites and surfaces only when Unicode case folding shifts byte alignment enough to cause drift. The same pattern applies anywhere you match text and then slice it — autocomplete labeling, search emphasis, parser token alignment.</p><p>In all of these, the rule is the same:</p><p><strong>Compare with </strong><strong>EqualFold. Track positions in rune space. Slice on rune boundaries.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15546011823c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes: A high level view]]></title>
            <link>https://medium.com/@mangla.1/kubernetes-a-high-level-view-e983a6fb32b1?source=rss-cac9ccad0f30------2</link>
            <guid isPermaLink="false">https://medium.com/p/e983a6fb32b1</guid>
            <category><![CDATA[kubernetes-cluster]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[RAJAT MANGLA]]></dc:creator>
            <pubDate>Wed, 29 Apr 2026 18:05:00 GMT</pubDate>
            <atom:updated>2026-04-29T18:05:00.077Z</atom:updated>
            <content:encoded><![CDATA[<h3>Context</h3><p>Kubernetes (K8S) is an open-source container orchestration platform originally developed by Google and now maintained by CNCF.</p><h3>Kubernetes:</h3><p>Kubernetes is a <strong>container orchestration platform</strong> — it manages where and how your containerized apps run across a fleet of machines. The entire system is called a <strong>cluster</strong>, which has two kinds of machines:</p><ul><li><strong>Control Plane</strong> — the brain. It makes decisions: schedule this pod here, restart that container, scale this deployment up.</li><li><strong>Worker Nodes</strong> — the muscle. They actually run your application workloads.</li></ul><h3>Here’s the architecture:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Fjk720UeOzA7JWuC" /></figure><h3>What is a Node?</h3><p>A <strong>node</strong> is simply a machine — physical or virtual — in your cluster that runs workloads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kVO2t5EqMimHJv_r" /></figure><p>Each worker node has three essential components:</p><h4><strong>kubelet</strong> — the node&#39;s agent.</h4><ol><li>The kubelet is a process that runs directly on the host OS (<strong>not in a container</strong>). It is the <strong>only</strong> Kubernetes component that runs natively on the node, and it has one job: make sure the containers described for this node are running and healthy.</li></ol><p>Here’s its loop:</p><ul><li>It registers the node with the API server on startup</li><li>It watches the API server for Pod objects assigned to its node</li><li>For each pod, it instructs the container runtime to pull images and start containers</li><li>It continuously monitors those containers and reports status back to the API server</li><li>If a container crashes, the kubelet restarts it (based on the pod’s restartPolicy)</li><li>It also runs <strong>liveness</strong> and <strong>readiness probes</strong> — regularly checking if containers are alive and ready to serve traffic</li></ul><blockquote>The kubelet does <em>not</em> manage containers it didn’t create. If you start a container manually with docker run on a node, the kubelet ignores it entirely.</blockquote><h4><strong>kube-proxy</strong> — the network rules manager</h4><p>kube-proxy runs on every node and is responsible for implementing Kubernetes Services.</p><ul><li>When you create a Service (a stable virtual IP for a group of pods), kube-proxy ensures that traffic hitting that IP gets forwarded to the right pods — even as pods come and go.</li><li>It does this by programming the Linux kernel’s iptables (or ipvs in newer setups) with forwarding rules. It watches the API server for Service and Endpoint changes and keeps those rules up to date.</li></ul><blockquote>A key thing to understand: kube-proxy handles <strong>east-west</strong> traffic (pod-to-pod, pod-to-service within the cluster).</blockquote><blockquote>It doesn’t handle traffic coming in from outside — that’s the job of an Ingress controller or LoadBalancer.</blockquote><h4><strong>Container runtime</strong> — the engine that actually runs containers</h4><ol><li>The kubelet doesn’t know how to run containers itself.</li><li>It delegates that work to a container runtime via a standard interface called the <strong>CRI</strong> (Container Runtime Interface).</li></ol><p>The two most common runtimes today are:</p><ol><li>containerd — the default in most Kubernetes distributions (it&#39;s what Docker itself uses under the hood)</li><li>CRI-O — a lightweight runtime purpose-built for Kubernetes</li></ol><p>The runtime’s job is to pull images from a registry, unpack them, and run containers using the <strong>OCI</strong> (Open Container Initiative) spec — setting up the Linux namespaces (pid, net, mnt, uts) and cgroups that isolate each container.</p><h3>How they work together — a concrete example</h3><p>When you run kubectl apply -f pod.yaml:</p><ol><li>The API server stores the Pod object in etcd with no nodeName yet</li><li>The scheduler picks a node and writes nodeName: worker-1 onto the pod</li><li>The kubelet on worker-1 sees this pod appear in its watch</li><li>The kubelet calls the container runtime (containerd) via CRI: <em>“pull this image and start this container”</em></li><li>containerd pulls the image, creates the container with proper namespaces/cgroups</li><li>The kubelet monitors the container and updates the pod’s status back to the API server</li><li>kube-proxy sees any service changes and updates iptables rules so traffic can reach the pod</li></ol><h3>What is a Pod?</h3><p>A Pod is the <strong>smallest deployable unit in Kubernetes</strong> — but it’s not a container. It’s a <em>wrapper around one or more containers</em> that share certain Linux namespaces.</p><p>The key insight is:</p><blockquote><em>Containers inside a pod share the same network and IPC namespace, but each has its own filesystem.</em></blockquote><ul><li>This is what makes a pod feel like a “logical host” — the containers inside it can talk to each other on localhost, see each other&#39;s processes (if pid namespace is shared), and share mounted volumes.</li></ul><blockquote><em>Because of the shared network namespace, two containers in a pod must not bind to the same port — they’d conflict with, just like two processes on the same host.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1-NqyWn8wBamz1Nb" /></figure><blockquote>The pause container you can see is a tiny do-nothing process that exists for one purpose — to <strong>hold the network and IPC namespaces</strong> for the pod&#39;s lifetime.</blockquote><h4>Pod lifecycle</h4><p>A pod moves through these phases:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0NdkwVdHwHZ7CTCk" /></figure><h3>Probes — how Kubernetes knows a container is healthy</h3><p>The kubelet runs three types of probes against your containers:</p><ol><li><strong>Liveness probe</strong> — “Is this container still alive?” If it fails, the kubelet kills and restarts the container. Use this to recover from deadlocks — situations where the process is running but stuck on something.</li><li><strong>Readiness probe</strong> — “Is this container ready to serve traffic?” If it fails, the pod is removed from the Service’s endpoints. Traffic stops being sent to it, but the container is <em>not</em> restarted. Use this during startup or when temporarily overloaded.</li><li><strong>Startup probe</strong> — “Has this container finished starting up?” Designed for slow-starting apps. While the startup probe is running, liveness and readiness probes are disabled. Once it passes, the other probes take over.</li></ol><blockquote>Each probe can be implemented as an HTTP GET, a TCP socket check, or a shell command exec inside the container.</blockquote><h3>restartPolicy — what happens when a container dies</h3><p>Every pod has a restartPolicy that tells the kubelet what to do when a container exits:</p><ul><li>Always (default) — restart no matter what. Good for long-running services.</li><li>OnFailure — restart only if the exit code is non-zero. Good for batch jobs.</li><li>Never — don&#39;t restart. Run once and done.</li></ul><p>Restarts use <strong>exponential backoff</strong> — 10s, 20s, 40s… up to 5 minutes between attempts. This is what you see as CrashLoopBackOff — the pod keeps failing and the kubelet keeps backing off before retrying.</p><h3>Control plane</h3><ul><li>The key insight here: <strong>everything goes through the API server</strong>.</li><li>No component talks directly to another — etcd, the scheduler, and the controller manager all communicate exclusively via the API server.</li><li>The API server is also the only component that reads and writes to the etcd (key-value store).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oxkCEXYWBdMwWHa5" /></figure><p>Now let’s look at how these four components actually work together when something happens — this is the reconciliation loop, the heartbeat of Kubernetes.</p><p>The flow when you run kubectl apply -f deployment.yaml:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eDNzTc0aFEreq_m2" /></figure><p>Let’s walk through each component’s role:</p><h3>API server</h3><p>is stateless and fronts everything.</p><p>When a request arrives, it runs it through three gates:</p><ul><li>authentication (who are you?),</li><li>authorization (are you allowed to do this?),</li><li>and admission controllers (is this request valid/safe — e.g. does it meet resource quota?).</li></ul><blockquote>Only then does it write to etcd. It also serves a long-poll /watch endpoint — this is how every other component gets notified of changes without polling.</blockquote><h3>etcd</h3><p>stores the entire cluster state as key-value pairs under /registry/....</p><ul><li>Every kubectl apply, every API call, every change to your cluster state ultimately flows through etcd.</li><li>It uses the <strong>Raft consensus algorithm</strong>, so in a production HA setup with 3 or 5 etcd nodes, a write is only acknowledged once a quorum agrees.</li></ul><blockquote>If etcd goes down, the cluster can still <em>run</em> existing workloads, but nothing new can be scheduled and no state changes are accepted.</blockquote><h3>Controller manager</h3><p>is a single binary running ~30 control loops concurrently.</p><p>Each controller watches a specific resource type and reconciles the actual vs desired state.</p><ul><li>The Deployment controller sees a new Deployment → creates a ReplicaSet.</li><li>The ReplicaSet controller sees the ReplicaSet → creates Pod objects.</li><li>The node controller watches for nodes that stop sending heartbeats and marks them NotReady.</li></ul><p>Every controller is a loop of: <em>observe → diff → act</em>.</p><h3>Scheduler</h3><p>watches the API server for pods with nodeName: &quot;&quot; (unscheduled).</p><ol><li>When it sees one, it runs two phases — <em>filter</em> (which nodes are even eligible? e.g. enough CPU/memory, matching nodeSelector, taints/tolerations) and <em>score</em> (of the eligible ones, which is best? least loaded, image locality, spread rules).</li><li>It then writes the chosen node name back to the pod object via the API server.</li></ol><p><strong>That’s all it does — it never talks to the kubelet.</strong></p><p>The mental model that makes everything click: <strong>Kubernetes components don’t call each other — they all react to state changes in the etcd via the API server’s watch mechanism.</strong></p><p>The scheduler doesn’t tell the kubelet to start a pod.</p><ul><li>It writes a node name onto a pod object.</li><li>The kubelet, watching for pods with its node name, then independently picks that up and starts the container.</li><li>This is what makes the system so resilient — any component can crash and restart without losing work.</li></ul><h3>Code Simulation:</h3><pre># 1. confirm orbstack kubernetes is running<br>kubectl cluster-info<br># 2. build your image into the orbstack docker context<br># (run from the directory containing your Dockerfile)<br>docker build -t k8s-demo:latest .<br>docker build -t k8s-demo:v2.0.0 .<br># 3. apply manifests<br>kubectl apply -f deployment.yaml<br>kubectl apply -f service.yaml<br># 4. watch pods come up in real time<br># Watch readiness during the 10s boot window<br>kubectl get pods -w<br># You&#39;ll see READY 0/1 for ~10s then flip to 1/1<br># Once all 3 pods are 1/1 Running, <br># Open a second terminal and run this to watch the Endpoints object live<br>kubectl get endpoints k8s-demo-service -w<br><br>kubectl get pods -o wide<br><br># Hit dep-down on one pod — target a specific pod<br># option 1: port forward<br>kubectl port-forward pod/&lt;pod-name&gt; 9090:8080<br>curl localhost:9090/dep-down<br># option 2: use pod-ip<br>curl 192.168.194.52:8080/dep-up<br># Watch that pod drop out of Endpoints - traffic reroutes to other 2<br>kubectl get endpoints k8s-demo-service -w<br># Recover it<br>curl localhost:9090/dep-up<br><br>curl 192.168.194.52:8080/kill<br># Watch restartCount increment<br>kubectl get pods -w<br># Pod stays, container restarts, restartCount goes to 1<br># Loop requests — you&#39;ll see different Pod hostnames responding<br>for i in $(seq 1 10); do curl localhost:30007; done</pre><h3>EXTRAS:</h3><pre>kubectl describe pod &lt;pod-name&gt;<br># Look at the Events section at the bottom — you&#39;ll see probe history<br><br>## kube-system containers<br>kubectl get pods -n kube-system<br><br>## etcd<br># See the raw etcd key for your deployment<br>kubectl get deployment k8s-demo -o json<br><br># See the raw pod objects<br>kubectl get pods -o json<br><br># See what&#39;s stored for your service<br>kubectl get service k8s-demo-service -o json<br><br>### Rollout commands<br># Check rollout status<br>kubectl rollout status deployment/k8s-demo<br><br># View revision history<br>kubectl rollout history deployment/k8s-demo<br><br># Roll back to previous version<br>kubectl rollout undo deployment/k8s-demo<br><br># Roll back to a specific revision<br>kubectl rollout undo deployment/web-app --to-revision=3</pre><p><strong>Key behaviours:</strong></p><ul><li>Old ReplicaSets are kept at 0 replicas after a rollout — retained for rollback (revisionHistoryLimit, default: 10).</li><li>Recreate strategy terminates all old pods before starting new ones — This causes downtime but avoids running two versions simultaneously.</li><li>RollingUpdate (default) keeps the app live throughout — tuned via maxSurge and maxUnavailable.</li></ul><h3>Horizontal Pod Autoscaler (HPA)</h3><p>An <strong>HPA</strong> automatically scales the number of pod replicas in a Deployment (or ReplicaSet/StatefulSet) based on observed metrics — typically CPU or memory utilisation, but also custom metrics via the Metrics API.</p><p>The HPA controller runs a control loop (default: every 15 seconds) that reads current metrics and adjusts the replica count to keep utilisation at the target.</p><p><strong>How it works:</strong></p><p>desired replicas = ceil(current replicas × (current metric / target metric))</p><p>For example: 3 pods at 80% CPU, target is 50% → ceil(3 × 80/50) = 5 pods.</p><h3>Questions:</h3><p>By default, how many pods can you run per node in Kubernetes?</p><p>Can two containers in the same pod bind to the same port?</p><p>Ans: NO</p><p>When you access an app in K8s, what routes the HTTP request?</p><ol><li>A — Ingress</li><li>B — LoadBalancer</li></ol><p>You’re asked to deploy an app that should automatically run on every new node added to the cluster. Which resource would you choose?</p><ol><li>A : Deployment</li><li>B : StatefulSet</li><li>C : DaemonSet</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e983a6fb32b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Go Slices Through a Backtracking Example]]></title>
            <link>https://medium.com/@mangla.1/understanding-go-slices-through-a-backtracking-example-505e95480eea?source=rss-cac9ccad0f30------2</link>
            <guid isPermaLink="false">https://medium.com/p/505e95480eea</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[go-slices]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[RAJAT MANGLA]]></dc:creator>
            <pubDate>Wed, 25 Feb 2026 03:35:31 GMT</pubDate>
            <atom:updated>2026-02-25T03:35:31.757Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stack vs Heap, Append, Copy, and the Bugs You Don’t See Coming</h3><p>Most Go developers learn early that:</p><blockquote><em>“Slices are passed by value.”</em></blockquote><p>But then they write a recursive backtracking algorithm…<br> …and everything breaks.</p><p>Let’s use a classic example — generating subsets — to deeply understand:</p><ul><li>What a slice really is</li><li>Where data lives (stack vs heap)</li><li>What append actually does</li><li>Why copying is sometimes mandatory</li><li>And how subtle bugs happen</li></ul><h3>The Backtracking Example</h3><p>Here’s a standard subsets implementation:</p><pre>func subsets(nums []int) [][]int {<br> result := [][]int{}<br> subset := []int{}<br><br> var backtrack func(int)<br> backtrack = func(start int) {<br>  tmp := make([]int, len(subset))<br>  copy(tmp, subset)<br>  result = append(result, tmp)<br><br>  for i := start; i &lt; len(nums); i++ {<br>   subset = append(subset, nums[i])<br>   backtrack(i + 1)<br>   subset = subset[:len(subset)-1] // backtrack<br>  }<br> }<br><br> backtrack(0)<br> return result<br>}</pre><p>Looks simple.</p><p>But this function depends entirely on how slices behave in memory.</p><p>Let’s break it down.</p><h3>What a Slice Actually Is</h3><p>A slice is not an array.</p><p>Internally, a slice is a small struct:</p><pre>type slice struct {<br>	ptr *T<br>	len int<br>	cap int<br>}</pre><p>That’s it.</p><p>So when you pass a slice to a function, Go copies only:</p><ul><li>The pointer</li><li>The length</li><li>The capacity</li></ul><p>The underlying array is NOT copied.</p><h3>Stack vs Heap — Where Does Data Live?</h3><h4>On the Stack</h4><p>Each recursive call stores:</p><ul><li>subset (slice header only)</li><li>start</li><li>return address</li></ul><p>That’s tiny.</p><p>Each frame holds roughly 24 bytes for the slice header (on 64-bit systems).</p><p>So recursion depth = n<br>Stack memory = O(n)</p><p>Very small.</p><h4>On the Heap</h4><p>The actual array data lives on the heap.</p><p>Every time we:</p><pre>subset = append(subset, nums[i])</pre><p>we may:</p><ul><li>Reuse the same backing array</li><li>Or allocate a new one (if capacity exceeded)</li></ul><p>And every time we do:</p><pre>tmp := make([]int, len(subset))<br>copy(tmp, subset)</pre><p>We allocate a brand new array on the heap.</p><p>The real memory cost comes from:</p><pre>O(n * 2^n)</pre><p>Because we store every subset.</p><h3>Why We Must Copy Before Saving</h3><p>Consider removing this:</p><pre>tmp := make([]int, len(subset))<br>copy(tmp, subset)</pre><p>And instead writing:</p><pre>result = append(result, subset)</pre><p>That introduces a bug.</p><p>Why?</p><p>Because multiple recursive calls may share the same backing array.</p><p>If later the slice changes, all saved results change too.</p><p>You didn’t copy the data — you copied the pointer to it.</p><h3>The Critical Distinction</h3><p>There are two kinds of operations on slices:</p><h4>1️⃣ Changing the slice header</h4><pre>subset = append(subset, x)<br>subset = subset[:len(subset)-1]</pre><p>These change:</p><ul><li>len</li><li>cap</li><li>possibly ptr (if reallocated)</li></ul><p>These affect only that slice header.</p><h4>2️⃣ Changing the backing array</h4><pre>subset[0] = 99</pre><p>This modifies the actual array in memory.</p><p>If multiple slices share that array, they all see the change.</p><p>This is where most subtle bugs happen.</p><h3>Why Backtracking Requires “Removal”</h3><p>Notice this line:</p><pre>subset = subset[:len(subset)-1]</pre><p>Why is it necessary?</p><p>Because in the loop-based backtracking pattern, we reuse the same slice across iterations.</p><p>If we don’t shrink the slice, the next loop iteration will continue growing from the previous state.</p><p>In contrast, the include/exclude recursion pattern doesn’t always require explicit removal because each branch works with a different slice header copy.</p><p>Understanding that difference requires understanding slice headers vs arrays.</p><h3>The Classic Slice Bug</h3><p>Consider:</p><pre>s := make([]int, 0, 2)<br><br>s1 := append(s, 1)<br>s2 := append(s, 2)<br><br>fmt.Println(s1, s2)</pre><p>What prints?</p><pre>[2] [2]</pre><p>Why?</p><p>Because:</p><ul><li>s has len=0</li><li>Both appends write at index 0</li><li>Both slices share the same backing array</li><li>The second append overwrites the first</li></ul><p>This is not obvious unless you understand how slices work.</p><h3>Append: When Does It Allocate?</h3><p>Append allocates a new backing array only when:</p><pre>len == cap</pre><p>Otherwise, it reuses the existing array.</p><p>This is why recursive algorithms can accidentally share memory across branches.</p><h3>Mental Model That Makes It Click</h3><p>Think of:</p><ul><li>The backing array = a whiteboard</li><li>The slice header = a window showing part of the whiteboard</li></ul><p>Appending:</p><ul><li>Writes on the whiteboard</li><li>Expands the window</li></ul><p>Reslicing:</p><ul><li>Shrinks the window</li></ul><p>Index assignment:</p><ul><li>Erases part of the whiteboard</li></ul><p>Copying:</p><ul><li>Gives you a new whiteboard</li></ul><p>If two windows point to the same whiteboard, they see the same writing.</p><h3>What About Memory Growth?</h3><p>When we pass a slice by value:</p><ul><li>Only 3 words are copied</li><li>Not the entire array</li></ul><p>So passing slices is cheap.</p><p>The real memory usage comes from:</p><ul><li>Allocating new backing arrays</li><li>Storing results long-term</li><li>Garbage collector pressure</li></ul><p>Stack usage is minimal.<br> Heap usage dominates.</p><h3>Why This Matters in Real Systems</h3><p>Understanding this affects:</p><ul><li>Recursive algorithms</li><li>Concurrent code</li><li>Caching layers</li><li>Returning slices from repository functions</li><li>Avoiding unnecessary allocations</li><li>Debugging strange data corruption bugs</li></ul><p>Most slice-related production bugs are not syntax mistakes — they are memory model misunderstandings.</p><h3>Final Takeaways</h3><ol><li>A slice is a header, not the data.</li><li>Passing slices copies the header, not the array.</li><li>append may or may not allocate.</li><li>Index assignment always modifies shared memory.</li><li>Always copy slices before storing them long-term.</li><li>Stack memory is small and linear. Heap memory dominates.</li></ol><p>If you understand this deeply, backtracking bugs disappear.</p><p>And more importantly — so do subtle production slice bugs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=505e95480eea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Confusing case of go slices]]></title>
            <link>https://medium.com/@mangla.1/the-confusing-case-of-go-slices-4596f6d85a58?source=rss-cac9ccad0f30------2</link>
            <guid isPermaLink="false">https://medium.com/p/4596f6d85a58</guid>
            <category><![CDATA[go-slices]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[RAJAT MANGLA]]></dc:creator>
            <pubDate>Sun, 29 Jun 2025 14:17:16 GMT</pubDate>
            <atom:updated>2025-06-29T14:17:16.959Z</atom:updated>
            <content:encoded><![CDATA[<p>A <strong>slice</strong> in Golang is a <strong>flexible, dynamically-sized view into the elements of an array</strong>. Unlike arrays, slices do not own the data they contain — they simply reference a portion of an underlying array.</p><p>A slice is internally represented by a small data structure containing:</p><ul><li>A <strong>pointer</strong> to the underlying array</li><li>A <strong>length</strong> (number of elements in the slice)</li><li>A <strong>capacity</strong> (maximum size from the starting element to the end of the array)</li></ul><p>Most of us while working with slice can make mistakes on this understanding that “slices are reference types”.</p><p>While I was working on a LeetCode problem given <a href="https://leetcode.com/problems/combination-sum">here</a>, I run into a similar situation after writing the solution as below:</p><pre>func findSum(uniqCombination, candidates []int, idx, total, target int, ans *[][]int) {<br> if total &gt; target || idx &gt;= len(candidates) {<br>  return<br> }<br><br> if total == target {<br>  *ans = append(*ans, uniqCombination)<br>  return<br> }<br><br> uniqCombination = append(uniqCombination, candidates[idx])<br> // consider the curr number<br> findSum(uniqCombination, candidates, idx, total+candidates[idx], target, ans)<br><br> // backtrack<br> findSum(uniqCombination[:len(uniqCombination)-1], candidates, idx+1, total, target, ans)<br>}<br><br>func combinationSum(candidates []int, target int) [][]int {<br> var ans [][]int<br> findSum([]int{}, candidates, 0, 0, target, &amp;ans)<br> return ans<br>}</pre><p>Even though the logical solution written above is correct but there is a problem in that which might not occur with other languages.</p><p>Try running it with the below inputs and it will produce incorrect results</p><pre>func main() {<br> candidates := []int{2, 3, 5}<br> target := 8<br> fmt.Println(combinationSum(candidates, target))<br>}</pre><p>The issue in the above solution is basically which i said initially. In Go, slices are reference types.</p><ul><li>If you append the same slice (<strong>uniqCombination</strong>) to your answer list (<strong>ans</strong>) multiple times without making a copy, all entries in ans will point to the same underlying array.</li><li>As you backtrack and modify <strong>uniqCombination</strong>, all previously stored combinations in ans will also change.</li></ul><p>Now a simple solution to rectify this problem is:</p><pre>// Make a copy to avoid referencing the same slice<br>  comb := make([]int, len(uniqCombination))<br>  copy(comb, uniqCombination)<br>  *ans = append(*ans, comb)</pre><p>Making a copy ensures each combination stored in <strong>ans</strong> is independent and won’t be affected by further changes to <strong>uniqCombination</strong>. This preserves the correct results for each unique combination found during backtracking.</p><p><strong>More takeaways:</strong></p><p>Does append always create a copy and then return?</p><ul><li>No, append does not always create a copy. If the slice has enough capacity, append just reslices the existing underlying array and returns a new slice header. Only when there is not enough capacity, append allocates a new underlying array, copies the elements, and returns a new slice referencing this new array.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4596f6d85a58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Test-Driven Development]]></title>
            <link>https://medium.com/@mangla.1/test-driven-development-abfdfdde53ed?source=rss-cac9ccad0f30------2</link>
            <guid isPermaLink="false">https://medium.com/p/abfdfdde53ed</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[gojek-bootcamp]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[RAJAT MANGLA]]></dc:creator>
            <pubDate>Sun, 11 Aug 2019 10:42:55 GMT</pubDate>
            <atom:updated>2019-08-11T10:42:55.277Z</atom:updated>
            <content:encoded><![CDATA[<p>Since I have been working in tech where the emphasis is to follow TDD when developing a Product, this blog is about my thoughts on TDD.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*wuIKhU8O2D8cWrhc2cpyuA.jpeg" /></figure><p>According to <a href="https://en.wikipedia.org/wiki/Test-driven_development">Wikipedia</a>, <strong>TDD</strong> is a <a href="https://en.wikipedia.org/wiki/Software_development_process">software development process</a> that relies on the repetition of a very short development cycle.</p><p>First, the requirements are turned into very specific test cases, then the software is written so that only the specified tests pass. We have to write minimal code to pass the test cases and finally refactor the code to acceptable standards. The steps generally followed are:</p><ul><li><em>Write a test according to requirements,</em></li><li><em>Run the program and see if it fails,</em></li><li><em>Write code to pass the tests,</em></li><li><em>Refactor according to standards and Repeat the Cycle</em></li></ul><p>If you need more clarity on TDD and some examples, Read <a href="https://www.eecs.yorku.ca/course_archive/2003-04/W/3311/sectionM/case_studies/money/KentBeck_TDD_byexample.pdf">Test Driven Development: By Example by Kent Beck</a></p><h4>Basic example to understand TDD</h4><p>Let’s say you have to program a <strong>calculator</strong> with a feature for adding two numbers and giving the output. Then according to the requirements, our first test for the functionality <strong>addition</strong> would be:</p><pre><strong>import static </strong>org.junit.Assert.<em>assertEquals</em>;<br><strong>import </strong>org.junit.Test;<br><br><strong>public class </strong>CalculatorTest {<br>    @Test<br>    <strong>public void </strong>shouldReturnThreeOnAddition(){<br>        Calculator testCalculator = <strong>new </strong>Calculator(1, 2);<br>        <em>assertEquals</em>(3, testCalculator.addition());<br>    }<br>}</pre><p>To make the test pass, the code required would be:</p><pre><strong>public class </strong>Calculator {<br>    <strong>public </strong>Calculator(<strong>int </strong>first_number, <strong>int </strong>second_number) {}<br><br>    <strong>public int </strong>addition() {<br>        <strong>return </strong>3;<br>    }<br>}</pre><p>Now if we add another test such as:</p><pre>@Test<br><strong>public void </strong>shouldReturnFiveOnAddition() {<br>    Calculator testCalculator = <strong>new </strong>Calculator(2, 3);<br>    <em>assertEquals</em>(5, testCalculator.addition());<br>}</pre><p>The corresponding code to make both test cases pass would be:</p><pre><strong>public class </strong>Calculator {<br>    <strong>private int </strong>first_number;<br>    <strong>private int </strong>second_number;<br>    <br>    <strong>public </strong>Calculator(<strong>int </strong>first_number, <strong>int </strong>second_number) {<br>        <strong>this</strong>.first_number<strong> </strong>= first_number;<br>        <strong>this</strong>.second_number<strong> </strong>= second_number;<br>    }<br><br>    <strong>public int </strong>addition() {<br>        <strong>return </strong>first_number<strong> </strong>+ second_number;<br>    }<br>}</pre><p>Now, we can follow similar steps to meet other requirements as per specifications.</p><p>There are various aspects to using test-driven development, for example, the principles of “keep it simple, stupid” (<a href="https://en.wikipedia.org/wiki/KISS_principle">KISS</a>) and “You aren’t gonna need it” (<a href="https://en.wikipedia.org/wiki/You_aren&#39;t_gonna_need_it">YAGNI</a>).</p><blockquote>In <em>Test-Driven Development by Example</em>, Kent Beck also suggests the principle “<a href="https://en.wikipedia.org/wiki/Fake_it_till_you_make_it">Fake it till you make it</a>”.</blockquote><p>By focusing on writing only the code necessary to pass tests, designs can often be cleaner and clearer than it is achieved by other methods.</p><p><strong>Every test case fails initially:</strong> This ensures that the test really works and can catch an error. Once this is shown, the underlying functionality can be implemented. This has led to the “<em>test-driven development mantra</em>”, which is “<em>red/green/refactor</em>”, where red means <strong><em>fail</em></strong> and green means <strong><em>pass</em></strong>. Test-driven development constantly repeats the steps of adding test cases that fail, passing them, and refactoring.</p><h4>TDD and Unit Testing</h4><p>Lot of us are sometimes confused between TDD and Unit testing, an answer on StackExchange states:</p><blockquote><em>Unit Testing</em> refers to <em>what</em> you are testing, <em>TDD</em> to <em>when</em> you are testing.</blockquote><p>Unit Testing means, testing individual units of behavior. An individual unit of behavior is the smallest possible unit of behavior that can be individually tested in isolation.</p><blockquote>You can write unit tests before you write your code or after you write your code or maybe while you write your code.</blockquote><p>TDD means letting your tests drive your development (and your design). You can do that with unit tests, functional tests, and acceptance tests. Usually, you use all three.</p><p>So, this was my understanding of TDD, I will write more on this as I progress and understand better. To get a better understanding of Development practices, one should always practice it rather than just following articles and textbooks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abfdfdde53ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[4 Days into Bootcamp]]></title>
            <link>https://medium.com/@mangla.1/4-days-into-bootcamp-30c20eed5c16?source=rss-cac9ccad0f30------2</link>
            <guid isPermaLink="false">https://medium.com/p/30c20eed5c16</guid>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[gojek-bootcamp]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[gojek]]></category>
            <category><![CDATA[bootcamp]]></category>
            <dc:creator><![CDATA[RAJAT MANGLA]]></dc:creator>
            <pubDate>Thu, 08 Aug 2019 18:25:25 GMT</pubDate>
            <atom:updated>2019-08-11T10:49:05.098Z</atom:updated>
            <content:encoded><![CDATA[<p>Four Days have already passed into the Bootcamp (Gojek), Me and other participants (around 21) working as a team is still not able to pass a single step which shows there is a lot to learn and perform in a better way.</p><p>Bootcamp drills you towards learning basics of the basic, which even a software engineer having an experience of more than five years may not have the idea of these.</p><p>Humans have a mindset of not being proven wrong in any situation, but these four days have changed my thinking to value other’s suggestions, accept my mistakes and a lot more. When you work in a team, it becomes essential to value other’s opinion and follow.</p><h4>My Key takeaways in these fours days are:</h4><ul><li><em>Make your point always clear with some clear facts or logic:</em> When you are working in a professional ecosystem, it becomes really important to state your argument in a crisp and clear way so that people follow what you are stating or else there is n number of interpretations possible.</li><li><em>Never love your code:</em> Never love what you have coded otherwise you will never be able to write better code than your previous one, it will stop you from evolving. Always think of a better design than your previous one. Don’t hesitate to do <strong><em>rm -rf </em></strong>if your code is not following the defined conventions and rules.</li><li><em>Conventions:</em> Conventions are fundamental whenever you are working on any project or as a team. It’s essential to draw your conventions first and reach a common consensus. Whether it’s related to structuring the program or a git commit, conventions are really important to have consistency across the team.</li><li><em>TDD: </em>While doing TDD, you understand why even a single step becomes crucial and drive your program, why tests are essential for an application. Only write a <strong>minimal</strong> code at each level which should make the tests run, and no code deletion should make the tests run.</li><li><em>Refactoring: </em>It is a part of TDD and a disciplined technique for restructuring an existing body of code. While refactoring only the implementation of the logic may change, but the <strong>contract</strong> should always remain the same — Many people have a wrong understanding of Refactoring.</li><li><em>Simple English Modeling:</em> As a part of TDD, it becomes really important to design your tests in a simple English model as it clearly expresses the behavior and flow of the program.</li></ul><p>There are many other learnings such as always following the <strong>Non-negotiable etiquettes</strong> in your code and then proceed further, Why there is a new line at the EOF and a lot more to talk about.</p><p>Bootcamp is shaping us to work in a professional ecosystem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30c20eed5c16" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CODE COMPLETE — Good Programming Practices]]></title>
            <link>https://medium.com/@mangla.1/code-complete-good-programming-practices-ff32d13892db?source=rss-cac9ccad0f30------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff32d13892db</guid>
            <category><![CDATA[code-complete]]></category>
            <category><![CDATA[books]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[RAJAT MANGLA]]></dc:creator>
            <pubDate>Sat, 03 Aug 2019 19:16:14 GMT</pubDate>
            <atom:updated>2019-08-03T19:16:14.785Z</atom:updated>
            <content:encoded><![CDATA[<h3>CODE COMPLETE — Good Programming Practices</h3><p>A short description of the Code Complete Book by Steve McConnell, Writing it from a recent graduate perspective.</p><p>A recent graduate is often rich in theoretical knowledge but poor in the practical knowledge — how that goes into building production programs. The practical lore of good coding is often passed down slowly in the ritualistic tribal dances of software architects, project leads, analysts, and more experienced programmers. Even more often, it’s the product of the individual programmer’s trials and errors. This book is an alternative to the slow workings of the traditional intellectual potlatch. It pulls together the helpful tips and effective development strategies previously available mainly by hunting and gathering from other people’s experience. It’s a hand up for the student making the transition from an academic environment to a professional one.</p><p>Software Construction is a really complicated process, below figure depicts the different tasks involved in the construction of software.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*ngo6qAXqVQpvSyVrrooxdw.png" /><figcaption>Illustrates construction’s place related to other software development activities. (Code Complete Book — Page 4)</figcaption></figure><h3>Measure Twice, Cut Once: Upstream Prerequisites</h3><p>It discusses the software equivalent of blueprints and construction permits.</p><p><strong><em>Preparation —</em></strong></p><ul><li>No matter what the project, the <strong>preparation</strong> is tailored to the project-specific needs and done conscientiously before construction begins. To further elaborate on this, Testing can’t detect a flaw such as building the wrong product or building the right product in the wrong way. Such flaws must be worked out earlier than in testing — before construction begins. The key point here is — If you emphasize quality in the middle of the project, you emphasize construction practices. Such practices are the focus of most of this book.</li><li>The overarching goal of <strong>preparation</strong> is risk reduction: a good project planner clears major risks out of the way as early as possible so that the bulk of the project can proceed as smoothly as possible</li></ul><p><strong>Problem-Definition Prerequisite —</strong></p><ul><li>The <strong>first prerequisite</strong> you need to fulfill before beginning construction is a clear statement of the problem that the system is supposed to solve. This is sometimes called “product vision,” “vision statement,” “mission statement,” or “product definition.” Here it’s called “problem definition.”</li></ul><p><strong>Architecture Prerequisite —</strong></p><ul><li>The Architecture refers to design constraints that apply systemwide, whereas high-level design refers to design constraints that apply at the subsystem or multiple-class level but not necessarily systemwide.</li><li>Why architecture is a prerequisite is because of the quality of the architecture deter-mines the conceptual integrity of the system. That, in turn, determines the ultimate quality of the system. A well-thought-out architecture provides the structure needed to maintain a system’s conceptual integrity from the top levels down to the bottom.</li><li>Good architecture should fit the problem. When you look at the architecture, you should be pleased by how natural and easy the solution seems. It shouldn’t look as if the problem and the architecture have been forced together with duct tape.</li></ul><p><strong>NOTE:</strong> Different kinds of software projects call for different balances between preparation and construction. Every project is unique, but projects do tend to fall into general development styles. So read about these styles first before proceeding further</p><h3>Design in Construction</h3><p>The phrase “software design” means the conception, invention, or contrivance of a scheme for turning a specification for computer software into operational software.</p><p>One of the main differences between programs you develop in school and those you develop as a professional is that the design problems solved by school programs are rarely, if ever, wicked. — Design as a wicked problem</p><p>Design is a <strong><em>sloppy</em></strong> process as a good solution is often only subtly different from a poor one. It is also sloppy because it’s hard to know when your design is “good enough.”</p><h4><strong>Key Design Concepts:</strong></h4><blockquote>Good design depends on understanding a handful of key concepts — complexity, desirable characteristics of designs, and levels of design.</blockquote><p><strong><em>Complexity —</em></strong></p><p>At the <em>software-architecture</em> level, the complexity of a problem is reduced by dividing the system into subsystems. The goal of all software-design techniques is to break a complicated problem into simple pieces.</p><p>The more independent the subsystems are, the more you make it safe to focus on one bit of <em>complexity</em> at a time. Carefully defined objects separate concerns so that you can focus on one thing at a time. Packages provide the same benefit at a higher level of aggregation.</p><p><strong><em>Characteristics of a Design —</em></strong></p><p>Some characteristics of design quality are also characteristics of a good program: reliability, performance, and so on. Others are internal characteristics of the design which are —</p><ul><li><em>Minimal complexity,</em></li><li><em>Ease of maintenance,</em></li><li><em>Loose coupling,</em></li><li><em>Extensibility,</em></li><li><em>Reusability and many more </em>(Read Page — 80 for details)</li></ul><p><strong><em>Levels of Design —</em></strong></p><p>Design is needed at several different levels of detail in a software system. Some design techniques apply at all levels, and some apply at only one or two. Various levels are —</p><ul><li><em>Software system,</em></li><li><em>The division into subsystems/packages,</em></li><li><em>The division into classes within packages,</em></li><li><em>The division into data and routines within classes,</em></li><li><em>Internal routine design.</em></li></ul><p>Read levels of design — <em>page no.80</em> for detailed information about each level.</p><blockquote>Treat design as a wicked, sloppy, heuristic process. Don’t settle for the first design that occurs to you. Collaborate. Strive for simplicity. Prototype when you need to. Iterate, iterate, and iterate again. You’ll be happy with your designs.</blockquote><h3>Working Classes</h3><p>A class is a collection of data and routines that share a cohesive, well-defined responsibility. A class might also be a collection of routines that provides a cohesive set of services even if no common data is involved.</p><blockquote>Classes are the primary tool for maximizing the portion of a program that you can safely ignore while working on any one section of code.</blockquote><h4><strong>Abstract Data Types (ADTs) —</strong></h4><p>Abstract data types form the foundation for the concept of classes. In languages that support classes, you can implement each abstract data type as its own class.</p><p>Understanding ADTs is essential to understanding object-oriented programming. Without understanding ADTs, programmers create classes that are “classes” in name only—in reality, they are little more than convenient carrying cases for loosely related collections of data and routines. There are many benefits of using ADTs such as:</p><ul><li><em>You can hide implementation details,</em></li><li><em>Changes don’t affect the whole program,</em></li><li><em>You can make the interface more informative,</em></li><li><em>It’s easier to improve performance,</em></li><li><em>You don’t have to pass data all over your program — </em>The data is directly accessed only by routines that are part of the ADT. Routines that aren’t part of the ADT don’t have to worry about the data.</li></ul><h4><strong>Good Class Interfaces —</strong></h4><p>The first and probably most important step in creating a high-quality class is creating a good interface. This consists of the following class qualities —</p><ul><li><strong><em>Good Abstraction </em></strong>— abstraction is the ability to view a complex operation in a simplified form. A class interface provides an abstraction of the implementation that’s hidden behind the interface. The class’s interface should offer a group of routines that clearly belong together.</li><li><strong><em>Good</em></strong> <strong><em>Encapsulation</em></strong> — While Abstraction helps to manage complexity by providing models that allow you to ignore implementation details. Encapsulation is the enforcer that prevents you from looking at the details even if you want to.</li></ul><blockquote><strong><em>Don’t expose member data in public</em></strong></blockquote><ul><li><strong><em>Inheritance</em></strong> — It is the idea that one class is a specialization of another class. The purpose of inheritance is to create simpler code by defining a base class that specifies common elements of two or more derived classes. The common elements can be routine interfaces, implementations, data members, or data types. Inheritance helps avoid the need to repeat code and data in multiple locations by centralizing it within a base class.</li></ul><p>You can read more about polymorphism and other practices to get a better understanding of the Classes — under chapter 6: working classes.</p><h3><strong>High-Quality Routines</strong></h3><p>As we have now discussed classes, to get a better understanding of creating the high-quality class we need to create high-quality routines for the class.</p><p>There are many reasons as to why we would create a routine for your program or why routines are basically needed, such are:</p><ul><li>To <em>Reduce complexity,</em></li><li>To <em>Introduce an intermediate, understandable abstraction</em></li><li>To <em>avoid duplicate code and many more other reasons</em></li></ul><p>To understand about design at the routine level, we need to first understand about <strong><em>Cohesion</em></strong> — which basically refers to how closely the operations in a routine are related. Discussions about cohesion typically refer to several levels of cohesion, some of them are:</p><ul><li><em>Functional cohesion — which </em>is the strongest and best kind of cohesion</li><li><em>Sequential cohesion,</em></li><li><em>Communicational cohesion,</em></li><li><em>Temporal cohesion and many more</em></li></ul><p>Understanding the concepts is more important than remembering specific terms so please read in detail from page no.168.</p><blockquote>A good name for a routine clearly describes everything the routine does.</blockquote><p>First, the purpose of creating a routine should be clear then name should be wisely chosen</p><p>The Parameters of a routine should be ordered in a specific manner so that consistency around the project is maintained, one example would be to put parameters in <em>input-modify-output</em> order.</p><p>To get a clear understanding of design, naming, parameters at the routine level, Functions, and Procedures — Read chapter no. 07.</p><h3><strong>Defensive Programming</strong></h3><p>Defensive programming doesn’t mean being defensive about your programming — “It does so work!”. In defensive programming, the main idea is that if a routine is passed bad data, it won’t be hurt, even if the bad data is another routine’s fault.</p><p><strong><em>Assertions</em> — </strong>Assertions are especially useful in large, complicated programs and in high-reliability programs. They enable programmers to more quickly flush out mismatched interface assumptions, errors that creep in when code is modified, and so on.</p><ul><li><em>Use error-handling code for conditions you expect to occur; use assertions for conditions that should </em>never <em>occur,</em></li><li><em>Use assertions to document and verify </em><strong><em>preconditions</em></strong><em> and </em><strong><em>postconditions</em></strong><em>.</em></li></ul><p><strong>Exceptions — </strong>Exceptions are a specific means by which code can pass along errors or exceptional events to the code that called it. If code in one routine encounters an unexpected condition that it doesn’t know how to handle, it throws an exception, essentially throwing up its hands.</p><ul><li><em>Throw an exception only for conditions that are truly exceptional</em></li><li><em>Throw exceptions at the right level of abstraction</em></li></ul><p><strong><em>Offensive Programming —</em></strong>Exceptional cases should be handled in a way that makes them obvious during development and recoverable when the production code is running. Michael Howard and David LeBlanc refer to this approach as “<em>offensive programming</em>”</p><blockquote>Sometimes the best defense is a good offense. Fail hard during development so that you can fail softer during production.</blockquote><p>Too much defensive programming creates problems of its own. Sometimes, the additional code needed for defensive programming adds complexity to the software. Think about where you need to be defensive, and set your defensive-programming priorities accordingly.</p><h3>PPP —<strong>The Pseudocode Programming Process</strong></h3><p>The term “pseudocode” refers to an informal, English-like notation for describing how an algorithm, a routine, a class, or a program will work. The Pseudocode Programming Process defines a specific approach to using pseudocode to streamline the creation of code within routines.</p><ul><li><em>Pseudocode makes reviews easier,</em></li><li><em>Pseudocode supports the idea of </em><strong><em>iterative refinement</em></strong><em>,</em></li><li><em>Pseudocode makes changes easier,</em></li><li><em>Pseudocode minimizes commenting effort,</em></li><li><em>Pseudocode is easier to maintain than other forms of design documentation.</em></li></ul><h3>Variables</h3><p>Take the “<em>Data</em> <em>Literacy</em> <em>Test</em>’’ on page no. <em>238</em> to determine how much you are familiar with different variables and keywords.</p><p><strong>Initialization</strong> —Improper data initialization is one of the most fertile sources of error in computer programming. Developing effective techniques for avoiding initialization problems can save a lot of debugging time some of which are —</p><ul><li><em>Initialize each variable as it’s declared,</em></li><li><em>Ideally, declare and define each variable close to where it’s first used,</em></li><li><em>Use </em>final <em>or </em>const <em>when possible and there are many discussed in detail (See chapter no. 10)</em></li></ul><h3><strong>Scope</strong></h3><p>Scope, or visibility, refers to the extent to which your variables are known and can be referenced throughout a program. A variable with limited or small scope is known in only a small area of a program and a variable with a large scope is known in many places in a program</p><h4>Some specific guidelines you can use to minimize scope:</h4><ul><li><em>Initialize variables used in a loop immediately before the loop rather than back at the beginning of the routine containing the loop,</em></li><li><em>Don’t assign a value to a variable until just before the value is used,</em></li><li><em>Break groups of related statements into separate routines,</em></li><li><em>Begin with most restricted visibility, and expand the variable’s scope only if necessary</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff32d13892db" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>