<?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 Jason Kam on Medium]]></title>
        <description><![CDATA[Stories by Jason Kam on Medium]]></description>
        <link>https://medium.com/@thefiend?source=rss-a7a4ff11fe52------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Cw2qd-CkA2MBBAeHEamOYA.jpeg</url>
            <title>Stories by Jason Kam on Medium</title>
            <link>https://medium.com/@thefiend?source=rss-a7a4ff11fe52------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 22:08:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thefiend/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[From Jira Ticket to AI-Ready Context in One Command]]></title>
            <link>https://levelup.gitconnected.com/from-jira-ticket-to-ai-ready-context-in-one-command-c4b8196258d1?source=rss-a7a4ff11fe52------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4b8196258d1</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Jason Kam]]></dc:creator>
            <pubDate>Mon, 20 Apr 2026 06:35:43 GMT</pubDate>
            <atom:updated>2026-04-21T00:33:39.570Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XcG2hQltdxRC85IQbBRMRw.png" /><figcaption>From Jira Ticket to AI-Ready Context in One Command by Nano Banana</figcaption></figure><p>Every developer who has tried using an AI coding agent knows the friction: you open your Jira board, find the ticket you’re working on, copy the title, copy the description, paste it into the chat, describe the attachments, re-paste the acceptance criteria… and by the time you’re done, you’ve spent five minutes just setting up context.</p><p>There’s a better way.</p><blockquote><strong>Follow Me to Stay Up to Date! </strong><em>🔔</em></blockquote><h3><strong>The Problem with AI Agents and Ticket Context</strong></h3><p>AI coding agents like <strong><em>Claude, Cursor, and GitHub Copilot</em></strong> are powerful, but they’re only as effective as the context you give them. A vague prompt like “implement the new user settings page” leads to a vague result. The more precisely you describe what needs to be built, the better the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sE7-4U2OlYP-uwhcZD_j3g.png" /><figcaption>The Problem with AI Agent Context by Nano Banana</figcaption></figure><p>Jira tickets, when well-written, already contain exactly that information: a summary, a detailed description, acceptance criteria, screenshots, and diagrams. The problem is getting that information into the agent efficiently.</p><p>Copy-pasting from Jira is tedious and lossy. Screenshots don’t transfer well. Formatting gets mangled. And if you’re working across multiple tickets or handing context to an autonomous agent that will work while you sleep, manual copy-pasting doesn’t scale.</p><blockquote><strong>Follow Me to Stay Up to Date! </strong><em>🔔</em></blockquote><h3><strong>Introducing Jira to Markdown</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wxxXivo_hbn5tkQsfGg2zw.jpeg" /><figcaption><strong>Jira to Markdown — Generated with Dalle-3</strong></figcaption></figure><p><a href="https://github.com/thefiend/Jira-to-Markdown"><strong>Jira to Markdown</strong></a><strong> </strong>is a small bash script that solves this exactly. It fetches a Jira Cloud issue via the REST API and writes it to a structured Markdown file, including downloading all image attachments and embedding them inline.</p><pre>jira-task PROJ-123</pre><p>That’s it. One command. After running it, you get:</p><pre>PROJ-123/<br>├── PROJ-123.md # issue title + description as Markdown<br>└── images/ # all image attachments, embedded inline in the .md</pre><p>The Markdown file looks like this:</p><pre># PROJ-123: Add dark mode toggle to user settings<br><br>## Description<br>Users have requested a dark mode option. The toggle should appear in the<br>**User Settings** page under the _Appearance_ section.<br><br>### Acceptance Criteria<br>- Toggle switches between light and dark themes<br>- Preference is persisted to the user&#39;s profile<br>- Theme applies across all pages immediately on toggle<br><br>![mockup.png](images/mockup.png)</pre><p>Clean, structured, and complete, ready to be dropped straight into any AI agent’s context window.</p><blockquote><strong>Follow Me to Stay Up to Date! </strong><em>🔔</em></blockquote><h3><strong>How It Works</strong></h3><p>Jira stores rich text descriptions in <strong>Atlassian Document Format (ADF)</strong>,<strong> </strong>a JSON tree format that encodes paragraphs, headings, lists, tables, code blocks, and embedded media. Jira to Markdown walks that tree recursively using<strong><em> jq</em> </strong>and converts each node to its Markdown equivalent.</p><p>For images, it goes a step further. Jira Cloud stores attachments with numeric IDs, but embeds them in the description using UUIDs from Atlassian’s media CDN. The script bridges this gap: it downloads each attachment by its numeric ID, follows the redirect to the CDN, extracts the UUID from the final URL, and maps it back to the filename — so every image referenced in the description becomes a proper Markdown image tag pointing to a local file.</p><p>When images are downloading, a progress bar keeps you informed:</p><pre>Downloading mockup.png<br>######################################################################## 100.0%</pre><h3><strong>Setup Takes Two Minutes</strong></h3><h4><strong>1. Install</strong></h4><pre>bash install.sh</pre><p>This copies <strong><em>jira-task</em></strong> to <strong><em>~/bin/</em></strong>. If <strong><em>~/bin</em></strong> isn’t in your <strong>PATH</strong> yet, add it to <strong><em>~/.zshrc</em></strong>:</p><pre>export PATH=&quot;$HOME/bin:$PATH&quot;</pre><h4><strong>2. Configure</strong></h4><pre>jira-task --config</pre><p>You’ll be prompted for your Jira base URL, email address, and API token. Credentials are saved to <strong><em>~/.zshrc</em></strong>. Get your API token at <a href="https://id.atlassian.com/manage-profile/security/api-tokens">https://id.atlassian.com/manage-profile/security/api-tokens</a>.</p><h4><strong>3. Run</strong></h4><pre>jira-task PROJ-123</pre><h3><strong>How This Changes AI Agent Workflows</strong></h3><h4><strong>Giving an Agent a Task</strong></h4><p>Instead of this:</p><blockquote><em>“Build the settings page. Users want dark mode. There’s a mockup somewhere in Jira.”</em></blockquote><p>You can do this:</p><pre>jira-task PROJ-123</pre><p>Then in your agent:</p><blockquote><em>“Read PROJ-123/PROJ-123.md and implement the feature described there.”</em></blockquote><p>The agent gets the full ticket — summary, description, acceptance criteria, formatted tables, and the actual mockup image, all in one structured file it can read directly from disk.</p><h4><strong>Autonomous Agent Handoffs</strong></h4><p>This is where <a href="https://github.com/thefiend/Jira-to-Markdown"><strong>Jira to Markdown</strong></a> really earns its keep. If you’re running an autonomous agent overnight or in CI, the kind that opens files, writes code, runs tests, and commits, you need it to have a self-contained brief it can reference at any point during execution.</p><p>A Markdown file in the repo is exactly that. The agent can re-read it if it needs to check acceptance criteria, reference a screenshot for layout, or confirm scope before making a decision.</p><h4><strong>Multi-Ticket Context</strong></h4><p>Working on a feature that spans several tickets? Fetch them all:</p><pre>jira-task PROJ-120<br>jira-task PROJ-121<br>jira-task PROJ-122</pre><p>Now you have three structured briefs the agent can reason across simultaneously.</p><blockquote><strong>Follow Me to Stay Up to Date! </strong><em>🔔</em></blockquote><p><strong>What Gets Converted</strong></p><p>The ADF-to-Markdown conversion handles the full range of Jira content:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2Ftpd9C%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2Ftpd9C%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2Ftpd9C%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="528" frameborder="0" scrolling="no"><a href="https://medium.com/media/034edc170d487c31b479bc8a5ae5d0ed/href">https://medium.com/media/034edc170d487c31b479bc8a5ae5d0ed/href</a></iframe><p>Tables with <strong><em>colspan</em></strong> cells are expanded correctly, pipe characters inside cells are escaped, and trailing spaces in bold text are moved outside the markers — all the formatting edge cases that matter when the output is being read by a parser or a language model.</p><blockquote><strong>Follow Me to Stay Up to Date! </strong><em>🔔</em></blockquote><h3><strong>The Bigger Picture</strong></h3><p>The friction between where work is described (Jira) and where work gets done (your IDE, your agent) is real, and it compounds. Every manual copy-paste is a chance for context to be lost, summarised incorrectly, or simply left out.</p><p>Tools like <a href="https://github.com/thefiend/Jira-to-Markdown"><strong>Jira to Markdown</strong></a> are small , a single bash script , but they close that gap cleanly. The ticket is the source of truth. Now your agent can read it directly.</p><blockquote><strong><em>Jira to Markdown</em></strong><em> is open source. Dependencies: </em><strong>curl</strong><em> (pre-installed on macOS) and </em><strong>jq</strong><em> (`brew install jq`).</em></blockquote><h3>Thinks</h3><p>Writing has always been my passion and it gives me pleasure to help and inspire people. If you have any questions, feel free to reach out!</p><p>Thank you for reading this far, please give this article <strong>a round of applause if you can, or give me a follow</strong>, I will thank you from the bottom of my heart.</p><p><a href="https://www.buymeacoffee.com/jasonkam">jasonkam</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4b8196258d1" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/from-jira-ticket-to-ai-ready-context-in-one-command-c4b8196258d1">From Jira Ticket to AI-Ready Context in One Command</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Palindrome with a Twist: Mastering the ‘Valid Palindrome II’ Problem in Python]]></title>
            <link>https://levelup.gitconnected.com/palindrome-with-a-twist-mastering-the-valid-palindrome-ii-problem-in-python-a0ce6522df5f?source=rss-a7a4ff11fe52------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0ce6522df5f</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[coding-challenge]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jason Kam]]></dc:creator>
            <pubDate>Thu, 03 Oct 2024 00:53:50 GMT</pubDate>
            <atom:updated>2024-10-03T14:50:11.404Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5m4OML4vU7GKE1PpyT1gYA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XgoQNOlLOZNFshpRSIRPMg.png" /></figure><h4><strong>The solution for ‘Valid Palindrome II’ Problem in Python that beat 92.20% of the solutions worldwide.</strong></h4><pre>class Solution:<br>    def validPalindrome(self, s: str) -&gt; bool:<br>        left, right = 0, len(s) - 1<br>        <br>        while left &lt; right:<br>            if s[left] != s[right]:<br>                return (s[left:right] == s[left:right][::-1]) or (s[left+1:right+1] == s[left+1:right+1][::-1])<br>            left += 1<br>            right -= 1<br>        <br>        return True</pre><ol><li><strong>Two-pointer approach:</strong></li></ol><pre>left, right = 0, len(s) - 1</pre><p>We start with two pointers, one at the beginning of the string (left) and one at the end (right).</p><p><strong>2. Main loop:</strong></p><pre>while left &lt; right:</pre><p>We continue comparing characters as long as the left pointer is less than the right pointer.</p><p><strong>3. Character comparison:</strong></p><pre>if s[left] != s[right]:</pre><p>If the characters at the left and right pointers don’t match, we’ve found a potential place where we might need to remove a character</p><p><strong>4. Palindrome check after potential removal:</strong></p><pre>return (s[left:right] == s[left:right][::-1]) or (s[left+1:right+1] == s[left+1:right+1][::-1])</pre><p>This is the key part of the optimization. When we find a mismatch, we check two possibilities:</p><p>a. s[left:right] == s[left:right][::-1]: This checks if the substring from left to right (exclusive) is a palindrome. This is equivalent to removing the character at right.</p><p>b. s[left+1:right+1] == s[left+1:right+1][::-1]: This checks if the substring from left+1 to right+1 (exclusive) is a palindrome. This is equivalent to removing the character at left.</p><p>The [::-1] is Python&#39;s way of reversing a string. We&#39;re comparing each substring with its reverse to check if it&#39;s a palindrome.</p><p>If either of these conditions is true, it means we can make the string a palindrome by removing one character, so we return True.</p><p><strong>5. Moving the pointers:</strong></p><pre>left += 1<br>right -= 1</pre><p>If the characters match, we move the pointers towards the center and continue checking.</p><p><strong>6. Final return:</strong></p><pre>return True</pre><p>If we’ve gone through the entire string without finding a mismatch that couldn’t be resolved by removing one character, the string is either already a palindrome or can be made into one by removing one character, so we return True.</p><p>This solution is efficient because it only does the palindrome check when necessary, and it only checks the two possible character removals that could potentially create a palindrome. It avoids checking every possible character removal, which would be much more time-consuming.</p><h3>Thinks</h3><p>Writing has always been my passion and it gives me pleasure to help and inspire people. If you have any questions, feel free to reach out!</p><p>Thank you for reading this far, please give this article <strong>a round of applause if you can, or give me a follow</strong>, I will thank you from the bottom of my heart</p><p><a href="https://www.buymeacoffee.com/jasonkam">jasonkam</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0ce6522df5f" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/palindrome-with-a-twist-mastering-the-valid-palindrome-ii-problem-in-python-a0ce6522df5f">Palindrome with a Twist: Mastering the ‘Valid Palindrome II’ Problem in Python</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ruby on Rails Creational Patterns: The Secret to Writing Flexible, Maintainable, and Performant…]]></title>
            <link>https://levelup.gitconnected.com/ruby-on-rails-creational-patterns-the-secret-to-writing-flexible-maintainable-and-performant-b988e782b77e?source=rss-a7a4ff11fe52------2</link>
            <guid isPermaLink="false">https://medium.com/p/b988e782b77e</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Jason Kam]]></dc:creator>
            <pubDate>Thu, 05 Oct 2023 06:25:35 GMT</pubDate>
            <atom:updated>2026-04-20T07:07:47.121Z</atom:updated>
            <content:encoded><![CDATA[<h3>Top 5 Ruby on Rails Creational Design Patterns: A Comprehensive Guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-gaUNGHdVVuNxoCSHdnyIA.png" /><figcaption>Creational Design Patterns — Ruby On Rails by Nano Banana</figcaption></figure><p><strong>Creational design patterns</strong> are reusable solutions to common software design problems related to object creation. They provide a structured approach to building robust and maintainable applications. Ruby on Rails is a full-stack web framework that encourages the use of design patterns.</p><blockquote><strong>Follow Me to Stay Up to Date for More Tips &amp; Tricks! </strong><em>🔔😜</em></blockquote><h3>Benefits of using Creational Design Patterns</h3><ul><li><strong>Increased flexibility and reusability:</strong> Creational design patterns allow you to create and manage objects in a more flexible and reusable way. This can make your code easier to maintain and update.</li><li><strong>Reduced coupling:</strong> Creational design patterns can help you to reduce coupling between different parts of your code. This can make your code more modular and easier to test.</li><li><strong>Improved performance:</strong> Creational design patterns can help you to improve the performance of your application by caching objects and avoiding unnecessary object creation.</li></ul><h3>Popular Creational Design Patterns in Ruby on Rails</h3><h4><strong>1. Factory Method</strong></h4><p>The Factory Method pattern allows you to create objects without specifying the exact class of the object that will be created. This can be useful when you need to create objects from different subclasses of a common base class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3u3UTzIJQpvtRWRO8fyY2A.png" /><figcaption>Factory Method by Nano Banana</figcaption></figure><p><strong>Example:</strong></p><pre>class UserFactory<br>  def self.create(type)<br>    case type<br>    when :admin<br>      AdminUser.new<br>    when :regular<br>      RegularUser.new<br>    else<br>      raise &quot;Unknown user type: #{type}&quot;<br>    end<br>  end<br>end<br><br># Usage:<br>user = UserFactory.create(:regular)</pre><h4>2. Abstract Factory</h4><p>The Abstract Factory pattern provides an interface for creating families of related objects without specifying their concrete classes. This can be useful when you need to create objects from different families of related classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BkT9_X121yf0kEnrr01MpQ.png" /><figcaption>Abstract Factory by Nano Banana</figcaption></figure><p><strong>Example:</strong></p><pre>class UserAbstractFactory<br>  def create_user(type)<br>    raise NotImplementedError<br>  end<br>  def create_product(type)<br>    raise NotImplementedError<br>  end<br>end<br><br>class AdminUserAbstractFactory &lt; UserAbstractFactory<br>  def create_user(type)<br>    AdminUser.new<br>  end<br>  def create_product(type)<br>    AdminProduct.new<br>  end<br>end<br><br>class RegularUserAbstractFactory &lt; UserAbstractFactory<br>  def create_user(type)<br>    RegularUser.new<br>  end<br>  def create_product(type)<br>    RegularProduct.new<br>  end<br>end<br><br># Usage:<br>factory = AdminUserAbstractFactory.new<br>user = factory.create_user(:admin)<br>product = factory.create_product(:admin)</pre><h4>3. Singleton</h4><p>The Singleton pattern ensures that a class has only one instance, and provides a global point of access to it. This can be useful when you need to have a single instance of a class for the entire application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GXPDxsror3OcXTN6Tho6sg.png" /><figcaption>Singleton by Nano Banana</figcaption></figure><p><strong>Example:</strong></p><pre>class DatabaseConnection<br>  include Singleton<br><br>  def self.connect<br>    instance.connection<br>  end<br><br>  def connection<br>    @connection ||= ActiveRecord::Base.establish_connection<br>  end<br>end<br><br># Usage:<br>connection = DatabaseConnection.connect</pre><h4>4. Prototype</h4><p>The Prototype pattern allows you to create new objects by copying existing objects. This can be useful when you need to create objects that are similar to existing objects, but with some minor changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6CztQ_EnS0HOu41nLV9_uA.png" /><figcaption>Prototype by Nano Banana</figcaption></figure><p><strong>Example:</strong></p><pre>class User<br>  attr_accessor :name, :email<br><br>  def clone<br>    User.new(name: name, email: email)<br>  end<br>end<br><br># Usage:<br>user = User.new(name: &quot;John Doe&quot;, email: &quot;john.doe@example.com&quot;)<br>new_user = user.clone<br>new_user.name = &quot;Jane Doe&quot;<br>new_user.email = &quot;jane.doe@example.com&quot;<br># new_user is a new User object with the same name and email as user,<br># but with some minor changes.</pre><h4><strong>5. Builder</strong></h4><p>The Builder pattern allows you to construct complex objects step-by-step. This can be useful when you need to create objects with many different configuration options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*et9ulTXPcZ-39T7dcMq9nw.png" /><figcaption>Builder by Nano Banana</figcaption></figure><p><strong>Example:</strong></p><pre>class UserBuilder<br>  attr_accessor :name, :email<br><br>  def build<br>    User.new(name: name, email: email)<br>  end<br>end<br><br># Usage:<br>builder = UserBuilder.new<br>builder.name = &quot;John Doe&quot;<br>builder.email = &quot;john.doe@example.com&quot;<br>user = builder.build<br># user is a new User object with the name and email that were set in the builder.</pre><h3>Conclusion</h3><p>Creational design patterns can be a valuable tool for Ruby on Rails developers. By using creational design patterns, you can write code that is more flexible, maintainable, and performant.</p><p><strong>Here are some additional tips for using creational design patterns in Ruby on Rails:</strong></p><ul><li>Choose the right pattern for the job. There is no one-size-fits-all creational design pattern. The best pattern to use will depend on the specific problem you are trying to solve.</li><li>Use creational design patterns in conjunction with other design patterns. Creational design patterns can often be used in conjunction with other design patterns, such as the MVC pattern, to create more robust and maintainable applications.</li><li>Don’t overuse creational design patterns. It is important to use creational design patterns wisely. Overusing creational design patterns can make your code more complex and difficult to understand.</li></ul><h3>Examples of creational design patterns in Ruby on Rails</h3><ul><li>The<strong> Factory Method</strong> pattern is used in Ruby on Rails to create ActiveRecord models. For example, the User.create method uses the Factory Method pattern to create a new User object.</li><li>The <strong>Abstract Factory pattern</strong> is used in Ruby on Rails to create families of related objects. For example, the ActionController::Base class uses the Abstract Factory pattern to create a new controller object.</li><li>The<strong> Singleton pattern</strong> is used in Ruby on Rails to create singletons. For example, the ActiveRecord::Base class uses the Singleton pattern to create a single database connection.</li><li>The<strong> Prototype pattern</strong> is used in Ruby on Rails to create copies of existing objects. For example, the ActiveRecord::Base class uses the Prototype pattern to create new copies of existing model objects.</li><li>The <strong>Builder pattern</strong> is used in Ruby on Rails to create complex objects step-by-step. For example, the FormHelper class uses the Builder pattern to create form objects.</li></ul><p>I hope this article has helped you to understand creational design patterns and how to use them in Ruby on Rails.</p><h3>Thinks</h3><p>Writing has always been my passion and it gives me pleasure to help and inspire people. If you have any questions, feel free to reach out!</p><p>Thank you for reading this far, please give this article <strong>a round of applause if you can, or give me a follow</strong>, I will thank you from the bottom of my heart</p><p><a href="https://www.buymeacoffee.com/jasonkam">jasonkam</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b988e782b77e" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/ruby-on-rails-creational-patterns-the-secret-to-writing-flexible-maintainable-and-performant-b988e782b77e">Ruby on Rails Creational Patterns: The Secret to Writing Flexible, Maintainable, and Performant…</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 10 Ruby on Rails Design Patterns for Speed and Performance]]></title>
            <link>https://levelup.gitconnected.com/top-10-ruby-on-rails-design-patterns-for-speed-and-performance-14052d4afbc0?source=rss-a7a4ff11fe52------2</link>
            <guid isPermaLink="false">https://medium.com/p/14052d4afbc0</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Jason Kam]]></dc:creator>
            <pubDate>Sat, 30 Sep 2023 14:33:12 GMT</pubDate>
            <atom:updated>2023-10-23T08:26:27.000Z</atom:updated>
            <content:encoded><![CDATA[<p>Ruby on Rails design patterns are reusable solutions to common software design problems. They provide a structured approach to building robust and maintainable applications. Ruby on Rails is a full-stack web framework that encourages the use of design patterns.</p><figure><img alt="Top 10 Ruby on Rails Design Patterns for Speed and Performance" src="https://cdn-images-1.medium.com/max/1024/1*3igIJKgkQz_tgDTVaicBZQ.jpeg" /><figcaption>Ruby on Rails Design Patterns</figcaption></figure><blockquote><strong>Follow Me to Stay Up to Date for More Tips &amp; Tricks! </strong><em>🔔😜</em></blockquote><p>In this article, we will discuss the top 10 Ruby on Rails design patterns and provide example code for each item.</p><h4><strong>1. Model-View-Controller (MVC)</strong></h4><p>The MVC pattern is the foundation of Rails application architecture. It separates the application into three distinct components:</p><ul><li><strong>Model: </strong>Represents the data and business logic of the application.</li><li><strong>View:</strong> Handles the presentation and UI of the application.</li><li><strong>Controller:</strong> Acts as an intermediary, controlling the flow of data and requests between the Model and View.</li></ul><p>The MVC pattern promotes the separation of concerns, maintainability, and code reusability.</p><p><strong>Example Code:</strong></p><pre># Model<br>class User &lt; ApplicationRecord<br>  validates :name, presence: true<br>  validates :email, presence: true, uniqueness: true<br>end<br><br># View<br>&lt;% @users.each do |user| %&gt;<br>  &lt;h1&gt;&lt;%= user.name %&gt;&lt;/h1&gt;<br>  &lt;p&gt;&lt;%= user.email %&gt;&lt;/p&gt;<br>&lt;% end %&gt;<br><br># Controller<br>class UsersController &lt; ApplicationController<br>  def index<br>    @users = User.all<br>  end<br>end</pre><h4>2. Active Record</h4><p>The Active Record pattern is an object-relational mapping (ORM) pattern that provides an object-oriented interface for interacting with a relational database. It is the default ORM for Rails applications.</p><p>Active Record makes it easy to retrieve, manipulate, and persist data in the database. It also provides a number of features that make it easy to write complex queries and maintain data integrity.</p><p><strong>Example Code:</strong></p><pre># Model<br>class User &lt; ApplicationRecord<br>  has_many :posts<br>end<br><br># Controller<br>class UsersController &lt; ApplicationController<br>  def index<br>    @users = User.includes(:posts).all<br>  end<br>end</pre><h4>3. Service Objects</h4><p>Service objects are used to encapsulate business logic into reusable units. They can be used to perform complex tasks, such as sending an email, processing a payment, or generating a report.</p><p>Service objects make the code more readable, maintainable, and testable. They also help to separate the concerns of the application.</p><p><strong>Example Code:</strong></p><pre># Service<br>class SendEmailService<br>  def initialize(user)<br>    @user = user<br>  end<br><br>  def call<br>    # Send an email to the user.<br>  end<br>end<br><br># Controller<br>class UsersController &lt; ApplicationController<br>  def index<br>    @users = User.all<br>  end<br><br>  def create<br>    user = User.new(user_params)<br>    if user.save<br>      SendEmailService.new(user).call<br>      redirect_to users_path<br>    else<br>      render :new<br>    end<br>  end<br><br>  private<br><br>  def user_params<br>    params.require(:user).permit(:name, :email)<br>  end<br>end</pre><h4>4. View Objects (Presenters)</h4><p>View objects, also known as presenters, are used to prepare data for the view. They can be used to format the data, filter it, or add additional information.</p><p>View objects make the views more readable and maintainable. They also help to separate the concerns of the application.</p><p><strong>Example Code:</strong></p><pre># Presenter<br>class UserPresenter<br>  def initialize(user)<br>    @user = user<br>  end<br><br>  def name<br>    @user.name<br>  end<br><br>  def email<br>    @user.email<br>  end<br><br>  def created_at<br>    @user.created_at.strftime(&#39;%d %b %Y&#39;)<br>  end<br>end<br><br># Controller<br>class UsersController &lt; ApplicationController<br>  def index<br>    @users = User.all<br>    @users_presenters = @users.map { |user| UserPresenter.new(user) }<br>  end<br>end</pre><h4>5. Query Objects</h4><p>Query objects are used to encapsulate query logic into reusable units. They can be used to perform complex queries without polluting the controller or model code.</p><p>Query objects make the code more readable, maintainable, and testable. They also help to separate the concerns of the application.</p><pre># Query<br>class RecentUsersQuery<br>  def call<br>    User.where(created_at: 1.week.ago..).order(created_at: :desc)<br>  end<br>end<br><br># Controller<br>class UsersController &lt; ApplicationController<br>  def index<br>    @users = RecentUsersQuery.new.call<br>  end<br>end</pre><h4>6. Decorators</h4><p>Decorators are used to add new functionality or behavior to existing objects. They can be used to decorate models, views, or controllers.</p><p>Decorators make the code more modular and reusable. They also help to avoid cluttering the original objects with additional code.</p><p><strong>Example Code:</strong></p><pre># Decorator<br>class UserDecorator<br>  def initialize(user)<br>    @user = user<br>  end<br><br>  def name<br>    @user.name<br>  end<br><br>  def email<br>    @user.email<br>  end<br><br>  def created_at<br>    @user.created_at.strftime(&#39;%d %b %Y&#39;)<br>  end<br><br>  def gravatar_url<br>    &quot;https://www.gravatar.com/avatar/#{@user.email_digest}&quot;<br>  end<br>end<br><br># Controller<br>class UsersController &lt; ApplicationController<br>  def index<br>    @users = User.all<br>    @users_decorators = @users.map { |user| UserDecorator.new(user) }<br>  end<br>end</pre><h4>7. Concerns</h4><p>Concerns are used to group related code together. They can be used to encapsulate functionality that is shared across multiple models, views, or controllers.</p><p>Concerns make the code more modular and reusable. They also help to improve the readability and maintainability of the code.</p><p><strong>Example Code:</strong></p><pre># Concern<br>module Validatable<br>  def validates(*args)<br>    super<br>    validate(*args)<br>  end<br><br>  def validate(*args)<br>    # Validation logic.<br>  end<br>end<br><br># Model<br>class User &lt; ApplicationRecord<br>  include Validatable<br>  validates :name, presence: true<br>  validates :email, presence: true, uniqueness: true<br>end</pre><h4>8. Callbacks</h4><p>Callbacks are used to execute code before or after a specific event. They can be used to perform tasks such as validation, logging, or caching.</p><p>Callbacks make the code more modular and reusable. They also help to avoid cluttering the models with additional code.</p><p><strong>Example Code:</strong></p><pre># Model<br>class User &lt; ApplicationRecord<br>  before_validation :strip_whitespace<br><br>  private<br><br>  def strip_whitespace<br>    self.name.strip!<br>    self.email.strip!<br>  end<br>end</pre><h4>9. Scopes</h4><p>Scopes are used to define named queries. They can be used to filter, sort, or order the results of a query.</p><p>Scopes make the code more readable and maintainable. They also help to avoid repeating the same query logic in multiple places.</p><p><strong>Example Code:</strong></p><pre># Model<br>class User &lt; ApplicationRecord<br>  scope :active, -&gt; { where(active: true) }<br>  scope :recent, -&gt; { order(created_at: :desc) }<br>end<br><br># Controller<br>class UsersController &lt; ApplicationController<br>  def index<br>    @users = User.active.recent.all<br>  end<br>end</pre><h4>10. Namespaces</h4><p>Namespaces are used to group related classes and modules together. They help to organize the code and avoid name collisions.</p><p>Namespaces make the code more modular and reusable. They also help to improve the readability and maintainability of the code.</p><p><strong>Example Code:</strong></p><pre># Controller<br>module Admin<br>  class UsersController &lt; ApplicationController<br>    def index<br>      @users = User.all<br>    end<br>  end<br>end</pre><p>These are just a few of the many Ruby on Rails design patterns that can be used to write faster and more efficient code. By using these patterns, you can improve the quality and maintainability of your Rails applications.</p><h3>Thinks</h3><p>Writing has always been my passion and it gives me pleasure to help and inspire people. If you have any questions, feel free to reach out!</p><p>Thank you for reading this far, please give this article a round of applause if you can, or give me a follow, I will thank you from the bottom of my heart</p><p><a href="https://www.buymeacoffee.com/jasonkam">jasonkam</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14052d4afbc0" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/top-10-ruby-on-rails-design-patterns-for-speed-and-performance-14052d4afbc0">Top 10 Ruby on Rails Design Patterns for Speed and Performance</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Solve Any Dynamic Programming Problem in 5 Simple Steps]]></title>
            <link>https://python.plainenglish.io/how-to-solve-any-dynamic-programming-problem-in-5-simple-steps-e9f57a291b37?source=rss-a7a4ff11fe52------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9f57a291b37</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <dc:creator><![CDATA[Jason Kam]]></dc:creator>
            <pubDate>Sat, 30 Sep 2023 14:09:26 GMT</pubDate>
            <atom:updated>2023-10-13T00:49:39.649Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="How to Solve Any Dynamic Programming Problem in 5 Simple Steps" src="https://cdn-images-1.medium.com/max/1024/1*rX2DaianIAMtPatW802_tQ.jpeg" /><figcaption>Solving Dynamic Programming Problems</figcaption></figure><p><strong>Dynamic programming</strong> is a powerful problem-solving technique that can be used to solve a wide variety of problems, including those in computer science, mathematics, and economics. It works by breaking down a large problem into smaller subproblems, solving the subproblems recursively, and then combining the solutions to the subproblems to solve the original problem.</p><blockquote><strong>Follow Me to Stay Up to Date for More Tips &amp; Tricks! </strong><em>🔔😜</em></blockquote><p>Here are some tips on how to break down dynamic programming with examples in Python:</p><p><strong>1. Identify the subproblems.</strong> What are the smaller problems that make up the larger problem? For example, the Fibonacci sequence problem can be broken down into the subproblems of finding the Fibonacci number at <strong>index n — 1</strong> and finding the Fibonacci number at <strong>index n — 2</strong>.</p><p><strong>2. Find the optimal substructure.</strong> This means that the optimal solution to the original problem can be constructed from the optimal solutions to its subproblems. For example, the optimal solution to the Fibonacci sequence problem can be constructed by taking the sum of the Fibonacci numbers at indices <strong>n — 1</strong> and <strong>n — 2</strong>.</p><p><strong>3. Write a recurrence relation. </strong>This is a mathematical equation that expresses the optimal solution to the problem in terms of the optimal solutions to its subproblems. For example, the recurrence relation for the Fibonacci sequence problem is:</p><pre>F(n) = F(n - 1) + F(n - 2)</pre><p><strong>4. Solve the base cases.</strong> These are the smallest subproblems that can be solved directly. For example, the base cases for the Fibonacci sequence problem are the Fibonacci numbers at indices 0 and 1, which are both equal to 0.</p><p><strong>5. Solve the problem bottom-up.</strong> This means starting with the base cases and using the recurrence relation to solve larger and larger subproblems until the original problem is solved.</p><p>Here is a Python implementation of the Fibonacci sequence problem using dynamic programming:</p><p><strong>Python Example Code:</strong></p><pre>def fibonacci(n):<br>  &quot;&quot;&quot;<br>  Computes the Fibonacci number at index n using dynamic programming.Args:<br>    n: The index of the Fibonacci number to compute.<br>  Returns:<br>    The Fibonacci number at index n.<br>  &quot;&quot;&quot;<br>  # Create a table to store the Fibonacci numbers that have already been computed.<br>  table = [0] * (n + 1)<br>  # Initialize the base cases.<br>  table[0] = 0<br>  table[1] = 1<br>  # Compute the Fibonacci numbers bottom-up.<br>  for i in range(2, n + 1):<br>    table[i] = table[i - 1] + table[i - 2]<br>  # Return the Fibonacci number at index n.<br>  return table[n]<br><br># Example usage:<br>print(fibonacci(10))<br></pre><p><strong>Output:</strong></p><pre>55</pre><p>This is just one example of how to break down dynamic programming with Python. Dynamic programming can be used to solve a wide variety of problems, including:</p><ul><li>The longest common subsequence problem</li><li>The knapsack problem</li><li>The edit distance problem</li><li>The coin change problem</li><li>The traveling salesman problem</li></ul><p>If you are having trouble solving a problem with dynamic programming, try breaking it down into smaller subproblems and using the tips above.</p><h3>Thinks</h3><p>Writing has always been my passion and it gives me pleasure to help and inspire people. If you have any questions, feel free to reach out!</p><p>Thank you for reading this far, please give this article a round of applause if you can, or give me a follow, I will thank you from the bottom of my heart</p><p><a href="https://www.buymeacoffee.com/jasonkam">jasonkam</a></p><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><strong><em>(X</em></strong>), <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, and <a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9f57a291b37" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/how-to-solve-any-dynamic-programming-problem-in-5-simple-steps-e9f57a291b37">How to Solve Any Dynamic Programming Problem in 5 Simple Steps</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 10 Programming Algorithms Every Programmer Should Know (and When to Use Them)]]></title>
            <link>https://levelup.gitconnected.com/top-10-programming-algorithms-every-programmer-should-know-and-when-to-use-them-ba4d8b43a58f?source=rss-a7a4ff11fe52------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba4d8b43a58f</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Jason Kam]]></dc:creator>
            <pubDate>Sat, 30 Sep 2023 13:38:55 GMT</pubDate>
            <atom:updated>2023-10-03T22:11:21.459Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Top 10 Programming Algorithms Every Programmer Should Know (and When to Use Them)" src="https://cdn-images-1.medium.com/max/1024/1*75NynVGNoRV8Mt1Vl8DiNw.jpeg" /><figcaption>Programming Algorithms</figcaption></figure><h3>Introduction</h3><p>Algorithms are the foundation of programming. They are step-by-step instructions that tell a computer how to solve a problem or perform a task. There are many different types of algorithms, each with its own strengths and weaknesses.</p><p>In this article, we will discuss the top 10 programming algorithms that every programmer should know, along with speed-optimized example code.</p><blockquote><strong>Follow Me to Stay Up to Date for More Tips &amp; Tricks! </strong><em>🔔😜</em></blockquote><h4>1. Binary search</h4><p><strong>Binary search</strong> is a divide-and-conquer algorithm that finds an element in a sorted array by repeatedly dividing the array in half and comparing the target element to the middle element.</p><p><strong>When to Use?</strong></p><ul><li>When searching for an element in a sorted array.</li><li>When the array is large and unsorted, it can be sorted first using a more efficient sorting algorithm, such as quicksort or mergesort.</li></ul><p><strong>Python Example Code:</strong></p><pre>def binary_search(array, target):<br>  low = 0<br>  high = len(array) - 1<br><br>  while low &lt;= high:<br>    mid = (low + high) // 2<br><br>    if array[mid] == target:<br>      return mid<br>    elif array[mid] &lt; target:<br>      low = mid + 1<br>    else:<br>      high = mid - 1<br><br>  return -1<br><br># Example usage:<br><br>array = [1, 3, 5, 7, 9]<br>target = 5<br><br>index = binary_search(array, target)<br><br>if index &gt;= 0:<br>  print(f&quot;The target element is at index {index}&quot;)<br>else:<br>  print(&quot;The target element is not in the array&quot;)</pre><p>The above example of the binary search uses a technique called “loop unrolling”. This involves unrolling the loop body so that it is executed multiple times per iteration. This can significantly improve the performance of the algorithm, especially for small arrays.</p><h4><strong>2. Breadth-first search (BFS)</strong></h4><p><strong>Breadth-first search</strong> is a graph algorithm that traverses a graph by visiting all of the nodes at a given level before moving on to the next level.</p><p><strong>When to Use?</strong></p><ul><li>When traversing a graph and visiting all nodes at a given level before moving on to the next level.</li><li>When finding the shortest path between two nodes in a graph.</li><li>When detecting cycles in a graph.</li></ul><p><strong>Python Example Code:</strong></p><pre>def bfs(graph, start_node):<br>  queue = []<br>  visited = set()<br><br>  queue.append(start_node)<br><br>  while queue:<br>    node = queue.pop(0)<br><br>    if node not in visited:<br>      visited.add(node)<br><br>      for neighbor in graph[node]:<br>        queue.append(neighbor)<br><br># Example usage:<br><br>graph = {<br>  0: [1, 2],<br>  1: [3, 4],<br>  2: [5, 6],<br>  3: [],<br>  4: [],<br>  5: [],<br>  6: []<br>}<br><br>start_node = 0<br><br>bfs(graph, start_node)</pre><p>The above example code of BFS uses a technique called “adjacency list”. This involves storing the graph as an adjacency list, which is a list of arrays where each array contains the neighbors of a node. This can significantly improve the performance of the algorithm, especially for large graphs.</p><h4><strong>3. Depth-first search (DFS)</strong></h4><p><strong>Depth-first search</strong> is a graph algorithm that traverses a graph by following one path until it reaches a dead end, then backtracking and trying another path.</p><p><strong>When to Use?</strong></p><ul><li>When traversing a graph and following one path until it reaches a dead end, then backtracking and trying another path.</li><li>When finding all paths between two nodes in a graph.</li><li>When detecting strongly connected components in a graph.</li></ul><p><strong>Python Example Code:</strong></p><pre>def dfs(graph, start_node):<br>  stack = []<br>  visited = set()<br><br>  stack.append(start_node)<br><br>  while stack:<br>    node = stack.pop()<br><br>    if node not in visited:<br>      visited.add(node)<br><br>      for neighbor in graph[node]:<br>        stack.append(neighbor)<br><br># Example usage:<br><br>graph = {<br>  0: [1, 2],<br>  1: [3, 4],<br>  2: [5, 6],<br>  3: [],<br>  4: [],<br>  5: [],<br>  6: []<br>}<br><br>start_node = 0<br><br>dfs(graph, start_node)</pre><p>The above example code of DFS uses a technique called “stack”. This involves storing the nodes to be visited in a stack. This can significantly improve the performance of the algorithm, especially for deep graphs.</p><h4><strong>4. Merge sort</strong></h4><p><strong>Merge sort</strong> is a divide-and-conquer algorithm that sorts an array by repeatedly dividing it into two halves, sorting each half, and then merging the two sorted halves back together.</p><p><strong>When to Use?</strong></p><ul><li>When sorting an array.</li><li>Merge sort is a stable sorting algorithm, which means that it preserves the original order of equal elements in the array.</li><li>Merge sort is also an efficient sorting algorithm for large arrays.</li></ul><p><strong>Python Example Code:</strong></p><pre>def merge_sort(array):<br>  if len(array) &lt;= 1:<br>    return array<br><br>  mid = len(array) // 2<br><br>  left = merge_sort(array[:mid])<br>  right = merge_sort(array[mid:])<br><br>  return merge</pre><h4><strong>5. Quicksort</strong></h4><p><strong>Quicksort</strong> is a divide-and-conquer algorithm that sorts an array by partitioning it around a pivot element and then recursively sorting the two subarrays.</p><p><strong>When to Use?</strong></p><ul><li>When sorting an array.</li><li>Quicksort is a fast sorting algorithm, but it is not stable.</li><li>Quicksort is not as efficient as merge sort for large arrays with many unique elements.</li></ul><p><strong>Python Example Code:</strong></p><pre>def quicksort(array):<br>  if len(array) &lt;= 1:<br>    return array<br><br>  pivot = array[0]<br>  less = []<br>  greater = []<br><br>  for element in array[1:]:<br>    if element &lt; pivot:<br>      less.append(element)<br>    else:<br>      greater.append(element)<br><br>  return quicksort(less) + [pivot] + quicksort(greater)<br><br># Example usage:<br><br>array = [5, 3, 2, 1, 4]<br><br>sorted_array = quicksort(array)<br><br>print(sorted_array)</pre><p>The above example code of quicksort uses a technique called “median-of-three partitioning”. This involves choosing the median of the first, middle, and last elements as the pivot element. This can significantly improve the performance of the algorithm, especially for large arrays.</p><h4>6. Heapsort</h4><p>Heapsort is a divide-and-conquer algorithm that sorts an array by building a heap and then repeatedly removing the largest element from the heap.</p><p><strong>When to Use?</strong></p><ul><li>When sorting an array.</li><li>Heapsort is an in-place sorting algorithm, which means that it sorts the array in place without creating a new array.</li><li>Heapsort is also an efficient sorting algorithm for large arrays.</li></ul><p><strong>Python Example Code:</strong></p><pre>def heapsort(array):<br>  def build_max_heap(array):<br>    for i in range(len(array) // 2, -1, -1):<br>      max_heapify(array, i)<br><br>  def max_heapify(array, i):<br>    left = 2 * i + 1<br>    right = 2 * i + 2<br><br>    largest = i<br><br>    if left &lt; len(array) and array[left] &gt; array[largest]:<br>      largest = left<br><br>    if right &lt; len(array) and array[right] &gt; array[largest]:<br>      largest = right<br><br>    if largest != i:<br>      array[i], array[largest] = array[largest], array[i]<br>      max_heapify(array, largest)<br><br>  build_max_heap(array)<br><br>  for i in range(len(array) - 1, 0, -1):<br>    array[i], array[0] = array[0], array[i]<br>    max_heapify(array, 0)<br><br># Example usage:<br><br>array = [5, 3, 2, 1, 4]<br><br>heapsort(array)<br><br>print(array)</pre><p>The above example code of heapsort uses a technique called “in-place sorting”. This involves sorting the array in place without creating a new array. This can significantly improve the performance of the algorithm, especially for large arrays.</p><h4>7. Radix sort</h4><p>Radix sort is a non-comparison sorting algorithm that sorts an array by repeatedly comparing the digits of the elements.</p><p><strong>When to Use?</strong></p><ul><li>When sorting an array of integers.</li><li>Radix sort is a very fast sorting algorithm, but it is not stable.</li><li>Radix sort is not as efficient as merge sort for large arrays with many unique elements.</li></ul><p><strong>Python Example Code:</strong></p><pre>def radix_sort(array):<br>  def counting_sort(array, digit):<br>    buckets = [0] * 10<br><br>    for element in array:<br>      buckets[element // digit % 10] += 1<br><br>    for i in range(1, 10):<br>      buckets[i] += buckets[i - 1]<br><br>    sorted_array = []<br><br>    for i in range(len(array) - 1, -1, -1):<br>      bucket = buckets[array[i] // digit % 10]<br>      sorted_array.insert(bucket, array[i])<br>      buckets[array[i] // digit % 10] -= 1<br><br>    return sorted_array<br><br>  max_element = max(array)<br>  max_digits = len(str(max_element))<br><br>  for digit in range(max_digits - 1, -1, -1):<br>    array = counting_sort(array, digit)<br><br># Example usage:<br><br>array = [5, 3, 2, 1, 4]<br><br>radix_sort(array)<br><br>print(array)</pre><p>The above example code of radix sort uses a technique called “counting sort”. This involves counting the number of occurrences of each digit and then using that information to sort the array. This can significantly improve the performance of the algorithm, especially for large arrays with unique digits.</p><h4><em>8. A search</em>*</h4><p><strong>A* search</strong> is a graph algorithm that finds the shortest path between two nodes in a graph. It is a heuristic search algorithm, which means that it uses a heuristic function to estimate the cost of reaching the goal node.</p><p><strong>When to Use?</strong></p><ul><li>When finding the shortest path between two nodes in a graph.</li><li>A* search is a heuristic search algorithm, which means that it uses a heuristic function to estimate the cost of reaching the goal node.</li><li>A* search is typically more efficient than other graph search algorithms, such as BFS and DFS.</li></ul><p><strong>Python Example Code:</strong></p><pre>class Node:<br>  def __init__(self, state, parent, cost, heuristic):<br>    self.state = state<br>    self.parent = parent<br>    self.cost = cost<br>    self.heuristic = heuristic<br><br>def a_star_search(graph, start_node, goal_node):<br>  open_list = [Node(start_node, None, 0, heuristic(start_node, goal_node))]<br>  closed_list = set()<br><br>  while open_list:<br>    current_node = min(open_list, key=lambda node: node.cost + node.heuristic)<br><br>    if current_node.state == goal_node:<br>      return current_node<br><br>    open_list.remove(current_node)<br>    closed_list.add(current_node.state)<br><br>    for neighbor in graph[current_node.state]:<br>      if neighbor not in closed_list:<br>        new_cost = current_node.cost + 1<br>        new_heuristic = heuristic(neighbor, goal_node)<br><br>        new_node = Node(neighbor, current_node, new_cost, new_heuristic)<br><br>        if neighbor in open_list:<br>          if new_cost &lt; open_list[neighbor].cost:<br>            open_list[neighbor] = new_node<br>        else:<br>          open_list.append(new_node)<br><br>  return None<br><br># Example usage:<br><br>graph = {<br>  0: [1, 2],<br>  1: [3, 4],<br>  2: [5, 6],<br>  3: [],<br>  4: [],<br>  5: [],<br>  6: []<br>}<br><br>start_node = 0<br>goal_node = 6<br><br>def heuristic(node, goal_node):<br>  return abs(node - goal_node)<br><br>path = a_star_search(graph, start_node, goal_node)<br><br>if path is not None:<br>  print(&quot;The shortest path is:&quot;, path.state)<br>else:<br>  print(&quot;There is no path to the goal node&quot;)</pre><p>The above example code of A* search uses a technique called “binary heap”. This involves storing the nodes in the open list in a binary heap, which is a data structure that allows for efficient retrieval of the minimum element. This can significantly improve the performance of the algorithm, especially for large graphs.</p><h4>9. Dijkstra’s algorithm</h4><p><strong>Dijkstra’s algorithm </strong>is a graph algorithm that finds the shortest path between a single source node and all other nodes in a graph. It is a non-greedy algorithm, which means that it does not always choose the best path at each step. However, it is guaranteed to find the shortest path to each node.</p><p><strong>When to Use?</strong></p><ul><li>When finding the shortest path between a single source node and all other nodes in a graph.</li><li>Dijkstra’s algorithm is a non-greedy algorithm, which means that it does not always choose the best path at each step. However, it is guaranteed to find the shortest path to each node.</li><li>Dijkstra’s algorithm is typically more efficient than other graph search algorithms, such as BFS and DFS.</li></ul><p><strong>Python Example Code:</strong></p><pre>def dijkstra(graph, start_node):<br>  distances = {}<br>  visited = set()<br><br>  distances[start_node] = 0<br><br>  while distances:<br>    current_node = min(distances, key=distances.get)<br><br>    visited.add(current_node)<br><br>    for neighbor in graph[current_node]:<br>      if neighbor not in visited:<br>        new_distance = distances[current_node] + 1<br><br>        if neighbor not in distances or new_distance &lt; distances[neighbor]:<br>          distances[neighbor] = new_distance<br><br>  return distances<br><br># Example usage:<br><br>graph = {<br>  0: [1, 2],<br>  1: [3, 4],<br>  2: [5, 6],<br>  3: [],<br>  4: [],<br>  5: [],<br>  6: []<br>}<br><br>start_node = 0<br><br>distances = dijkstra(graph, start_node)<br><br>print(&quot;The shortest distances from the start node are:&quot;, distances)</pre><p>The above example code of Dijkstra’s algorithm uses a technique called “binary heap”. This involves storing the nodes in the distances dictionary in a binary heap, which is a data structure that allows for efficient retrieval of the minimum element. This can significantly improve the performance of the algorithm, especially for large graphs.</p><h4><strong>10. Bellman-Ford algorithm</strong></h4><p>The Bellman-Ford algorithm is a dynamic programming algorithm, which means that it builds up the solution to the problem by solving smaller subproblems. It is similar to Dijkstra’s algorithm, but it can handle graphs with negative edge weights.</p><p><strong>When to Use?</strong></p><ul><li>When finding the shortest path between a single source node and all other nodes in a graph with negative edge weights.</li><li>The Bellman-Ford algorithm is a dynamic programming algorithm, which means that it builds up the solution to the problem by solving smaller subproblems.</li><li>The Bellman-Ford algorithm is typically more efficient than other graph search algorithms for graphs with negative edge weights.</li></ul><p><strong>Python Example Code:</strong></p><pre>def bellman_ford(graph, start_node):<br>  distances = {}<br>  predecessors = {}<br><br>  for node in graph:<br>    distances[node] = float(&#39;inf&#39;)<br>    predecessors[node] = None<br><br>  distances[start_node] = 0<br><br>  for i in range(len(graph) - 1):<br>    for node in graph:<br>      for neighbor in graph[node]:<br>        new_distance = distances[node] + graph[node][neighbor]<br><br>        if new_distance &lt; distances[neighbor]:<br>          distances[neighbor] = new_distance<br>          predecessors[neighbor] = node<br><br>  # Check for negative cycles<br>  for node in graph:<br>    for neighbor in graph[node]:<br>      new_distance = distances[node] + graph[node][neighbor]<br><br>      if new_distance &lt; distances[neighbor]:<br>        return False<br><br>  return distances, predecessors<br><br># Example usage:<br><br>graph = {<br>  0: {(1, 1), (2, 5)},<br>  1: {(2, 3)},<br>  2: {(3, 1)}<br>}<br><br>start_node = 0<br><br>distances, predecessors = bellman_ford(graph, start_node)<br><br>print(&quot;The shortest distances from the start node are:&quot;, distances)<br>print(&quot;The shortest paths from the start node are:&quot;, predecessors)</pre><p>The above example code of the Bellman-Ford algorithm uses a technique called “path relaxation”. This involves repeatedly iterating over the edges of the graph and updating the distances to the nodes. This can significantly improve the performance of the algorithm, especially for large graphs.</p><h3>Conclusion</h3><p>These are the top 10 programming algorithms that every programmer should know. These algorithms are used in a wide variety of applications, from web development to machine learning. By understanding these algorithms and how to implement them, you can become a better programmer and solve problems more efficiently.</p><h3>Thinks</h3><p>Writing has always been my passion and it gives me pleasure to help and inspire people. If you have any questions, feel free to reach out!</p><p>Thank you for reading this far, please give this article a round of applause if you can, or give me a follow, I will thank you from the bottom of my heart</p><p><a href="https://www.buymeacoffee.com/jasonkam">jasonkam</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba4d8b43a58f" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/top-10-programming-algorithms-every-programmer-should-know-and-when-to-use-them-ba4d8b43a58f">Top 10 Programming Algorithms Every Programmer Should Know (and When to Use Them)</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[4 Advanced Backend Development Patterns to Master in 2023]]></title>
            <link>https://levelup.gitconnected.com/4-advanced-backend-development-patterns-to-master-in-2023-e3359afa9054?source=rss-a7a4ff11fe52------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3359afa9054</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jason Kam]]></dc:creator>
            <pubDate>Sat, 30 Sep 2023 09:25:47 GMT</pubDate>
            <atom:updated>2023-10-13T01:38:12.708Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B73IDPEf-LH2y1CFvCDJng.jpeg" /><figcaption>Advanced Backend Development Patterns</figcaption></figure><h3>Introduction</h3><p>Advanced backend development patterns are reusable solutions to common problems that software developers encounter when developing the backend of web applications. These patterns can help developers to write more efficient, scalable, and maintainable code.</p><p>In this article, we will discuss some of the most advanced backend development patterns that you should master in 2023. We will also provide example code for each pattern to help you understand how to use it in your own projects.</p><blockquote><strong>Follow Me to Stay Up to Date for More Tips &amp; Tricks! </strong><em>🔔😜</em></blockquote><h3>Advanced Backend Development Patterns</h3><h4>Backend for Frontend (BFF)</h4><p>The BFF pattern is a design pattern that allows you to develop separate backends for different types of clients. This can be useful for improving performance and scalability, as well as for making it easier to develop and maintain your application.</p><p><strong>Example code:</strong></p><pre>class BFF:<br>    def __init__(self, client_type):<br>        self.client_type = client_type<br><br>    def get_data(self):<br>        if self.client_type == &quot;web&quot;:<br>            return self.get_web_data()<br>        elif self.client_type == &quot;mobile&quot;:<br>            return self.get_mobile_data()<br>        else:<br>            raise Exception(&quot;Unknown client type&quot;)<br>    def get_web_data(self):<br>        # ...<br>    def get_mobile_data(self):<br>        # ...<br># Example usage<br>bff = BFF(&quot;web&quot;)<br>data = bff.get_data()</pre><h4>Command Query Responsibility Segregation (CQRS)</h4><p>The CQRS pattern is a design pattern that separates the reading and writing of data into separate models and operations. This can help to improve performance and scalability, as well as to make your code more modular and reusable.</p><p><strong>Example code:</strong></p><pre>class Command:<br>    def execute(self):<br>        # ...<br>class Query:<br>    def execute(self):<br>        # ...<br>class CommandHandler:<br>    def handle(self, command):<br>        # ...<br>class QueryHandler:<br>    def handle(self, query):<br>        # ...<br><br># Example usage<br>command = MyCommand()<br>command_handler = CommandHandler()<br>command_handler.handle(command)<br>query = MyQuery()<br>query_handler = QueryHandler()<br>result = query_handler.handle(query)</pre><h4>Event Sourcing</h4><p>Event sourcing is a design pattern that records all changes to data as a sequence of events. This can be useful for auditing purposes, as well as for making it easier to recover from data loss or corruption.</p><p><strong>Example code:</strong></p><pre>class Event:<br>    def __init__(self, type, data):<br>        self.type = type<br>        self.data = data<br><br>class EventStore:<br>    def save(self, event):<br>        # ...<br>    def get_all_events(self):<br>        # ...<br><br>class AggregateRoot:<br>    def __init__(self, id):<br>        self.id = id<br>        self.events = []<br>    def apply_event(self, event):<br>        self.events.append(event)<br>    def get_state(self):<br>        # ...<br><br># Example usage<br>aggregate_root = AggregateRoot(1)<br>event = MyEvent(data)<br>aggregate_root.apply_event(event)<br>event_store = EventStore()<br>event_store.save(event)<br>state = aggregate_root.get_state()</pre><h4>Microservices Architecture</h4><p>A microservices architecture is a software design pattern that structures an application as a collection of loosely coupled services. This can make applications more scalable, resilient, and easier to develop and maintain.</p><pre>class UserService:<br>    def get_user(self, id):<br>        # ...<br><br>class ProductService:<br>    def get_product(self, id):<br>        # ...<br><br># Example usage<br>user_service = UserService()<br>product_service = ProductService()<br>user = user_service.get_user(1)<br>product = product_service.get_product(2)</pre><p>By mastering the advanced backend development patterns that I have discussed in this article, you can write more efficient, scalable, and maintainable code that will help you to build better web applications. I encourage you to experiment with these patterns and see how they can help you to improve your own projects.</p><h3>Thinks</h3><p>Writing has always been my passion and it gives me pleasure to help and inspire people. If you have any questions, feel free to reach out!</p><p>Thank you for reading this far, please give this article a round of applause if you can, or give me a follow, I will thank you from the bottom of my heart</p><p><a href="https://www.buymeacoffee.com/jasonkam">jasonkam</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3359afa9054" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/4-advanced-backend-development-patterns-to-master-in-2023-e3359afa9054">4 Advanced Backend Development Patterns to Master in 2023</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[4 Essential React Advanced Patterns for 2023: Upgrade Your Skills and Build Better Apps]]></title>
            <link>https://javascript.plainenglish.io/4-essential-react-advanced-patterns-for-2023-upgrade-your-skills-and-build-better-apps-a6023cdb85b3?source=rss-a7a4ff11fe52------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6023cdb85b3</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Jason Kam]]></dc:creator>
            <pubDate>Sat, 30 Sep 2023 09:14:14 GMT</pubDate>
            <atom:updated>2023-10-13T00:38:12.364Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="4 Essential React Advanced Patterns for 2023: Upgrade Your Skills and Build Better Apps" src="https://cdn-images-1.medium.com/max/1024/1*rzptKzyYbZjNHC44j12VKA.jpeg" /><figcaption>Essential React Advanced Patterns</figcaption></figure><h3>Introduction</h3><p>React is one of the most popular JavaScript libraries for building user interfaces. It’s known for its simplicity, flexibility, and performance. However, as React applications become more complex, it can be difficult to manage state, handle asynchronous input, and maintain a scalable architecture.</p><p>In this article, we’ll discuss four advanced React patterns that can help you overcome these challenges and build better React applications:</p><ul><li>Backend for Frontend (BFF) pattern</li><li>Hooks pattern</li><li>Higher-Order Component (HOC) pattern</li><li>Observer pattern</li></ul><h3>Backend for Frontend (BFF) pattern</h3><p>The Backend for Frontend (BFF) pattern is a design pattern for developing APIs that are tailored to the specific needs of different front-end clients. This pattern can be useful for decoupling the front-end and back-end of a React application, which can improve scalability and maintainability.</p><p>Here is an example of how to use the BFF pattern to implement a simple chat application:</p><h4><strong>Back-end API</strong></h4><pre>const express = require(&#39;express&#39;);<br><br>const app = express();<br><br>app.get(&#39;/messages&#39;, (req, res) =&gt; {<br>  // Get the messages from the database<br>  const messages = [];<br>  // Send the messages to the front-end client<br>  res.json(messages);<br>});<br><br>app.post(&#39;/messages&#39;, (req, res) =&gt; {<br>  // Add the new message to the database<br>  const message = req.body;<br>  // Send a confirmation response to the front-end client<br>  res.status(201).json({ message });<br>});<br><br>app.listen(3000, () =&gt; {<br>  console.log(&#39;Server is listening on port 3000&#39;);<br>});</pre><h4><strong>Front End React Application</strong></h4><pre>import React, { useState, useEffect } from &#39;react&#39;;<br>import axios from &#39;axios&#39;;<br><br>const App = () =&gt; {<br>  const [messages, setMessages] = useState([]);<br>  useEffect(() =&gt; {<br>    // Fetch the messages from the back-end API<br>    axios.get(&#39;/messages&#39;).then((response) =&gt; {<br>      setMessages(response.data);<br>    });<br>  }, []);<br>  const sendMessage = (message) =&gt; {<br>    // Send the message to the back-end API<br>    axios.post(&#39;/messages&#39;, { message });<br>  };<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Chat&lt;/h1&gt;<br>      &lt;ul&gt;<br>        {messages.map((message) =&gt; (<br>          &lt;li key={message.id}&gt;{message.text}&lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>      &lt;input type=&quot;text&quot; value={message} onChange={(e) =&gt; setMessage(e.target.value)} /&gt;<br>      &lt;button onClick={() =&gt; sendMessage(message)}&gt;Send&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default App;</pre><p>In this example, the back-end API provides a simple endpoint for getting and sending messages. The front-end React application uses the axios library to fetch and send messages to the back-end API.</p><h3>Hooks pattern</h3><p>The Hooks pattern is a new way to manage state and side effects in React applications. Hooks were introduced in React 16.8, and they have become increasingly popular since then.</p><p>Hooks provide a number of advantages over the traditional way of managing state and side effects in React. For example, hooks are easier to compose and reuse, and they can make your code more concise and readable.</p><p>Here is an example of how to use the Hooks pattern to implement a simple state management solution:</p><pre>import React, { useState } from &#39;react&#39;;<br><br>const Counter = () =&gt; {<br>  const [count, setCount] = useState(0);<br>  const increment = () =&gt; {<br>    setCount(count + 1);<br>  };<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Counter&lt;/h1&gt;<br>      &lt;p&gt;{count}&lt;/p&gt;<br>      &lt;button onClick={increment}&gt;Increment&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default Counter;</pre><p>In this example, the useState hook is used to manage the state of the counter. The increment function is used to increment the counter by one.</p><h3>Higher-Order Component (HOC) pattern</h3><p>The Higher-Order Component (HOC) pattern is a design pattern for creating reusable React components. HOCs take an existing component and return a new component that wraps the existing component and adds additional functionality.</p><p>HOCs can be used to add a variety of functionality to React components, such as state management, error handling, and logging.</p><p>Here is an example of how to use the HOC pattern to implement a simple state management solution:</p><pre>import React, { useState } from &#39;react&#39;;<br><br>const withState = (Component) =&gt; {<br>  const WrapperComponent = (props) =&gt; {<br>    const [state, setState] = useState(props.initialState);<br>    return &lt;Component {...props} state={state} setState={setState} /&gt;;<br>  };<br>  return WrapperComponent;<br>};<br><br>const Counter = ({ state, setState }) =&gt; {<br>  const increment = () =&gt; {<br>    setState({ count: state.count + 1 });<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Counter&lt;/h1&gt;<br>      &lt;p&gt;{state.count}&lt;/p&gt;<br>      &lt;button onClick={increment}&gt;Increment&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>const ConnectedCounter = withState(Counter);<br><br>export default ConnectedCounter;</pre><p>In this example, the withState HOC is used to add state management functionality to the Counter component. The ConnectedCounter component is the result of wrapping the Counter component with the withState HOC.</p><h3>Observer pattern</h3><p>The Observer pattern is a design pattern that allows objects to be notified of changes to other objects. This pattern can be useful for implementing real-time data updates and other state-based logic in React applications.</p><p>Here is an example of how to use the Observer pattern to implement a simple real-time chat application:</p><pre>import React, { useState, useEffect } from &#39;react&#39;;<br><br>const ChatContext = React.createContext();<br><br>const ChatProvider = ({ children }) =&gt; {<br>  const [messages, setMessages] = useState([]);<br>  const sendMessage = (message) =&gt; {<br>    setMessages([...messages, message]);<br>  };<br>  useEffect(() =&gt; {<br>    // Subscribe to real-time chat updates<br>  }, []);<br>  return (<br>    &lt;ChatContext.Provider value={{ messages, sendMessage }}&gt;<br>      {children}<br>    &lt;/ChatContext.Provider&gt;<br>  );<br>};<br><br>const ChatConsumer = ({ children }) =&gt; {<br>  const { messages } = React.useContext(ChatContext);<br>  return &lt;ul&gt;{messages.map((message) =&gt; &lt;li key={message.id}&gt;{message.text}&lt;/li&gt;)}&lt;/ul&gt;;<br>};<br><br>const App = () =&gt; {<br>  return (<br>    &lt;ChatProvider&gt;<br>      &lt;div&gt;<br>        &lt;h1&gt;Real-Time Chat&lt;/h1&gt;<br>        &lt;ChatConsumer /&gt;<br>      &lt;/div&gt;<br>    &lt;/ChatProvider&gt;<br>  );<br>};<br><br>export default App;</pre><p>In this example, the ChatContext context is used to share the state of the chat application with all of its descendant components. The ChatProvider component provides the chat state to its descendant components, and the ChatConsumer component consumes the chat state and renders the messages.</p><p>The useEffect hook in the ChatProvider component is used to subscribe to real-time chat updates. When the messages state changes, all of the ChatConsumer components will be re-rendered.</p><h3>Conclusion</h3><p>By mastering these four advanced React patterns, you can supercharge your React skills and build better React applications.</p><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><strong><em>(X</em></strong>), <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, and <a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6023cdb85b3" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/4-essential-react-advanced-patterns-for-2023-upgrade-your-skills-and-build-better-apps-a6023cdb85b3">4 Essential React Advanced Patterns for 2023: Upgrade Your Skills and Build Better Apps</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prompt Engineering for Programming: The Future and its Benefits with Python Examples]]></title>
            <link>https://levelup.gitconnected.com/prompt-engineering-for-programming-the-future-and-its-benefits-with-python-examples-d9691ae46404?source=rss-a7a4ff11fe52------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9691ae46404</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Jason Kam]]></dc:creator>
            <pubDate>Sat, 30 Sep 2023 07:58:59 GMT</pubDate>
            <atom:updated>2023-10-09T02:14:17.899Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yomRNjlAN1dziEsaDS92SA.jpeg" /><figcaption>Prompt Engineering for Programming</figcaption></figure><p><strong>Prompt engineering</strong> is a new and rapidly growing field that is revolutionizing the way we interact with computers. It is the process of designing and crafting prompts for large language models (LLMs) in order to elicit desired responses. LLMs are a type of artificial intelligence (AI) that can generate and understand text, translate languages, write different kinds of creative content, and answer your questions in an informative way.</p><blockquote><strong>Follow Me to Stay Up to Date for More Tips &amp; Tricks! </strong><em>🔔😜</em></blockquote><p>Prompt engineering has the potential to revolutionize the way we program computers. By designing and crafting prompts that are specific and clear, we can instruct LLMs to generate code that meets our specific needs. This can save us time and effort, and it can also help us to write better code.</p><h3>Why is prompt engineering the future of programming?</h3><p>There are a number of reasons why prompt engineering is the future of programming. First, LLMs are becoming increasingly powerful and sophisticated. They are now able to generate code that is of high quality and that is often indistinguishable from human-written code. Second, prompt engineering techniques are becoming more advanced. This means that we are now able to craft prompts that are more specific and more likely to elicit the desired response from the LLM.</p><h3>Benefits of prompt engineering for programming</h3><p>There are many benefits to using prompt engineering for programming. Here are a few examples:</p><ul><li><strong>Increased productivity: </strong>Prompt engineering can help us to write code more quickly and efficiently. By using prompts to generate code snippets or even entire functions, we can avoid having to write the code ourselves.</li><li><strong>Improved code quality:</strong> Prompt engineering can help us to write better code. By using prompts to specify the desired behavior of the code, we can help the LLM to generate code that is more accurate, efficient, and maintainable.</li><li><strong>Reduced errors: </strong>Prompt engineering can help us to reduce the number of errors in our code. By using prompts to generate code snippets that have been tested and verified, we can help to ensure that our code is bug-free.</li><li><strong>Increased creativity:</strong> Prompt engineering can help us to be more creative in our programming. By using prompts to experiment with different ideas and approaches, we can generate code that we would not have thought of otherwise.</li></ul><h3>Python examples of prompt engineering for programming</h3><p>Here are a few Python examples of how prompt engineering can be used for programming:</p><h4><strong>Generating code snippets:</strong></h4><p><strong>Prompt:</strong></p><pre>Generate a Python code snippet for sorting a list of numbers in ascending order.</pre><p><strong>Response:</strong></p><pre>def sort_ascending(list):<br>    list.sort()<br>    return list</pre><h4><strong>Generating entire functions:</strong></h4><p><strong>Prompt:</strong></p><pre>Generate a Python function for calculating the factorial of a number</pre><p><strong>Response:</strong></p><pre>def factorial(number):<br>    if n == 0:<br>        return 1<br>    else:<br>        return n * factorial(n - 1)</pre><h4><strong>Translating code from one language to another:</strong></h4><p><strong>Prompt:</strong></p><pre>Translate the following Python function to JavaScript:<br><br>def factorial(n):<br>    if n == 0:<br>        return 1<br>    else:<br>        return n * factorial(n - 1)</pre><p><strong>Response:</strong></p><pre>function factorial(n) {<br>  if (n === 0) {<br>    return 1;<br>  } else {<br>    return n * factorial(n - 1);<br>  }<br>}</pre><h4>Optimizing code:</h4><p>One way to use prompt engineering to optimize code is to start by identifying a piece of code that could be improved. For example, you might have a function that is long and complex, or you might have a loop that could be made more efficient.</p><p>Once you have identified a piece of code that could be improved, you can use prompt engineering to generate different options for optimization. For example, you could prompt the LLM to generate a more efficient version of the function, or you could prompt it to generate a different algorithm for the loop.</p><p>Once you have generated a number of options for optimization, you can test them out to see which one works the best. You can also use the LLM to help you debug the code and ensure that it is still working correctly after the optimization.</p><p>Here is an example of how prompt engineering could be used to optimize a simple Python code snippet:</p><p><strong>Prompt:</strong></p><pre>Generate a more efficient version of the following sum_of_squares:<br><br># Original code:<br>def sum_of_squares(n):<br>    sum = 0<br>    for i in range(n):<br>        sum += i * i<br>    return sum</pre><p><strong>Response:</strong></p><pre>def sum_of_squares(n):<br>    return n * (n + 1) * (2 * n + 1) // 6</pre><p>The second version of the sum_of_squares function is more efficient because it uses a mathematical formula to calculate the sum of squares instead of a loop.</p><p>Prompt engineering can be used to optimize code in a variety of ways. For example, it can be used to:</p><ul><li>Make code more efficient</li><li>Reduce the number of lines of code</li><li>Improve the readability of code</li><li>Make code more robust to errors</li></ul><p>Suppose you are working on a large and complex software project. You have a number of functions that are long and complex, and you are concerned about their performance. You can use prompt engineering to generate more efficient versions of these functions.</p><p>You can also use prompt engineering to identify and fix performance bottlenecks in your code. For example, you can prompt the LLM to identify any areas of code that are using excessive resources, such as CPU or memory.</p><h4>Refactor Code:</h4><p>One way to use prompt engineering to refactor code is to start by identifying a piece of code that could be improved. For example, you might have a function that is long and complex, or you might have a piece of code that is duplicated in multiple places.</p><p>Once you have identified a piece of code that could be improved, you can use prompt engineering to generate different options for refactoring. For example, you could prompt the LLM to generate a more modular version of the function, or you could prompt it to generate a single function that can be used to replace the duplicated code.</p><p>Once you have generated a number of options for refactoring, you can test them out to see which one works the best. You can also use the LLM to help you debug the code and ensure that it is still working correctly after the refactoring.</p><p>Here is an example of how prompt engineering could be used to refactor a simple Python code snippet:</p><p><strong>Original Code:</strong></p><pre>Generate a more modular version of the following function:<br><br>def calculate_shipping_cost(weight, distance):<br>    if weight &lt;= 1:<br>        cost = 5<br>    elif weight &lt;= 5:<br>        cost = 10<br>    else:<br>        cost = 15<br>    if distance &lt;= 100:<br>        cost += 5<br>    elif distance &lt;= 200:<br>        cost += 10<br>    else:<br>        cost += 15<br>    return cost</pre><p><strong>Response:</strong></p><pre>def calculate_shipping_cost(weight, distance):<br>    weight_cost = calculate_weight_cost(weight)<br>    distance_cost = calculate_distance_cost(distance)<br>    total_cost = weight_cost + distance_cost<br>    return total_cost<br><br>def calculate_weight_cost(weight):<br>    if weight &lt;= 1:<br>        cost = 5<br>    elif weight &lt;= 5:<br>        cost = 10<br>    else:<br>        cost = 15<br>    return cost<br><br>def calculate_distance_cost(distance):<br>    if distance &lt;= 100:<br>        cost = 5<br>    elif distance &lt;= 200:<br>        cost = 10<br>    else:<br>        cost = 15<br>    return cost</pre><p>The second version of the <strong>calculate_shipping_cost function</strong> is more modular because it breaks down the calculation into two separate functions: <strong>calculate_weight_cost()</strong> and <strong>calculate_distance_cost()</strong>. This makes the code easier to read and maintain, and it also makes it easier to reuse the code in other parts of the project.</p><p>Prompt engineering can be used to refactor code in a variety of ways. For example, it can be used to:</p><ul><li>Break down large and complex functions into smaller, more manageable functions</li><li>Eliminate duplicate code</li><li>Improve the readability and maintainability of code</li><li>Make code more reusable</li></ul><h3>Future of prompt engineering for programming</h3><p>Prompt engineering is still a new field, but it has the potential to revolutionize the way we program computers. In the future, we can expect to see a wide range of new and innovative applications of prompt engineering for programming. For example, we may see prompt engineering being used to:</p><ul><li>Develop new programming languages</li><li>Create new tools for code generation and debugging</li><li>Automate many of the tasks that are currently performed by human programmers</li></ul><p>Overall, prompt engineering is a powerful new tool that has the potential to make programming more efficient, creative, and accessible to everyone.</p><h3>Thinks</h3><p>Writing has always been my passion and it gives me pleasure to help and inspire people. If you have any questions, feel free to reach out!</p><p>Thank you for reading this far, please give this article a round of applause if you can, or give me a follow, I will thank you from the bottom of my heart</p><p><a href="https://www.buymeacoffee.com/jasonkam">jasonkam</a></p><h2>Level Up Coding</h2><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li></ul><p>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></p><p><strong>🧠 AI Tools ⇒ </strong><a href="https://www.aimind.so/prompt-generator?utm_source=luc&amp;utm_medium=article"><strong>Become an AI prompt engineer</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9691ae46404" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/prompt-engineering-for-programming-the-future-and-its-benefits-with-python-examples-d9691ae46404">Prompt Engineering for Programming: The Future and its Benefits with Python Examples</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Code: The Secret to Writing Efficient and Elegant Software]]></title>
            <link>https://levelup.gitconnected.com/the-power-of-clean-code-unlocking-efficiency-and-elegance-7e778d9b99e8?source=rss-a7a4ff11fe52------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e778d9b99e8</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Jason Kam]]></dc:creator>
            <pubDate>Sat, 08 Jul 2023 14:02:28 GMT</pubDate>
            <atom:updated>2023-10-13T01:38:30.991Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Clean Code: The Secret to Writing Efficient and Elegant Software" src="https://cdn-images-1.medium.com/max/1024/1*K90-ttMhb6crxOV-UBmH1w.jpeg" /><figcaption>Clean Code: The Secret to Writing Efficient and Elegant Software</figcaption></figure><p>In the world of software development, clean code is like a breath of fresh air. It’s a concept that emphasizes writing code that is not only functional but also easy to read, understand, and maintain. Clean code is not just a matter of personal preference or aesthetics; it has tangible benefits that can save time, enhance collaboration, and prevent unnecessary headaches. In this article, we’ll explore the virtues of clean code and its practical advantages, backed by simple examples in Python.</p><blockquote><strong>Follow Me to Stay Up to Date for More Tips &amp; Tricks! </strong><em>🔔😜</em></blockquote><h3>1. Readability: The Universal Language</h3><p>Clean code is all about readability. When code is clean, it becomes a language that everyone can comprehend, regardless of their skill level or familiarity with the codebase. By using meaningful variable names, following consistent formatting conventions, and writing concise and clear code, you make it easier for yourself and others to understand the purpose and functionality of your code.</p><p>Let’s consider an example where a function checks if a number is more than 5:</p><pre># Unclean Code<br>def foo(x):<br>    if(x &gt; 5):<br>        return True<br>    else:<br>        return False</pre><p>In this unclean code example, the function foo lacks clarity due to poor naming and inconsistent indentation. Now, let&#39;s transform it into clean code:</p><pre># Clean Code<br>def isGreaterThanFive(number):<br>    if number &gt; 5:<br>        return True<br>    else:<br>        return False</pre><p>In the clean code example, the function isGreaterThanFive uses meaningful names and follows consistent indentation, making it easier to understand the purpose and flow of the code. Clean code acts as a universal language, facilitating effective collaboration among programmers.</p><h3>2. Collaboration: Building Bridges, Not Barriers</h3><p>Collaboration lies at the heart of successful software projects. Clean code fosters an environment of seamless teamwork by promoting clarity and eliminating confusion.</p><p>Let’s consider an example where multiple programmers are working on a project involving a sorting algorithm:</p><pre># Unclean Code<br>def sortArray(arr):<br>    n = len(arr)<br>    for i in range(n):<br>        for j in range(0, n-i-1):<br>            if arr[j] &gt; arr[j+1]:<br>                temp = arr[j]<br>                arr[j] = arr[j+1]<br>                arr[j+1] = temp<br>    return arr</pre><p>In this unclean code example, the sorting logic lacks clarity due to variable names like arr, n, and temp. Now, let&#39;s transform it into clean code:</p><pre># Clean Code<br>def bubbleSort(numbers):<br>    length = len(numbers)<br>    for currentIndex in range(length):<br>        for comparisonIndex in range(0, length - currentIndex - 1):<br>            if numbers[comparisonIndex] &gt; numbers[comparisonIndex + 1]:<br>                swap(numbers, comparisonIndex, comparisonIndex + 1)<br>    return numbers<br><br>def swap(array, firstIndex, secondIndex):<br>    array[firstIndex], array[secondIndex] = array[secondIndex], array[firstIndex]</pre><p>In the clean code example, the function bubbleSort and the helper function swap use descriptive names, making the code more readable and comprehensible to fellow programmers. Clean code streamlines collaboration, enabling teams to work harmoniously towards achieving project goals.</p><h3>3. Maintainability: A Lifesaver for Developers</h3><p>As software projects evolve, code inevitably requires maintenance and updates. Clean code significantly simplifies the process of making changes without introducing bugs or unintended consequences. By adhering to principles such as the Single Responsibility Principle (SRP) and keeping functions and classes focused on specific tasks, you can easily locate and modify specific sections of code, resulting in faster debugging, easier testing, and enhanced maintainability.</p><p>Let’s consider an example where a function calculates the sum of an array:</p><pre># Unclean Code<br>def sumArray(arr):<br>    sum = 0<br>    for i in range(len(arr)):<br>        sum += arr[i]<br>    return sum</pre><p>In this unclean code example, the function sumArray lacks readability due to poor naming choices and unnecessary use of the sum variable. Now, let&#39;s transform it into clean code:</p><pre># Clean Code<br>def calculateArraySum(numbers):<br>    total = 0<br>    for number in numbers:<br>        total += number<br>    return total</pre><p>In the clean code example, the function calculateArraySum uses descriptive names and eliminates the unnecessary variable, making the code more concise and maintainable. Clean code simplifies maintenance by reducing complexity and allowing developers to navigate through the codebase effortlessly.</p><h3>Conclusion</h3><p>Clean code is a transformative approach that revolutionizes collaboration and simplifies project maintenance in software development. By prioritizing readability, fostering seamless collaboration, and adhering to effective strategies, we can harness the power of clean code and unlock its potential. Embrace the journey of writing clean code, and witness the profound impact it has on the success and longevity of your software projects.</p><h3>Good Reads</h3><ul><li><a href="https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882">Clean Code: A Handbook of Agile Software Craftsmanship</a></li></ul><h3>Thinks</h3><p>Writing has always been my passion and it gives me pleasure to help and inspire people. If you have any questions, feel free to reach out!</p><p>Thank you for reading this far, please give this article a round of applause if you can, or give me a follow, I will thank you from the bottom of my heart</p><p><a href="https://www.buymeacoffee.com/jasonkam">jasonkam</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e778d9b99e8" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/the-power-of-clean-code-unlocking-efficiency-and-elegance-7e778d9b99e8">Clean Code: The Secret to Writing Efficient and Elegant Software</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>