<?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 Jonathan Alkalay on Medium]]></title>
        <description><![CDATA[Stories by Jonathan Alkalay on Medium]]></description>
        <link>https://medium.com/@alkalayj28?source=rss-72155cd8c8b9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5N2vkxDRp6zk9kOu7pPW6Q@2x.jpeg</url>
            <title>Stories by Jonathan Alkalay on Medium</title>
            <link>https://medium.com/@alkalayj28?source=rss-72155cd8c8b9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 23:36:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alkalayj28/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[Practical Coding Guidelines: Writing Code Your Future Self Will Thank You For]]></title>
            <link>https://blog.stackademic.com/practical-coding-guidelines-writing-code-your-future-self-will-thank-you-for-4be102e76e2c?source=rss-72155cd8c8b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/4be102e76e2c</guid>
            <category><![CDATA[coding-guide]]></category>
            <category><![CDATA[coding-best-practices]]></category>
            <category><![CDATA[senior-developer]]></category>
            <dc:creator><![CDATA[Jonathan Alkalay]]></dc:creator>
            <pubDate>Tue, 20 May 2025 13:01:51 GMT</pubDate>
            <atom:updated>2025-05-27T07:27:58.084Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qVbO20EzKXoKzRz6.png" /></figure><h3>Introduction:</h3><p>Writing code isn’t just about making something work — it’s about making it <em>understandable</em>, <em>testable</em>, and <em>maintainable</em> over time. Whether you’re working on a solo project or collaborating with a team, clean code pays dividends. This guide isn’t about fancy patterns or theoretical best practices — it’s a set of grounded, real-world principles to help you write code that’s easy to follow, easy to debug, and easy to change.</p><p>Think of it as a checklist for writing code you won’t dread revisiting in six months. <strong><em>(Special tip at number 10!!)</em></strong></p><h3>1. Use Concise, Self-Explanatory Names for Variables and Functions</h3><p><strong>Principle:</strong><br> Choose variable and function names that make the code readable without needing extra comments. A variable name should tell you what it holds and why it exists. A function name should clearly describe what the function does — without needing to read its implementation. Both should act like a contract: the name tells you what to expect. If someone else reads your code (or you do six months later), they should understand the variable’s role and the function’s behavior instantly.</p><p>Avoid vague or generic names like:</p><ul><li>data, info, temp, value, calculate(), handle(), ...etc.</li></ul><p>Bad Example:</p><p>This forces the reader to trace through the logic to understand what d and a are supposed to represent, and what the handle function does. In this example the function has only 1 line but if it had 30 lines we would be forced to read the logic in order to understand its purpose.</p><pre>const d = getData();<br>const a = d[0];<br><br>function handle(user) {<br>  ...code<br>  ...code<br>  return user.age &gt; 18;<br><br>}</pre><p>Good Example:</p><pre>const users = getUserList();<br>const firstUser = users[0];<br><br>function isAdult(user) {<br>  ...code<br>  ...code<br>  return user.age &gt; 18;<br>}</pre><p>Now, it’s obvious that:</p><ul><li>users holds a list of user objects</li><li>firstUser represents the first user in that list</li><li>isAdult checks if the user is categorised as an adult</li></ul><p><strong>Why it matters:</strong><br> Clear names reduce cognitive overhead. They let the code speak for itself, making it easier to debug, maintain, and extend.</p><h3>2. “Newsletter Principle” Functions should read like a newspaper, Headlines with the ability to dive into each “subject” (function logic)</h3><p><strong>Principle:</strong><br> Each function should take care of a single job. This does not necessarily mean it has to be short — a longer function is fine if it handles a single task cohesively.<br> Functions should strive to be as declarative as possible — a series of smaller function calls with the main function being the orchestrator (the “newsletter principle”).</p><p>Bad Example: (does multiple things and hides intent):</p><pre>function processUser(user: User) {<br>  if (!user.name) {<br>    return;<br>  }<br><br>  const score = user.actions.reduce((acc, curr) =&gt; acc + curr.value, 0);<br>  if (score &gt; 10) {<br>    user.rank = &#39;gold&#39;;<br>    sendPromo(user.email);<br>  }<br>  database.save(user);<br>}</pre><p>Good Example:</p><pre>function processUser(user: User) {<br>  if (!isValidUser(user)) {<br>    return;<br>  }<br><br>  const scoredUser = assignUserScore(user);<br>  const promotedUser = maybePromoteUser(scoredUser);<br>  notifyIfEligible(promotedUser);<br>  saveUser(promotedUser);<br>}<br><br>function isValidUser(user: User) { /* ... */ }<br>function assignUserScore(user: User) { /* ... */ }<br>function maybePromoteUser(user: User) { /* ... */ }<br>function notifyIfEligible(user: User) { /* ... */ }<br>function saveUser(user: User) { /* ... */ }</pre><p><strong>Why this matters:</strong><br> Smaller functions with clear names help make your code easier to read, reason about, and test. The main function should read like a high-level summary — clear, structured, and focused on one job.</p><h3>3. Avoid Mutations — Objects, Arrays, Global Variables</h3><p><strong>Principle:</strong><br> Avoid directly mutating objects, arrays, or shared/global variables. Instead, return new values using immutable operations like map, filter, reduce, and create new objects instead of mutating existing ones. Immutability leads to fewer bugs, more predictable behavior, and cleaner, easier-to-reason-about code.</p><p>Bad Example:</p><pre>function prepareUsers(users) {<br>  let processedUsers = users;<br><br>  removeInactiveUsers(processedUsers);<br>  promoteAdmins(processedUsers);<br>  sortByName(processedUsers);<br><br>  return processedUsers;<br>}<br><br>function removeInactiveUsers(users) {<br>  for (let i = users.length - 1; i &gt;= 0; i--) {<br>    if (!users[i].isActive) {<br>      users.splice(i, 1);<br>    }<br>  }<br>}<br><br>function promoteAdmins(users) {<br>  users.forEach(user =&gt; {<br>    if (user.isAdmin) {<br>      user.role = &#39;superadmin&#39;;<br>    }<br>  });<br>}<br><br>function sortByName(users) {<br>  users.sort((a, b) =&gt; a.name.localeCompare(b.name));<br>}</pre><p><strong>What’s the issue here?</strong></p><ul><li>All helper functions modify the same array in place.</li><li>You can’t understand the final output of prepareUsers without diving into every helper function.</li><li>This makes the code harder to maintain because if we remove one of the function calls or want to add a new function to the flow we might unintentionally break the other functions because they all depend on the same state</li></ul><p>Good Example:</p><pre>function prepareUsers(users) {<br>  const withoutInactive = removeInactiveUsers(users);<br>  const withPromotedAdmins = promoteAdmins(withoutInactive);<br>  const sorted = sortByName(withPromotedAdmins);<br><br>  return sorted;<br>}<br><br>function removeInactiveUsers(users) {<br>  return users.filter(user =&gt; user.isActive);<br>}<br><br>function promoteAdmins(users) {<br>  return users.map(user =&gt;<br>    user.isAdmin ? { ...user, role: &#39;superadmin&#39; } : user<br>  );<br>}<br><br>function sortByName(users) {<br>  return [...users].sort((a, b) =&gt; a.name.localeCompare(b.name));<br>}</pre><h3><strong>Why this version is better:</strong></h3><ul><li>Each function returns a new array instead of mutating the input.</li><li>The data flow in prepareUsers is clear and linear.</li><li>You can understand each transformation at a glance.</li><li>Functions are predictable, testable, and easy to maintain.</li></ul><h3>4. Avoid Strange “Elegant” Solutions and Don’t Hide Your Code’s Intentions</h3><p><strong>Principle:</strong><br> Avoid clever tricks just because they save a few lines of code. You will most likely not understand how they work in 6 months. Keep your code as simple and self-explanatory as possible, even at the cost of more lines of code… your future self will thank you.<br> Don’t hide your code’s intentions — write it out clearly. For example, complex expressions buried inside an if block are hard to understand later. Extract them into well-named variables or functions so the name tells the story.</p><p>Bad Example (The intent of the code is clear only at the time of writing it, it will be forgotten in a few months time):</p><p><em>— What does this do? Why split on “/”? Why filter? This will be impossible to understand in the future</em></p><pre>if (user.name.split(&quot;/&quot;).filter(Boolean).length &gt; 5) {<br>  // ...<br>}</pre><p>Good Example (clear and explicit):</p><pre>const hasLongNameSegments = userHasMoreThanFiveNameParts(user);<br><br>if (hasLongNameSegments) {<br>  // ...<br>}<br><br>function userHasMoreThanFiveNameParts(user) {<br>  const parts = user.name.split(&quot;/&quot;).filter(Boolean);<br>  return parts.length &gt; 5;<br>}</pre><p><em>— Clear, intention-revealing naming makes the code easy to follow.</em></p><p><strong>Why this matters:</strong><br> Readable, explicit code is easier to maintain and debug. Write for your future self or others who will read your code. Clear names and simple logic beat clever tricks every time.</p><h3>5. Avoid Deeply Nesting Code</h3><p><strong>Principle:</strong><br> Avoid deep nesting like multiple if statements or loops inside each other. Extract inner blocks into separate functions with descriptive names. Flattening your logic improves readability and reduces cognitive load.</p><p>Bad Example (deep nesting):</p><pre>function processOrder(order) {<br>  if (order) {<br>    if (order.items.length &gt; 0) {<br>      for (const item of order.items) {<br>        if (item.inStock) {<br>          // process item<br>        }<br>      }<br>    }<br>  }<br>}</pre><p>Good Example (flattened logic using extracted functions):</p><pre>function processOrder(order) {<br>  if (!order) return;<br>  if (!hasItems(order)) return;<br><br>  order.items.forEach(processItemIfInStock);<br>}<br><br>function hasItems(order) {<br>  return order.items.length &gt; 0;<br>}<br><br>function processItemIfInStock(item) {<br>  if (!item.inStock) return;<br>  // process item<br>}</pre><p><strong>Why this matters:</strong><br> Reducing nesting makes your code easier to scan and understand. Extracting nested logic into clearly named functions means readers can grasp high-level flow without digging through details.</p><h3>6. Leave Logs in Important Areas of the Code</h3><p><strong>Principle:</strong><br> Make sure to leave logs in important areas of the code so you will have an easy time debugging the flow in a production environment.</p><p><strong>Bad Example (no visibility into what’s happening):</strong></p><pre>function processPayment(userId, amount) {<br>  // silently fails or succeeds<br>  paymentService.charge(userId, amount);<br>}</pre><p>Good Example (clear, intentional logging):</p><pre>function processPayment(userId, amount) {<br>  console.log(`Processing payment of $${amount} for user ${userId}`);<br>  <br>  try {<br>    paymentService.charge(userId, amount);<br>    console.log(`Payment successful for user ${userId}`);<br>  } catch (err) {<br>    console.error(`Payment failed for user ${userId}:`, err.message);<br>  }<br>}</pre><p><strong>Why this matters:</strong><br> Logs give you visibility into how your app behaves in production. They help you track down bugs, understand failures, and monitor system health. Don’t wait until things break — build logging in as you go.</p><h3>7. Follow Consistent Patterns for Organizing Files and Components</h3><p><strong>Principle:</strong><br> Follow consistent patterns for organizing files and components so that others (or future-you) can quickly understand where things live and why.</p><h3>8. Keep Modules/Components Loosely Coupled and Highly Cohesive</h3><p><strong>Principle:</strong><br>Don’t make functions or components smarter than they need to be. Instead of passing flags that let a function decide what logic to execute internally, delegate that responsibility to a higher-level coordinator.</p><p>The function should do <em>exactly</em> what it claims — nothing more. That keeps it simple, reusable, and easier to test. Let the delegator handle context; keep the core logic focused.</p><p>Bad Example</p><pre>function calculateAverageAge(<br>  users: User[],<br>  onlyAdmins: boolean,<br>  onlyAdults: boolean<br>): number {<br>  let filtered = users;<br><br>  if (onlyAdmins) {<br>    filtered = filtered.filter(user =&gt; user.role === &#39;admin&#39;);<br>  }<br><br>  if (onlyAdults) {<br>    filtered = filtered.filter(user =&gt; user.age &gt;= 18);<br>  }<br><br>  if (filtered.length === 0) return 0;<br><br>  const total = filtered.reduce((sum, user) =&gt; sum + user.age, 0);<br>  return total / filtered.length;<br>}<br><br>// Example usage<br>const avgAll = calculateAverageAge(users, false, false);<br>const avgAdmins = calculateAverageAge(users, true, false);<br>const avgAdultAdmins = calculateAverageAge(users, true, true);</pre><p><strong>Problems:</strong></p><ul><li>Function is doing too much — deciding what its dataset is <strong>and</strong> calculating.</li><li>Every condition adds more flags.</li><li>Not composable or testable in isolation.</li><li>Violates the <strong>Single Responsibility Principle</strong>.</li><li>We must touch the core component with every new flag we add and can potentially break it</li></ul><p>Good Example (function only cares about what it needs)</p><pre><br>function calculateAverageAge(users: User[]): number {<br>  if (users.length === 0) return 0;<br>  const total = users.reduce((sum, user) =&gt; sum + user.age, 0);<br>  return total / users.length;<br>}<br><br>function getAverageByType(userGroup: UserGroup): number {<br>  const { users, type } = userGroup;<br><br>  switch (type) {<br>    case &#39;admins&#39;: {<br>      const admins = users.filter(user =&gt; user.role === &#39;admin&#39;);<br>      return calculateAverageAge(admins);<br>    }<br><br>    case &#39;adults&#39;: {<br>      const adults = users.filter(user =&gt; user.age &gt;= 18);<br>      return calculateAverageAge(adults);<br>    }<br><br>    case &#39;adultAdmins&#39;: {<br>      const adultAdmins = users<br>        .filter(user =&gt; user.role === &#39;admin&#39;)<br>        .filter(user =&gt; user.age &gt;= 18);<br>      return calculateAverageAge(adultAdmins);<br>    }<br><br>    default:<br>      return calculateAverageAge(users);<br>  }<br>}<br><br>// Usage<br>const avg = getAverageByType(userGroup);<br></pre><h3>Why This Is Better</h3><ul><li>calculateAverageAge does <em>exactly one thing</em>.</li><li>Filtering helpers like filterAdmins and filterAdults are isolated and reusable.</li><li>The delegator (getAverageByType) is responsible for orchestration — <em>not</em> the logic itself.</li><li>Easier to test, extend, and reason about.</li><li>No flags, no branching logic inside your pure function — just clarity.</li></ul><p><strong>Why this matters:</strong><br> When a function only receives the exact data it needs, it becomes easier to reuse in different contexts, easier to test, and less likely to break if other systems change. It’s no longer tied to <em>how</em> the data is retrieved — just <em>what</em> data it receives.</p><h3>9. Clean It Up!!!</h3><p><strong>Principle:</strong><br> Don’t be lazy and leave code cleaner than you found it. Refactor and tidy up when adding new features or fixing bugs. Treat the codebase like a shared kitchen. Don’t be afraid to touch things that are written badly just because you were not the one who wrote it.</p><p>Even small improvements — renaming a confusing variable, removing dead code, or formatting messy blocks — go a long way. You don’t have to rebuild everything, just make the part you touched a little better.</p><p><strong>Why this matters:</strong><br> Clean code is easier to understand, extend, and debug. It makes the project better for everyone — including future-you.</p><h3>10. Bonus Tip:</h3><p>If you made it this far, I will let you in on a secret that took me a while to learn.</p><p>Enjoy what you do. If you can learn to see problems not as inconveniences but as opportunities to grow and improve, you’ll stay ahead of the curve, reach the top, and enjoy your work so much more.</p><h3>Closing Statement:</h3><p>Writing maintainable code starts with thoughtful choices — like using clear, purposeful names and embracing challenges as opportunities to improve. When your code communicates its intent effortlessly and you approach problems with a growth mindset, you set yourself — and your projects — up for long-term success. Keep refining your craft, and enjoy the journey of becoming a better developer every day.</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://differ.blog/inplainenglish"><strong>Differ</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4be102e76e2c" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/practical-coding-guidelines-writing-code-your-future-self-will-thank-you-for-4be102e76e2c">Practical Coding Guidelines: Writing Code Your Future Self Will Thank You For</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes ~ Persistent Volumes]]></title>
            <link>https://blog.stackademic.com/kubernetes-persistent-volumes-74c5d6831633?source=rss-72155cd8c8b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/74c5d6831633</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[persistent-volume]]></category>
            <dc:creator><![CDATA[Jonathan Alkalay]]></dc:creator>
            <pubDate>Sun, 16 Mar 2025 07:31:16 GMT</pubDate>
            <atom:updated>2025-05-27T07:28:04.706Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/624/0*TtlcfDajv2xCLFK2.png" /></figure><h3><strong>Understanding Kubernetes Persistent Volumes: PostgreSQL Example</strong></h3><h3>Introduction</h3><p>When deploying databases in Kubernetes, ensuring data persistence is crucial. By default, when a Pod is deleted or restarted, its filesystem is wiped. This leads to data loss, making it unsuitable for databases like PostgreSQL. This is where Kubernetes Persistent Volumes (PV) and Persistent Volume Claims (PVC) come into play.</p><p>In this blog, we’ll explore how persistent storage is configured in a PostgreSQL deployment using Kubernetes. We’ll break down the PersistentVolumeClaim (PVC) used in the example YAML configuration.</p><h3>What is a Persistent Volume (PV) and Persistent Volume Claim (PVC)?</h3><p><strong>Persistent Volume (PV):</strong> A PV is a piece of storage provisioned in the cluster. It abstracts storage details from the user and allows stateful applications to persist data across restarts.</p><p><strong>Persistent Volume Claim (PVC):</strong> A PVC is a request for storage by a user. It allows applications to claim storage resources without worrying about the underlying storage infrastructure.</p><h3>Breaking Down the PVC in the PostgreSQL Deployment</h3><p>Below is the PVC definition in our example YAML file:</p><pre>apiVersion: v1<br>kind: PersistentVolumeClaim<br>metadata:<br>  name: postgres-pvc<br>spec:<br>  accessModes:<br>    - ReadWriteOnce<br>  resources:<br>    requests:<br>      storage: &#39;5G&#39;</pre><h3>Explanation</h3><ul><li><strong>metadata.name: postgres-pvc</strong> → This PVC is named postgres-pvc, and it is used by the PostgreSQL Deployment.</li><li><strong>accessModes: ReadWriteOnce</strong> → The volume can be mounted as read-write by a single node.</li><li><strong>resources.requests.storage: ‘5G’</strong> → Requests 5GB of storage.</li></ul><h3>Default Storage Class</h3><p>The PVC does not specify a storage class, so it uses the default storage class provided by the Kubernetes cluster. This means that the underlying storage provisioner will handle the allocation of the requested storage.</p><h3>How PVC is Used in the Deployment</h3><p>The PVC is referenced in the PostgreSQL Deployment using a volume mount:</p><pre>volumeMounts:<br>  - mountPath: /var/lib/postgresql/data<br>    name: postgres-data</pre><p>And the volume is defined as:</p><pre>volumes:<br>  - name: postgres-data<br>    persistentVolumeClaim:<br>      claimName: postgres-pvc</pre><h3>Why Mounting to /var/lib/postgresql/data is Needed</h3><p>Mounting the volume to /var/lib/postgresql/data is necessary because this is the default directory where PostgreSQL stores its data files. By mounting the PVC to this path, we ensure that the database files are stored on persistent storage, allowing them to survive Pod restarts and deletions.</p><h3>How This Works</h3><ol><li>The Deployment requests a volume with the name postgres-data.</li><li>This volume is linked to the PVC named postgres-pvc.</li><li>The container mounts this volume to /var/lib/postgresql/data, ensuring database files persist even if the Pod is restarted.</li></ol><h3>Demonstrating Persistence with a Simple Test</h3><p>To see this in action, follow these steps:</p><h3>Step 1: Deploy PostgreSQL</h3><p>Apply the YAML file using:</p><pre>kubectl apply -f postgres.yaml</pre><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: postgres-service<br>spec:<br>  type: NodePort<br>  selector:<br>    component: postgres<br>  ports:<br>    - port: 5432<br>      targetPort: 5432<br>---<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: postgres<br>  labels:<br>    component: postgres<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      component: postgres<br>  template:<br>    metadata:<br>      labels:<br>        component: postgres<br>    spec:<br>      containers:<br>        - name: postgres<br>          image: postgres:latest<br>          env:<br>            - name: POSTGRES_PASSWORD<br>              value: password<br>          ports:<br>            - containerPort: 5432<br>          volumeMounts:<br>            - mountPath: /var/lib/postgresql/data<br>              name: postgres-data<br>      volumes:<br>        - name: postgres-data<br>          persistentVolumeClaim:<br>            claimName: postgres-pvc<br>---<br>apiVersion: v1<br>kind: PersistentVolumeClaim<br>metadata:<br>  name: postgres-pvc<br>spec:<br>  accessModes:<br>    - ReadWriteOnce<br>  resources:<br>    requests:<br>      storage: &#39;5G&#39;</pre><h3>Step 2: Verify the PVC</h3><p>Check if the PVC is bound to a volume:</p><pre>kubectl get pvc</pre><p>Expected output:</p><pre>NAME           STATUS   VOLUME                                     CAPACITY   ACCESS MODES   STORAGECLASS<br>postgres-pvc   Bound    pvc-12345678-abcde-1234-5678-abcdefg       5Gi        RWO            standard</pre><h3>Step 3: Create a Table in PostgreSQL</h3><p>Access the PostgreSQL Pod:</p><pre>kubectl exec -it &lt;postgres-pod-name&gt; -- psql -U postgres</pre><p>Create a test table:</p><pre>CREATE TABLE test_table (id SERIAL PRIMARY KEY, name TEXT);<br>INSERT INTO test_table (name) VALUES (&#39;Persistent Data&#39;);<br>SELECT * FROM test_table;</pre><h3>Step 4: Restart the Pod</h3><pre>kubectl delete pod &lt;postgres-pod-name&gt;</pre><h3>Step 5: Verify Data Persistence</h3><p>Reconnect to PostgreSQL and run:</p><pre>SELECT * FROM test_table;</pre><p>You should still see the inserted data, proving that persistence works!</p><h3>Conclusion</h3><p>By using a Persistent Volume Claim (PVC), we ensure that PostgreSQL data is not lost when a Pod restarts. This approach is essential for running databases and stateful applications in Kubernetes. The use of the default storage class simplifies the process by leveraging the cluster’s built-in storage provisioning capabilities.</p><p>Have any questions or want more details? Drop a comment below!</p><figure><a href="http://ko-fi.com/jonathanalkalay"><img alt="" src="https://cdn-images-1.medium.com/max/700/0*0_7AbZHuv7EUsK7O.png" /></a></figure><h3>Please leave a like, follow, and comment if you enjoyed the article.</h3><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://differ.blog/inplainenglish"><strong>Differ</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74c5d6831633" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/kubernetes-persistent-volumes-74c5d6831633">Kubernetes ~ Persistent Volumes</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using npm packages to share TypeScript types between projects]]></title>
            <link>https://blog.stackademic.com/using-npm-packages-to-share-typescript-types-between-projects-f42a940ac7bb?source=rss-72155cd8c8b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/f42a940ac7bb</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Jonathan Alkalay]]></dc:creator>
            <pubDate>Mon, 29 Apr 2024 15:50:23 GMT</pubDate>
            <atom:updated>2024-04-30T01:01:14.169Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*OtyvIXCreHG29qdF.png" /></figure><p>When working on large code bases with multiple services, many times we encounter the same interfaces/types throughout the different services.</p><p>We don’t want to redeclare the types in each project, this will be time consuming and can lead to annoying bugs if the types do not match. Also if the types change in one project we need to change them in each individual project and that just isn’t optimal.</p><h3>How do we solve the issue?</h3><p>We declare all of our types that get used in multiple projects in a seperate NPM project (we will call it common-types), we can have as many of these as we desire, then we will install this package as a dependency in every other project that wishes to consume these types. This addresses all of the problems mentioned before.</p><blockquote>To start we will create our 3 new NPM projects, one for our common types and 2 projects to consume these types.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*y5DpqpaeI3lBhJuTkn3sPQ.png" /></figure><p>In each project we will initialize the npm project and install TypeScript. You can follow the steps below. Additionally we will install <strong><em>rimraf</em></strong>, it will help us later on.</p><pre>npm init -y<br>npm install --save-dev typescript<br>npm install rimraf</pre><blockquote>Next we will create our ts.config file and add these settings</blockquote><p>The main thing to take away from these settings is that everything in the <strong><em>src</em></strong> folder will be the target for the TypeScript compiler and will be able to be imported from this package. The transpiled code will be put into the <strong><em>build</em></strong> folder. Anything we add into the exclude array will not be transpiled.</p><pre>{<br>    &quot;compilerOptions&quot;: {<br>      &quot;target&quot;: &quot;es2019&quot;, <br>      &quot;lib&quot;: [&quot;es2019&quot;, &quot;dom&quot;],                                 <br>      &quot;module&quot;: &quot;commonjs&quot;,  <br>      &quot;declaration&quot;: true,<br>      &quot;rootDir&quot;: &quot;src&quot;,<br>      &quot;allowJs&quot;: true,<br>      &quot;outDir&quot;: &quot;./build&quot;,<br>      &quot;noEmit&quot;: false,                             <br>      &quot;esModuleInterop&quot;: true,         <br>      &quot;noImplicitAny&quot;: false,<br>      &quot;moduleResolution&quot;: &quot;node&quot;,                    <br>      &quot;forceConsistentCasingInFileNames&quot;: true,            <br>      &quot;strict&quot;: true,                                  <br>      &quot;skipLibCheck&quot;: true                                 <br>    },<br>    &quot;include&quot;: [<br>      &quot;src&quot;<br>    ],<br>    &quot;exclude&quot;: [<br>  <br>    ],<br>    &quot;ts-node&quot;: {<br>      &quot;require&quot;: [&quot;tsconfig-paths/register&quot;]<br>    }<br>  }</pre><blockquote>Now in the package.json we add a script that invokes the TypeScript compiler</blockquote><blockquote>It will add everything into the build folder beacuse of the settings in our ts.config above. We use rimraf here to remove the previous build before recreating the folder to remove the old types.</blockquote><pre>{<br>    &quot;name&quot;: &quot;common&quot;,<br>    &quot;version&quot;: &quot;1.0.0&quot;,<br>    &quot;description&quot;: &quot;&quot;,<br>    &quot;scripts&quot;: {<br>      &quot;build&quot;: &quot;rimraf ./build &amp;&amp; tsc&quot;<br>    },<br>    &quot;author&quot;: &quot;&quot;,<br>    &quot;license&quot;: &quot;ISC&quot;,<br>    &quot;dependencies&quot;: {<br>      &quot;rimraf&quot;: &quot;^3.0.2&quot;<br>    },<br>    &quot;devDependencies&quot;: {<br>      &quot;typescript&quot;: &quot;^4.8.4&quot;<br>    }<br>}</pre><p>Lastly we need to tell npm where to import our types from. To do this we simply need to add the path in the “types” section in our package.json. Here is our final package.json</p><pre>{<br>    &quot;name&quot;: &quot;common&quot;,<br>    &quot;version&quot;: &quot;1.0.0&quot;,<br>    &quot;description&quot;: &quot;&quot;,<br>    &quot;types&quot;: &quot;build/index.d.ts&quot;,<br>    &quot;scripts&quot;: {<br>      &quot;build&quot;: &quot;rimraf ./build &amp;&amp; tsc&quot;<br>    },<br>    &quot;author&quot;: &quot;&quot;,<br>    &quot;license&quot;: &quot;ISC&quot;,<br>    &quot;dependencies&quot;: {<br>      &quot;rimraf&quot;: &quot;^3.0.2&quot;<br>    },<br>    &quot;devDependencies&quot;: {<br>      &quot;typescript&quot;: &quot;^4.8.4&quot;<br>    }<br>}</pre><p>We tell npm that our types live in build/index.d.ts. You can change this to match your needs.</p><p>Now we create a new folder inside of common-types named src and create an index file. Any type exported from the index file will be available to use from this package.</p><h3>Lets try it out.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*2JlC1IzYm6DqXFXveBDkhQ.png" /></figure><p>I created the index file and also a file to declare the Person type.</p><p>In the person file I export the new Person type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*5whUbCPYr-6350JPU2Qghw.png" /></figure><p>In the index.ts file, export all from the person.ts file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*fR79Ytx0uD7dvC7mIPJOIA.png" /></figure><p>Now that our types are declared we just need to run the “build” script that we created before and we are ready to install our types as an npm package.</p><pre>npm run build</pre><p>If you followed the steps until now you should have a new build folder with all your transpiled code and the auto generated declaration files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*hTJcn1RJbdFaqhQRTG41Cg.png" /></figure><p>Now the only thing left to do is to install our NPM package as a dependency in our other projects.</p><p>Lets start with Project 1.</p><p>In the package json we will add our npm package as a dependency like so.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*yilb3Regtwwf3WLE9nZ9pA.png" /></figure><p>This is the syntax to install a local dependency that is not yet published to the npm cloud. The way it works is you add the path to your npm project after “file:” in our case its “../common-types”. The name of the dependency can be any name of your choosing as long as the path is correct. The name is what we use to reference this package in our code when importing from it.</p><p>Now we run npm install</p><pre>npm install</pre><p>Now we can freely import the Person type in the project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*BYeezpp4yumekQcAsGfDbw.png" /></figure><blockquote>The same thing will be true in Project2.</blockquote><p>Thats it! Now we have an NPM package with all of our common types that can be installed as a dependency in as many different projects as we want.</p><blockquote>REMINDER: Dont forget to run the build script whenever modifying the types in the common package.</blockquote><h3>Please leave a like, follow, and comment if you enjoyed the article.</h3><figure><a href="https://ko-fi.com/jonathanalkalay"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RAVsw7Mcvsh8aJL3LuG6bg.png" /></a></figure><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f42a940ac7bb" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/using-npm-packages-to-share-typescript-types-between-projects-f42a940ac7bb">Using npm packages to share TypeScript types between projects</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript Discriminated Unions]]></title>
            <link>https://blog.stackademic.com/typescript-discriminated-unions-13d8c6f0c643?source=rss-72155cd8c8b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/13d8c6f0c643</guid>
            <category><![CDATA[advanced-typescript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Jonathan Alkalay]]></dc:creator>
            <pubDate>Thu, 25 Apr 2024 11:22:13 GMT</pubDate>
            <atom:updated>2024-04-29T00:38:01.647Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DHPT8AxmJUFpS53i" /></figure><p>What is a discriminated union in TypeScript ?</p><p>A discriminated union in TypeScript is a way of combining different types into one. Each type has a special property that helps TypeScript figure out which type it is, allowing you to have stronger type safety in your code.</p><p>Here is an example. We will look at a simple Api response type that will be a different shape depending on the status of the request.</p><pre>type ApiResponse&lt;TReturnType&gt; = {<br>  status: &quot;uninitialized&quot; | &quot;loading&quot; | &quot;success&quot; | &quot;error&quot;;<br>  data?: TReturnType;<br>  error?: string;<br>}</pre><p>If we were to use this type above the developer would need to know ahead of time when exactly <strong><em>data</em></strong> and <strong><em>error</em></strong> are not undefined, in this case it is pretty easy to guess but it won’t always be the case. On top of that the developer will be forced to get in the way of typescripts compiler and scatter non-null assertion operators (!) throughout the code and can cause errors when not careful.</p><p>Here is an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dsZamX-jwPSCWfl07_mwsQ.png" /></figure><h3>So what is the alternative?</h3><blockquote>Discriminated Unions.</blockquote><p>Here is how we will improve on the above type and take advantage of typescripts powerfull features.</p><p>We will create 4 new types, one for each one of the possible status states.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*yvpsTirik8QcjuAYpeQFwA.png" /></figure><p>We can see that the only time we will have the data property is when the status is <strong><em>success</em></strong> and error when the status is <strong><em>error.</em></strong></p><p>Now that we have the shapes of our different responses we will combine them and create our Discriminated Union</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*WhYPExkmHOfjmjNiDjNXYw.png" /></figure><p>This may look a bit strange but it is fairly simple, we are creating a Union of our 4 other types and making sure we have a property to discriminate by, in our case it is <strong><em>status</em></strong>. Now when we do the same check as before, typescript is able to determine the shape of the object based on the discriminating property.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*cxJz9EPfIFfb4SBKdfNHIw.png" /></figure><p>Now typescipt was able to determine that data exists when the status is success and we didn’t have to intervene with the compiler and add any non-null assertion operators.</p><h3>Please leave a like, follow, and comment if you enjoyed the article.</h3><figure><a href="https://ko-fi.com/jonathanalkalay"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RAVsw7Mcvsh8aJL3LuG6bg.png" /></a></figure><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13d8c6f0c643" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/typescript-discriminated-unions-13d8c6f0c643">TypeScript Discriminated Unions</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom HTML Input Tag React TypeScript Tutorial]]></title>
            <link>https://blog.stackademic.com/custom-html-input-tag-react-typescript-tutorial-0ca1db418d6d?source=rss-72155cd8c8b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ca1db418d6d</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[htmlinput]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react-typescript]]></category>
            <category><![CDATA[frontend-development]]></category>
            <dc:creator><![CDATA[Jonathan Alkalay]]></dc:creator>
            <pubDate>Mon, 22 Apr 2024 11:56:48 GMT</pubDate>
            <atom:updated>2024-04-29T00:38:12.628Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vc9LQeubMpl3lrGg.jpeg" /></figure><p><strong>Anyone who has used the base input tag in html knows how bad it looks, suprisingly many developers struggle to customize it or don’t even know its possible to, today we will learn how. </strong><a href="https://codesandbox.io/p/sandbox/custom-html-input-gvzwc9"><strong>If you want to follow along the sandbox will be linked here</strong></a></p><blockquote><strong>To start we will create a simple React component using the base input tag that will allow us to upload a basic file.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*ngmLMrrUyFZo1LxYpUZPTQ.png" /><figcaption>Basic Html Input tag</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*zmI2_XCfKEIY9x6zWzzJEw.png" /></figure><p><strong>As we can see above the default look of the input is undesirable, to say the least. So how can we fix this? Simple, we will use the functionality of the element by using a ref and hide the content that the input button displays.</strong></p><h3><strong>Here is our new and improved version of the default input tag button</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*DSfDY2Igg6phXb4i2hhkZw.png" /><figcaption>Customized Input element</figcaption></figure><h3><strong><em>So what changed?</em></strong></h3><blockquote><strong><em>1 )</em></strong></blockquote><blockquote><strong><em>First we created a ref using Reacts useRef hook.</em></strong></blockquote><blockquote><strong>2 )</strong></blockquote><blockquote><strong><em>We created a function that triggers the onClick function of the input tag, and passed this function as an onClickHandler into our custom button that we want the user to click on when uploading files.</em></strong></blockquote><blockquote><strong>3)</strong></blockquote><blockquote><strong>Lastly we passed this ref to the input tag and to finish it all off we hid the actual default button with some css</strong></blockquote><h3><strong>And There you have it, a fully reusable customized input tag that can be made to look however you like!</strong></h3><blockquote><a href="https://codesandbox.io/p/sandbox/custom-html-input-gvzwc9"><strong>If you would like to check out the example you can find it in this sandbox</strong></a></blockquote><h3><strong>Please leave a like, follow and comment if you enjoyed the article.</strong></h3><figure><a href="https://ko-fi.com/jonathanalkalay"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RAVsw7Mcvsh8aJL3LuG6bg.png" /></a></figure><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ca1db418d6d" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/custom-html-input-tag-react-typescript-tutorial-0ca1db418d6d">Custom HTML Input Tag React TypeScript Tutorial</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>