<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ command - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ command - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Fri, 08 May 2026 11:10:28 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/command/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ cmd Delete Folder – How to Remove Files and Folders in Windows ]]>
                </title>
                <description>
                    <![CDATA[ Sometimes it's just faster to do things with the command line. In this quick tutorial we'll go over how to open Command Prompt, some basic commands and flags, and how to delete files and folders in Command Prompt. If you're already familiar with basi... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/cmd-delete-folder-how-to-remove-files-and-folders-in-windows/</link>
                <guid isPermaLink="false">66ac87ef6fb3204d41f56350</guid>
                
                    <category>
                        <![CDATA[ command ]]>
                    </category>
                
                    <category>
                        <![CDATA[ command line ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Windows ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Windows 10 ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kristofer Koishigawa ]]>
                </dc:creator>
                <pubDate>Fri, 13 Nov 2020 04:35:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5fc9bc71e6787e098393991d.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Sometimes it's just faster to do things with the command line.</p>
<p>In this quick tutorial we'll go over how to open Command Prompt, some basic commands and flags, and how to delete files and folders in Command Prompt.</p>
<p>If you're already familiar with basic DOS commands, feel free to <a class="post-section-overview" href="#how-to-delete-files-with-the-del-command">skip ahead</a>.</p>
<h2 id="heading-how-to-open-command-prompt">How to open Command Prompt</h2>
<p>To open Command Prompt, press the Windows key, and type in "cmd". </p>
<p>Then, click on "Run as Administrator":</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/12/run-command-prompt-as-administrator.jpg" alt="Screenshot showing how to open Command Prompt as an administrator" width="600" height="400" loading="lazy"></p>
<p>After that, you'll see a Command Prompt window with administrative privileges:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/12/command-prompt-new-window.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Screenshot of Command Prompt window</em></p>
<p>If you can't open Command Prompt as an administrator, no worries. You can open a normal Command Prompt window by clicking "Open" instead of "Run as Administrator".</p>
<p>The only difference is that you may not be able to delete some protected files, which shouldn't be a problem in most cases.</p>
<h2 id="heading-how-to-delete-files-with-the-del-command">How to delete files with the <code>del</code> command</h2>
<p>Now that Command Prompt is open, use <code>cd</code> to change directories to where your files are.</p>
<p>I've prepared a directory on the desktop called Test Folder. You can use the command <code>tree /f</code> to see a, well, tree, of all the nested files and folders:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/12/command-prompt-tree.jpg" alt="Screenshot after running tree /f in target directory" width="600" height="400" loading="lazy"></p>
<p>To delete a file, use the following command: <code>del "&lt;filename&gt;"</code>.</p>
<p>For example, to delete <code>Test file.txt</code>, just run <code>del "Test File.txt"</code>. </p>
<p>There may be a prompt asking if you want to delete the file. If so, type "y" and hit enter.</p>
<p><strong>Note:</strong> Any files deleted with the <code>del</code> command cannot be recovered. Be very careful where and how you use this command.</p>
<p>After that, you can run <code>tree /f</code> to confirm that your file was deleted:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/12/del-tree-check.jpg" alt="Screenshot after deleting file with del command" width="600" height="400" loading="lazy"></p>
<p>Also, bonus tip – Command Prompt has basic autocompletion. So you could just type in <code>del test</code>, press the tab key, and Command Prompt will change it to <code>del "Test File.txt"</code>.</p>
<h3 id="heading-how-to-force-delete-files-with-the-del-command">How to force delete files with the <code>del</code> command</h3>
<p>Sometimes files are marked as read only, and you'll see the following error when you try to use the <code>del</code> command:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/12/read-only-error.jpg" alt="Screenshot of error after trying to delete a read only file" width="600" height="400" loading="lazy"></p>
<p>To get around this, use the <code>/f</code> flag to force delete the file. For example, <code>del /f "Read Only Test File.txt"</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/12/del-force-flag.jpg" alt="Screenshot after deleting file with the force flag" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-delete-folders-with-the-rmdir-command">How to delete folders with the <code>rmdir</code> command</h2>
<p>To delete directories/folders, you'll need to use the <code>rmdir</code> or <code>rd</code> command. Both commands work the same way, but let's stick with <code>rmdir</code> since it's a bit more expressive.</p>
<p>Also, I'll use the terms directory and folder interchangeably for the rest of the tutorial. "Folder" is a newer term that became popular with early desktop GUIs, but folder and directory basically mean the same thing.</p>
<p>To remove a directory, just use the command <code>rmdir &lt;directory name&gt;</code>.</p>
<p><strong>Note:</strong> Any directories deleted with the <code>rmdir</code> command cannot be recovered. Be very careful where and how you use this command.</p>
<p>In this case I want to remove a directory named Subfolder, so I'll use the command <code>rmdir Subfolder</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/12/directory-not-empty.jpg" alt="Screenshot of a directory not empty error" width="600" height="400" loading="lazy"></p>
<p>But, if you remember earlier, Subfolder has a file in it named Nested Test File.</p>
<p>You could <code>cd</code> into the Subfolder directory and remove the file, then come back with <code>cd ..</code> and run the <code>rmdir Subfolder</code> command again, but that would get tedious. And just imagine if there were a bunch of other nested files and directories!</p>
<p>Like with the <code>del</code> command, there's a helpful flag we can use to make things much faster and easier.</p>
<h3 id="heading-how-to-use-the-s-flag-with-rmdir">How to use the <code>/s</code> flag with <code>rmdir</code></h3>
<p>To remove a directory, including all nested files and subdirectories, just use the <code>/s</code> flag:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/12/rmdir-s-flag.jpg" alt="Screenshot after running rmdir with the /s flag" width="600" height="400" loading="lazy"></p>
<p>There will probably be a prompt asking if you want to remove that directory. If so, just type "y" and hit enter.</p>
<p>And that's it! That should be everything you need to know to remove files and folders in the Windows Command Prompt.</p>
<p>All of these commands should work in PowerShell, which is basically Command Prompt version 2.0. Also, PowerShell has a bunch of cool aliases like <code>ls</code> and <code>clear</code> that should feel right at home if you're familiar with the Mac/Linux command line.</p>
<p>Did these commands help you? Are there any other commands that you find useful? Either way, let me know over on Twitter.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Linux LS Command – How to List Files in a Directory + Option Flags ]]>
                </title>
                <description>
                    <![CDATA[ Since the creation of Unix in the 1970s, a lot of operating systems have used it as their foundation. Many of these operating systems failed, while others succeeded. Linux is one of the most popular Unix based operating systems. It's open source, and... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-linux-ls-command-how-to-list-files-in-a-directory-with-options/</link>
                <guid isPermaLink="false">66d84e2ac15439a8d5631e49</guid>
                
                    <category>
                        <![CDATA[ command ]]>
                    </category>
                
                    <category>
                        <![CDATA[ command line ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Linux ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Bolaji Ayodeji ]]>
                </dc:creator>
                <pubDate>Thu, 03 Sep 2020 07:59:30 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/09/article-banner-7.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Since the creation of Unix in the 1970s, a lot of operating systems have used it as their foundation. Many of these operating systems failed, while others succeeded.</p>
<p>Linux is one of the most popular Unix based operating systems. It's open source, and is used all over the world across many industries.</p>
<p>One amazing feature of the Linux operating system is the Command Line Interface (CLI) which allows users to interact with their computer from a shell. The Linux shell is a REPL (<strong>R</strong>ead, <strong>E</strong>valuate, <strong>P</strong>rint, <strong>L</strong>oop) environment where users can enter a command and the shell runs it and returns a result.</p>
<p>The <code>ls</code> command is one of the many Linux commands that allow a user to list files or directories from the CLI.</p>
<p>In this article, we'll go in depth on the <code>ls</code> command and some of the most important flags you'll need day-to-day.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<ul>
<li><p>A computer with directories and files</p>
</li>
<li><p>Have one of the Linux distros installed</p>
</li>
<li><p>Basic knowledge of navigating around the CLI</p>
</li>
<li><p>A smile on your face :)</p>
</li>
</ul>
<h2 id="heading-the-linux-ls-command">The Linux ls Command</h2>
<p>The <code>ls</code> command is used to list files or directories in Linux and other Unix-based operating systems.</p>
<p>Just like you navigate in your <em>File explorer</em> or <em>Finder</em> with a GUI, the <code>ls</code> command allows you to list all files or directories in the current directory by default, and further interact with them via the command line.</p>
<p>Launch your terminal and type <code>ls</code> to see this in action:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/08/Screenshot-2020-08-20-at-9.40.29-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-list-files-in-a-directory-with-options">How to list Files in a Directory with Options</h2>
<p>The <code>ls</code> command also accepts some flags (also known as options) which are additional information that changes how files or directories are listed in your terminal.</p>
<p>In other words, flags change how the <code>ls</code> command works:</p>
<pre><code class="lang-python"> ls [flags] [directory]
</code></pre>
<blockquote>
<p>PS: The word <strong>contents</strong> used in throughout the article refers to the <strong>files and directories</strong> being listed, not the actual contents of the files/directories ?</p>
</blockquote>
<h3 id="heading-list-files-in-the-current-working-directory">List files in the current working directory</h3>
<p>Type the <code>ls</code> command to list the contents of the current working directory:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/08/Screenshot-2020-08-20-at-9.40.29-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-list-files-in-another-directory">List files in another directory</h3>
<p>Type the <code>ls [directory path here]</code> command to list the contents of another directory:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/08/Screenshot-2020-08-20-at-10.32.52-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-list-files-in-the-root-directory">List files in the root directory</h3>
<p>Type the <code>ls /</code> command to list the contents of the root directory:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/08/Screenshot-2020-08-20-at-10.46.10-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-list-files-in-the-parent-directory">List files in the parent directory</h3>
<p>Type the <code>ls ..</code> command to list the contents of the parent directory one level above. Use <code>ls ../..</code> for contents two levels above:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/08/Screenshot-2020-08-20-at-10.48.22-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-list-files-in-the-users-home-directory-homeuser">List files in the user's home directory (/home/user)</h3>
<p>Type the <code>ls ~</code> command to list the contents in the users's home directory:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/08/Screenshot-2020-08-20-at-10.51.19-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-list-only-directories">List only directories</h3>
<p>Type the <code>ls -d */</code> command to list only directories:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/08/Screenshot-2020-08-21-at-12.53.05-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-list-files-with-subdirectories">List files with subdirectories</h3>
<p>Type the <code>ls *</code> command to list the contents of the directory with it's subdirectories:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/08/Screenshot-2020-08-21-at-1.07.54-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-list-files-recursively">List files recursively</h3>
<p>Type the <code>ls -R</code> command to list all files and directories with their corresponding subdirectories down to the last file:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/09/Screenshot-2020-09-01-at-9.04.56-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<blockquote>
<p>If you have a lot of files, this can take a very long time to complete as every single file in each directory will be printed out. You can instead specify a directory to run this command in, like so: <code>ls Downloads -R</code></p>
</blockquote>
<h3 id="heading-list-files-with-their-sizes">List files with their sizes</h3>
<p>Type the <code>ls -s</code> command (the <strong>s</strong> is lowercase) to list files or directories with their sizes:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/08/Screenshot-2020-08-21-at-12.30.19-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-list-files-in-long-format">List files in long format</h3>
<p>Type the <code>ls -l</code> command to list the contents of the directory in a table format with columns including:</p>
<ul>
<li><p>content permissions</p>
</li>
<li><p>number of links to the content</p>
</li>
<li><p>owner of the content</p>
</li>
<li><p>group owner of the content</p>
</li>
<li><p>size of the content in bytes</p>
</li>
<li><p>last modified date / time of the content</p>
</li>
<li><p>file or directory name</p>
</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/08/Screenshot-2020-08-20-at-10.52.37-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-list-files-in-long-format-with-readable-file-sizes">List files in long format with readable file sizes</h3>
<p>Type the <code>ls -lh</code> command to list the files or directories in the same table format above, but with another column representing the size of each file/directory:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/08/Screenshot-2020-08-21-at-12.14.33-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Note that sizes are listed in bytes (B), megabytes (MB), gigabytes (GB), or terabytes (TB) when the file or directory's size is larger than 1024 bytes.</p>
<h3 id="heading-list-files-including-hidden-files">List files including hidden files</h3>
<p>Type the <code>ls -a</code> command to list files or directories including hidden files or directories. In Linux, anything that begins with a <code>.</code> is considered a hidden file:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/08/Screenshot-2020-08-21-at-11.12.26-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-list-files-in-long-format-including-hidden-files">List files in long format including hidden files</h3>
<p>Type the <code>ls -l -a</code> or <code>ls -a -l</code> or <code>ls -la</code> or <code>ls -al</code> command to list files or directories in a table format with extra information including hidden files or directories:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/08/Screenshot-2020-08-21-at-12.17.01-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-list-files-and-sort-by-date-and-time">List files and sort by date and time</h3>
<p>Type the <code>ls -t</code> command to list files or directories and sort by last modified date in descending order (biggest to smallest).</p>
<p>You can also add a <code>-r</code> flag to reverse the sorting order like so: <code>ls -tr</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/08/Screenshot-2020-08-21-at-12.20.09-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-list-files-and-sort-by-file-size">List files and sort by file size</h3>
<p>Type the <code>ls -S</code> (the <strong>S</strong> is uppercase) command to list files or directories and sort by size in descending order (biggest to smallest).</p>
<p>You can also add a <code>-r</code> flag to reverse the sorting order like so: <code>ls -Sr</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/08/Screenshot-2020-08-21-at-12.20.38-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-list-files-and-output-the-result-to-a-file">List files and output the result to a file</h3>
<p>Type the <code>ls &gt; output.txt</code> command to print the output of the preceding command into an <code>output.txt</code> file. You can use any of the flags discussed before like <code>-la</code> — the key point here is that the result will be outputted into a file and not logged to the command line.</p>
<p>Then you can use the file as you see fit, or log the contents of the file with <code>cat output.txt</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/09/Screenshot-2020-09-01-at-9.12.59-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>.</em></p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>There are tons of other commands and combinations you can explore to list out files and directories based on your needs. One thing to remember is the ability to combine multiple commands together at once.</p>
<p>Imagine you want to list a file in long format, including hidden files, and sort by file size. The command would be <code>ls -alS</code>, which is a combination of <code>ls -l</code>, <code>ls -a</code>, and <code>ls -S</code>.</p>
<p>If you forget any command or are unsure about what to do, you can run <code>ls --help</code> or <code>man ls</code> which will display a manual with all possible options for the <code>ls</code> command:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/09/Screenshot-2020-09-01-at-9.57.37-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Thanks for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python List Files in a Directory Guide - listdir VS system("ls") Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ 🔹 Welcome If you want to learn how these functions work behind the scenes and how you can use their full power, then this article is for you. We will start by diving into concepts that are essential to work with listdir and system: The built-in Pyt... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-list-files-in-a-directory-guide-listdir-vs-system-ls-explained-with-examples/</link>
                <guid isPermaLink="false">66b1f871444616a731246a0e</guid>
                
                    <category>
                        <![CDATA[ command ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Tutorial ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Estefania Cassingena Navone ]]>
                </dc:creator>
                <pubDate>Mon, 06 Apr 2020 14:10:27 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/04/listdir-vs-system-v2.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <h2 id="heading-welcome">🔹 Welcome</h2>
<p>If you want to learn how these functions work behind the scenes and how you can use their full power, then this article is for you.</p>
<p>We will start by diving into concepts that are essential to work with <code>listdir</code> and <code>system</code>:</p>
<ul>
<li>The built-in Python <code>os</code> module and how to import it.</li>
<li>The concepts of "directory" and "current working directory".</li>
<li>How to check and change your current working directory. </li>
<li>The difference between an absolute path and a relative path.</li>
</ul>
<p>Then, we will dive into the functions themselves:</p>
<ul>
<li>How to work with the <code>listdir</code> function and when to use it.</li>
<li>How to work with the <code>system("ls")</code> function and when to use it.</li>
<li>Examples of both of them and how they work behind the scenes.</li>
</ul>
<p>Let's begin! ⭐</p>
<h2 id="heading-the-os-module">🔸 The OS Module</h2>
<p>The two functions that we will discuss: <code>listdir()</code> and <code>system()</code> belong to the <code>os</code> module. This module includes functions that are used to interact with your operating system, performing actions like:</p>
<ul>
<li>Making a new directory.</li>
<li>Renaming an existing directory.</li>
<li>Removing a directory.</li>
<li>Displaying the path to your current working directory.</li>
<li>Much more! </li>
</ul>
<p><strong>💡 Tips:</strong> </p>
<ul>
<li>A <strong>directory</strong> is what we commonly know as a "folder", where we usually store related files and/or other directories, creating a hierarchy of directories within directories that are called subdirectories. An example of a directory is your "Documents" folder.</li>
<li>A <strong>module</strong> is a file that contains related Python code. </li>
</ul>
<h3 id="heading-how-to-import-the-os-module">How to Import the OS Module</h3>
<p>To use the <code>os</code> module in your script, you need to "import" it. Importing a module means gaining access to all the functions and variables that are stored within the module. We import a module when we want to use its code in our script. </p>
<p>To import the <code>os</code> module, you simply need to include this line at the top of your Python script or run this line in the interactive shell:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> os
</code></pre>
<p>This will give you access to all the functions defined in the <code>os</code> module.</p>
<p><strong>💡 Tip:</strong> this module was already installed when you installed Python 3, so you will be able to use it immediately.</p>
<p>To be able to use the functions from the <code>os</code> module, you will need to add the prefix <code>os.</code> before the name of the function that you want to call, like this:</p>
<pre><code class="lang-python">os.&lt;function&gt;(&lt;params&gt;)
</code></pre>
<p>For example:</p>
<pre><code>os.mkdir(<span class="hljs-string">"New Folder"</span>)
</code></pre><h3 id="heading-how-to-import-individual-functions">How to Import Individual Functions</h3>
<p>If you are only going to work with one or two functions from the module, you can import them individually using this syntax:</p>
<pre><code><span class="hljs-keyword">from</span> &lt;<span class="hljs-built_in">module</span>&gt; <span class="hljs-keyword">import</span> &lt;function1&gt;, <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">function2</span>&gt;</span>, ...</span>
</code></pre><p>For example:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> os <span class="hljs-keyword">import</span> listdir, system
</code></pre>
<p>In this case, you can call the functions in your script as you normally would, <strong>without</strong> adding the <code>os.</code> prefix, like this:</p>
<pre><code class="lang-python">&lt;function&gt;(&lt;params&gt;)
</code></pre>
<p>For example:</p>
<pre><code>mkdir(<span class="hljs-string">"New Folder"</span>)
</code></pre><h2 id="heading-current-working-directory">🔹 Current Working Directory</h2>
<p>Now let's see a very important concept that you need to know before you start working with <code>listdir</code> and <code>system</code>. Your current working directory, as the name implies, is the directory (folder) where you are currently working. </p>
<p>You can check your current working directory with this function from the <code>os</code> module:</p>
<pre><code class="lang-python">os.getcwd()
</code></pre>
<p>This will show you the path to your current working directory. </p>
<p>💡 <strong>Tip:</strong> <code>cwd</code> means "current working directory."</p>
<h3 id="heading-from-the-interactive-shell">From the Interactive Shell</h3>
<p>If I run this command in the interactive shell (Windows), I see this:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>os.getcwd()
<span class="hljs-string">'C:\\Users\\estef\\AppData\\Local\\Programs\\Python\\Python38-32'</span>
</code></pre>
<p>This is the full path to my current working directory:</p>
<pre><code class="lang-python"><span class="hljs-string">'C:\\Users\\estef\\AppData\\Local\\Programs\\Python\\Python38-32'</span>
</code></pre>
<h3 id="heading-from-a-script">From a Script</h3>
<p>If I run this command from a script, like this:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> os
print(os.getcwd())
</code></pre>
<p> I see:</p>
<pre><code class="lang-python">C:\Users\estef\Documents\freeCodeCamp\freeCodeCamp News\listdir vs system
</code></pre>
<p>The full path to the script (its location in the system, in the hierarchy of directories).</p>
<p>💡 <strong>Tip:</strong> If you run a script (a Python file), your current working directory is the directory where the script is currently in.</p>
<h3 id="heading-how-to-change-your-current-working-directory">How to Change your Current Working Directory</h3>
<p>You can change your current working directory with this command from the <code>os</code> module:</p>
<pre><code class="lang-python">os.chdir(&lt;path&gt;)
</code></pre>
<p>You will need to specify the path to the new working directory, passing it as an argument, formatted as a string. It can be either an absolute path or a relative path. </p>
<p>💡 <strong>Tip:</strong> </p>
<ul>
<li>An <strong>absolute path</strong> specifies all the sequence of directories that you need to go through to reach your target directory. This path starts from the root directory of your system. </li>
</ul>
<p>For example:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> os
<span class="hljs-meta">&gt;&gt;&gt; </span>os.chdir(<span class="hljs-string">r"C:\Users\estef\Documents\FreeCodeCamp\freeCodeCamp News\9 - listdir vs system"</span>)

<span class="hljs-comment"># Checking current working directory:</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>os.getcwd()
<span class="hljs-string">'C:\\Users\\estef\\Documents\\FreeCodeCamp\\freeCodeCamp News\\9 - listdir vs system'</span>
</code></pre>
<p>Notice that I added an <code>r</code> before the absolute path to convert the string into a raw string. If you use <code>\</code> and you don't add the <code>r</code>, you will get an error because the <code>\</code> symbol will be treated as a special character.</p>
<p>Alternatively, you could replace the backslashes  <code>\</code> with forward slashes <code>/</code> in the path:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>os.chdir(<span class="hljs-string">"C:/Users/estef/Documents/FreeCodeCamp/freeCodeCamp News/9 - listdir vs system"</span>)

<span class="hljs-comment"># Checking current working directory</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>os.getcwd()
<span class="hljs-string">'C:\\Users\\estef\\Documents\\FreeCodeCamp\\freeCodeCamp News\\9 - listdir vs system'</span>
</code></pre>
<ul>
<li>A <strong>relative path</strong> specifies the path that you want to follow to find the target directory, but now the path starts from your <strong>current</strong> working directory. It's shorter and simpler than the absolute path. </li>
</ul>
<p>For example, if your current working directory contains a subdirectory (folder) <code>Directory 1</code>, you can move to this directory using a relative path (imagine it as a folder within another folder, and we are going deeper and deeper into the hierarchy), like this:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> os
<span class="hljs-meta">&gt;&gt;&gt; </span>os.chdir(<span class="hljs-string">".\Directory 1"</span>)

<span class="hljs-comment"># Check current working directory</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>os.getcwd()
<span class="hljs-string">'C:\\Users\\estef\\Documents\\FreeCodeCamp\\freeCodeCamp News\\9 - listdir vs system\\Directory 1'</span>
</code></pre>
<p>💡 <strong>Tip:</strong> The dot (<code>.</code>) at the beginning of the relative path <code>.\Directory 1</code> represents the current working directory. A double dot ( <code>..</code>) is used to move up the hierarchy, to the "parent" directory.</p>
<p>Now that you have all the background knowledge that you will need to truly understand how <code>listdir</code> and <code>system</code> work, let's see them in detail.</p>
<h2 id="heading-listdir">🔸 Listdir</h2>
<p>We will start with the <code>listdir</code> function. Let's reveal its mysteries. ?</p>
<h3 id="heading-purpose-and-return-value">Purpose and Return Value</h3>
<p>According to the <a target="_blank" href="https://docs.python.org/3/library/os.html#os.listdir">Python Documentation</a>, the purpose of this function is to:</p>
<blockquote>
<p>Return a list containing the names of the entries in the directory given by <em>path</em>.</p>
</blockquote>
<p>Basically, this function returns a list with the names of all files and directories that are currently found within a particular directory that you specify when you call the function.</p>
<p>💡 <strong>Tip:</strong> The list will not have a specific order, even if you usually sort the elements alphabetically.</p>
<h3 id="heading-syntax-and-parameter">Syntax and Parameter</h3>
<p>To call <code>listdir</code>, will need to use this syntax:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/image-9.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The parameter <code>path</code> is precisely that, the absolute or relative path to the directory that you want to visualize. In Python 3.2 and above, this parameter is optional. By default, the path will lead to your current working directory if you don't pass an argument. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/image-12.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Remember that you must import the <code>os</code> module before calling this function.</p>
<p>💡 <strong>Tip:</strong> If you use this import statement <code>from os import listdir</code> to import the function individually, you can omit the <code>os.</code> prefix, like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/image-10.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-use-cases-and-advantages">Use Cases and Advantages</h3>
<p>The function <code>listdir</code> is very helpful because it works on any operating system where Python runs, so if Python is installed on your device, this function will work correctly. </p>
<p>Now let's talk a little bit about its return value. Since it returns a list, we can store this list in a variable and work with it in our program. </p>
<p>For example, let's say that we want to do something with all the files from a given directory, such as converting images to black and white or modifying their content. We could do it using a for loop, like this:</p>
<pre><code class="lang-python">images = os.listdir(&lt;path&gt;)

<span class="hljs-keyword">for</span> image <span class="hljs-keyword">in</span> images:
    <span class="hljs-comment"># Do something to the image</span>
</code></pre>
<p>Of course, you would need to define what happens within the loop, but this is an example of what you could do with this function. </p>
<p>This is awesome, right? </p>
<p>But having files and directories in the same list can be a little bit problematic if we want to work with a for loop, right? We would need to add a conditional to check the type of each element. How can we make a list that only contains file names (no directories) or vice versa? </p>
<p>Let's see! ✨</p>
<h3 id="heading-only-include-files">Only Include Files</h3>
<p>If you want to "filter" the list returned by <code>os.listdir()</code> to include only <strong>files</strong> (no directories) you can use this line of code:</p>
<pre><code class="lang-python">list(filter(os.path.isfile, os.listdir(&lt;path&gt;)))
</code></pre>
<p>💡 <strong>Tip:</strong> You can customize the <code>&lt;path&gt;</code> argument or omit it to use your current working directory.</p>
<p>Let's see an example with my current working directory (I'm using Windows):</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/image-23.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>My directory (folder) has:</p>
<ul>
<li>Two subdirectories (folders within the main folder)</li>
<li>One PowerPoint file</li>
<li>One image (.png file)</li>
<li>One Python script</li>
</ul>
<p>If I call the <code>listdir</code> function from the <code>script.py</code> file and print the list returned:</p>
<pre><code class="lang-python">print(os.listdir())
</code></pre>
<p>This is the output:</p>
<pre><code class="lang-python">[<span class="hljs-string">'Diagrams.ppt'</span>, <span class="hljs-string">'Directory 1'</span>, <span class="hljs-string">'Directory 2'</span>, <span class="hljs-string">'listdir vs system.png'</span>, <span class="hljs-string">'script.py'</span>]
</code></pre>
<p>You can see that all files and directories from my current working directory were included.</p>
<p>To filter the list to only contain files, we can use this statement:</p>
<pre><code class="lang-python">print(list(filter(os.path.isfile, os.listdir())))
</code></pre>
<p>Now the output is:</p>
<pre><code class="lang-python">[<span class="hljs-string">'Diagrams.ppt'</span>, <span class="hljs-string">'listdir vs system.png'</span>, <span class="hljs-string">'script.py'</span>]
</code></pre>
<p>Notice how the directories were "filtered", exactly what we wanted.</p>
<h3 id="heading-only-include-directories">Only Include Directories</h3>
<p>Similarly, if you want to "filter" the list to include only <strong>directories</strong>, you can use this line of code:</p>
<pre><code class="lang-python">list(filter(os.path.isdir, os.listdir(&lt;path&gt;)))
</code></pre>
<p>Now the output is:</p>
<pre><code>[<span class="hljs-string">'Directory 1'</span>, <span class="hljs-string">'Directory 2'</span>]
</code></pre><p>Exactly what we wanted. But how does this statement work behind the scenes? Let's see.</p>
<h3 id="heading-how-filter-works-behind-the-scenes">How <code>filter()</code> Works Behind the Scenes</h3>
<p>The filter function is called using this syntax:</p>
<pre><code>filter(&lt;function&gt;, &lt;list&gt;)
</code></pre><p>It basically "filters" the elements of the second argument (the list) based on the truth value returned by calling the function passed as the first argument (<code>os.path.isfile()</code> or <code>os.path.isdir()</code> in their respective commands):</p>
<pre><code class="lang-python">print(list(filter(os.path.isfile, os.listdir())))
</code></pre>
<pre><code class="lang-python">list(filter(os.path.isdir, os.listdir()))
</code></pre>
<p>These two functions:</p>
<pre><code>os.path.isfile(&lt;path&gt;)

os.path.isdir(&lt;path&gt;)
</code></pre><p>Return <code>True</code> if the argument is a file or a directory, respectively.  </p>
<p>Based on these truth values, the elements of the list will be included (or not) in the final "filtered" list. The elements of the list returned by <code>os.listdir()</code> are passed one by one to these functions to check if they are files (or directories, respectively).</p>
<p>For example: If we have this line of code:</p>
<pre><code class="lang-python">filter(os.path.isfile, os.listdir())))
</code></pre>
<p> And <code>os.listdir()</code> returns this list:</p>
<pre><code class="lang-python">[<span class="hljs-string">'Diagrams.ppt'</span>, <span class="hljs-string">'Directory 1'</span>, <span class="hljs-string">'Directory 2'</span>, <span class="hljs-string">'script.py'</span>]
</code></pre>
<p>The first element of the list (<code>'Diagrams.ppt'</code>) is passed as argument to <code>os.path.isfile()</code> to check if it's a file :</p>
<pre><code class="lang-python">os.path.isfile(<span class="hljs-string">'Diagrams.ppt'</span>) <span class="hljs-comment"># True</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/image-30.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The function call returns <code>True</code>, so it's a file and it's included in the list.</p>
<p>But if the element is a directory:</p>
<pre><code class="lang-python">os.path.isfile(<span class="hljs-string">'Directory 1'</span>) <span class="hljs-comment"># False</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/image-31.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The function call returns <code>False</code>, so it's not included in the list. This process continues for every element in the list until the new list only contains file names.</p>
<p>Then, since <code>filter()</code> returns an iterable, we make a list from this iterable using <code>list()</code>:</p>
<pre><code class="lang-python">list(filter(os.path.isfile, os.listdir()))
</code></pre>
<p>And we print it since we are working with a Python file (script):</p>
<pre><code class="lang-python">print(list(filter(os.path.isfile, os.listdir())))
</code></pre>
<p>💡 <strong>Tip:</strong> You can visually identify if an element of the list represents a file or a directory by seeing if it has an extension (type) after its name. For example: <code>Diagrams.ppt</code> has a <code>.ppt</code> extension that tells you that it's a PowerPoint file but a directory doesn't have an extension, like <code>'Directory 1'</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/image-32.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-systemls">🔹 System("ls")</h2>
<p>Now that you know how to work with <code>listdir</code>, let's see how the <code>system()</code> function works behind the scenes and how you can use it. </p>
<h3 id="heading-purpose">Purpose</h3>
<p>According to the <a target="_blank" href="https://docs.python.org/3/library/os.html#os.system">Python Documentation</a>, the purpose of the <code>system()</code> function is to:</p>
<blockquote>
<p>Execute the command (a string) in a subshell</p>
</blockquote>
<p>Basically, this function takes a command (as a string) and executes it. </p>
<p>In this case, the command that we are passing is <code>'ls'</code> , a Unix command used in Linux to display the content of a directory as standard output. </p>
<p>Unlike <code>listdir</code>, the <code>system()</code> function <strong>will not return a list</strong> if we pass the <code>'ls'</code> command, it will only <strong>display</strong> the list of files and directories as standard output. Therefore, you should use it if you only want to visualize the list without actually working with it in your program.</p>
<h3 id="heading-syntax-and-parameter-1">Syntax and Parameter</h3>
<p>To call this function, you will need to use this syntax:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/image-15.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Its only argument is the command that you want to execute formatted as a string (surrounded by double quotes or single quotes).</p>
<p>Particularly, the <code>ls</code> command lets you see the content of your current working directory. </p>
<p>For example: if this is my working directory (three Python files and one subdirectory):</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/image-17.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>And I call the <code>system()</code> function, like this:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> os
<span class="hljs-meta">&gt;&gt;&gt; </span>os.system(<span class="hljs-string">"ls"</span>)
</code></pre>
<p>This is the output:</p>
<pre><code class="lang-python"><span class="hljs-string">'Directory 1'</span>  <span class="hljs-string">'file 1.py'</span>  <span class="hljs-string">'file 2.py'</span>   main.py
<span class="hljs-number">0</span>
</code></pre>
<p>We can see the standard output in the console (the list of files and directories):</p>
<pre><code class="lang-python"><span class="hljs-string">'Directory 1'</span>  <span class="hljs-string">'file 1.py'</span>  <span class="hljs-string">'file 2.py'</span>   main.py
</code></pre>
<p>and the return value:</p>
<pre><code class="lang-python"><span class="hljs-number">0</span>
</code></pre>
<p>💡 <strong>Note:</strong> For these examples of the <code>system()</code> function, I'm working with an online command line tool called Repl.it since my computer has Windows installed and the command <code>ls</code> is not recognized by the default command prompt. </p>
<h3 id="heading-limitations">Limitations</h3>
<p>One of the main limitation of this function is that the command passed as argument has to be recognized by the operating system or environment that you are working with. </p>
<p>For example, the <code>ls</code> command will not be recognized in Windows by default in the command prompt. You will see this error if you try to run it:</p>
<blockquote>
<p>'ls' is not recognized as an internal or external command, operable program or batch file.</p>
</blockquote>
<p>A similar command in Windows would be the <code>'dir'</code> command:</p>
<pre><code class="lang-python">os.system(<span class="hljs-string">'dir'</span>)
</code></pre>
<p><strong>💡 Tip:</strong> There are alternative ways to run the <code>ls</code> command on Windows, such as using terminal programs that recognize Unix commands, but by default Windows does not recognize the <code>'ls'</code> command.</p>
<h3 id="heading-return-value">Return Value</h3>
<p>According to the <a target="_blank" href="https://docs.python.org/3/library/os.html#os.system">Python documentation</a>:</p>
<blockquote>
<p>On Unix, the return value is the exit status of the process encoded in the format specified for <a target="_blank" href="https://docs.python.org/3/library/os.html#os.wait"><code>wait()</code></a>.</p>
</blockquote>
<p>and...</p>
<blockquote>
<p>On Windows, the return value is that returned by the system shell after running <em>command</em>.</p>
</blockquote>
<p>💡 <strong>Tip:</strong> Note that this function does not return a list. It simply displays the list as standard output, so you can't store it in a variable like you did with <code>listdir</code>.</p>
<h3 id="heading-variations-of-the-ls-command">Variations of the <code>ls</code> command</h3>
<p>A key feature of <code>os.system('ls')</code> is that it has many helpful and interesting options to customize how present the output. Let's see some of them.</p>
<p><strong>Option 1:</strong> We can show more information about files and directories such as their size, location, and modification date and time using the command <code>ls -l</code>.</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> os
<span class="hljs-meta">&gt;&gt;&gt; </span>os.system(<span class="hljs-string">'ls -l'</span>)
total <span class="hljs-number">12</span>
drwxr-xr-x <span class="hljs-number">1</span> runner runner  <span class="hljs-number">0</span> Apr  <span class="hljs-number">3</span> <span class="hljs-number">18</span>:<span class="hljs-number">23</span> <span class="hljs-string">'Directory 1'</span>
-rw-r--r-- <span class="hljs-number">1</span> runner runner <span class="hljs-number">11</span> Apr  <span class="hljs-number">3</span> <span class="hljs-number">18</span>:<span class="hljs-number">38</span> <span class="hljs-string">'file 1.py'</span>
-rw-r--r-- <span class="hljs-number">1</span> runner runner <span class="hljs-number">11</span> Apr  <span class="hljs-number">3</span> <span class="hljs-number">18</span>:<span class="hljs-number">38</span> <span class="hljs-string">'file 2.py'</span>
-rw-r--r-- <span class="hljs-number">1</span> runner runner <span class="hljs-number">11</span> Apr  <span class="hljs-number">3</span> <span class="hljs-number">18</span>:<span class="hljs-number">38</span>  main.py
<span class="hljs-number">0</span>
</code></pre>
<p><strong>Option 2:</strong> To be able to visually recognize directories faster, we can use <code>ls -F</code>, which adds a forward slash <code>/</code> to the end of their names (see <code>'Directory 1/'</code> below).</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> os
<span class="hljs-meta">&gt;&gt;&gt; </span>os.system(<span class="hljs-string">'ls -F'</span>)
<span class="hljs-string">'Directory 1'</span>/  <span class="hljs-string">'file 1.py'</span>  <span class="hljs-string">'file 2.py'</span>   main.py
<span class="hljs-number">0</span>
</code></pre>
<p><strong>Option 3:</strong> To sort the files by size, we can use the command <code>ls -lS</code>.</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> os
<span class="hljs-meta">&gt;&gt;&gt; </span>os.system(<span class="hljs-string">'ls -lS'</span>)
total <span class="hljs-number">12</span>
-rw-r--r-- <span class="hljs-number">1</span> runner runner <span class="hljs-number">11</span> Apr  <span class="hljs-number">3</span> <span class="hljs-number">18</span>:<span class="hljs-number">38</span> <span class="hljs-string">'file 1.py'</span>
-rw-r--r-- <span class="hljs-number">1</span> runner runner <span class="hljs-number">11</span> Apr  <span class="hljs-number">3</span> <span class="hljs-number">18</span>:<span class="hljs-number">38</span> <span class="hljs-string">'file 2.py'</span>
-rw-r--r-- <span class="hljs-number">1</span> runner runner <span class="hljs-number">11</span> Apr  <span class="hljs-number">3</span> <span class="hljs-number">18</span>:<span class="hljs-number">38</span>  main.py
drwxr-xr-x <span class="hljs-number">1</span> runner runner  <span class="hljs-number">0</span> Apr  <span class="hljs-number">3</span> <span class="hljs-number">18</span>:<span class="hljs-number">23</span> <span class="hljs-string">'Directory 1'</span>
<span class="hljs-number">0</span>
</code></pre>
<p>There are many more options for customization that can be helpful for your particular goal. <a target="_blank" href="https://en.wikipedia.org/wiki/Ls">Here you can find more information</a> about the <code>-ls</code> command and how you can use its full power.</p>
<h2 id="heading-summary-of-listdir-vs-systemls">🔸 Summary of listdir vs. system("ls")</h2>
<ul>
<li><strong>Purpose:</strong> <code>listdir</code> returns the list of file names and directories in the path specified (by default, the current working directory) while <code>system("ls")</code> only displays them as standard output.</li>
<li><strong>Operating System:</strong> <code>listdir</code> can be used independently of the operating system that you are working with. In contrast, <code>system('ls')</code> has to be executed in an operating system or environment that recognizes the <code>'ls'</code> command. </li>
<li><strong>Customization:</strong> you can filter the list returned by <code>listdir</code> if you need to remove files or directories using the <code>filter()</code> function and you can pass options to customize the output of <code>system('ls')</code>.</li>
</ul>
<p><strong>I really hope that you liked my article and found it helpful.</strong> Now you can work with these functions in your Python projects. <a target="_blank" href="https://www.udemy.com/user/estefania-cn/">Check out my online courses</a>. Follow me on <a target="_blank" href="https://twitter.com/EstefaniaCassN">Twitter</a>. ⭐️</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The 3 Types of Design Patterns All Developers Should Know (with code examples of each) ]]>
                </title>
                <description>
                    <![CDATA[ By Sameeha Rahman What is a Design Pattern? Design patterns are design level solutions for recurring problems that we software engineers come across often. It’s not code - I repeat, ❌CODE. It is like a description on how to tackle these problems and ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-basic-design-patterns-all-developers-need-to-know/</link>
                <guid isPermaLink="false">66d460cfe39d8b5612bc0df1</guid>
                
                    <category>
                        <![CDATA[ command ]]>
                    </category>
                
                    <category>
                        <![CDATA[ decorator ]]>
                    </category>
                
                    <category>
                        <![CDATA[ design patterns ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ object oriented ]]>
                    </category>
                
                    <category>
                        <![CDATA[ singleton ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 24 Jul 2019 06:52:52 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/07/design-patterns-everywhere.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Sameeha Rahman</p>
<h1 id="heading-what-is-a-design-pattern">What is a Design Pattern?</h1>
<p>Design patterns are design level solutions for recurring problems that we software engineers come across often. It’s not code - I repeat, ❌<strong>CODE</strong>. It is like a description on how to tackle these problems and design a solution. </p>
<p>Using these patterns is considered good practice, as the design of the solution is quite tried and tested, resulting in higher readability of the final code. Design patterns are quite often created for and used by OOP Languages, like Java, in which most of the examples from here on will be written.</p>
<h2 id="heading-types-of-design-patterns">Types of design patterns</h2>
<p>There are about 26 Patterns currently discovered (I hardly think I will do them all…).</p>
<p>These 26 can be classified into 3 types:</p>
<ol>
<li><p>Creational: These patterns are designed for class instantiation. They can be either class-creation patterns or object-creational patterns.</p>
</li>
<li><p>Structural: These patterns are designed with regard to a class's structure and composition. The main goal of most of these patterns is to increase the functionality of the class(es) involved, without changing much of its composition.</p>
</li>
<li><p>Behavioral: These patterns are designed depending on how one class communicates with others.</p>
</li>
</ol>
<p>In this post, we will go through one basic design pattern for each classified type.</p>
<h2 id="heading-type-1-creational-the-singleton-design-pattern">Type 1: Creational - The Singleton Design Pattern</h2>
<p>The Singleton Design Pattern is a Creational pattern, whose objective is to create only one instance of a class and to provide only one global access point to that object. One commonly used example of such a class in Java is Calendar, where you cannot make an instance of that class. It also uses its own <code>getInstance()</code>method to get the object to be used.</p>
<p>A class using the singleton design pattern will include,</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/07/singleton-class-diagram.png" alt="Image" width="600" height="400" loading="lazy">
<em>Singleton Class Diagram</em></p>
<ol>
<li>A private static variable, holding the only instance of the class.</li>
<li>A private constructor, so it cannot be instantiated anywhere else.</li>
<li>A public static method, to return the single instance of the class.</li>
</ol>
<p>There are many different implementations of singleton design. Today, I’ll be going through the implementations of;</p>
<ol>
<li><p>Eager Instantiation</p>
</li>
<li><p>Lazy Instantiation</p>
</li>
<li><p>Thread-safe Instantiation</p>
</li>
</ol>
<h3 id="heading-eager-beaver">Eager Beaver</h3>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">EagerSingleton</span> </span>{
    <span class="hljs-comment">// create an instance of the class.</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> EagerSingleton instance = <span class="hljs-keyword">new</span> EagerSingleton();

    <span class="hljs-comment">// private constructor, so it cannot be instantiated outside this class.</span>
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">EagerSingleton</span><span class="hljs-params">()</span> </span>{  }

    <span class="hljs-comment">// get the only instance of the object created.</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> EagerSingleton <span class="hljs-title">getInstance</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> instance;
    }
}
</code></pre>
<p>This type of instantiation happens during class loading, as the instantiation of the variable instance happens outside any method. This poses a hefty drawback if this class is not being used at all by the client application. The contingency plan, if this class is not being used, is the Lazy Instantiation.</p>
<h3 id="heading-lazy-days">Lazy Days</h3>
<p>There isn’t much difference from the above implementation. The main differences are that the static variable is initially declared null, and is only instantiated within the <code>getInstance()</code> method if - and only if - the instance variable remains null at the time of the check. </p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LazySingleton</span> </span>{
    <span class="hljs-comment">// initialize the instance as null.</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> LazySingleton instance = <span class="hljs-keyword">null</span>;

    <span class="hljs-comment">// private constructor, so it cannot be instantiated outside this class.</span>
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">LazySingleton</span><span class="hljs-params">()</span> </span>{  }

    <span class="hljs-comment">// check if the instance is null, and if so, create the object.</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> LazySingleton <span class="hljs-title">getInstance</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">if</span> (instance == <span class="hljs-keyword">null</span>) {
            instance = <span class="hljs-keyword">new</span> LazySingleton();
        }
        <span class="hljs-keyword">return</span> instance;
    }
}
</code></pre>
<p>This fixes one problem, but another one still exists. What if two different clients access the Singleton class at the same time, right to the millisecond? Well, they will check if the instance is null at the same time, and will find it true, and so will create two instances of the class for each request by the two clients. To fix this, Thread Safe instantiation is to be implemented.</p>
<h3 id="heading-thread-safety-is-key">(Thread) Safety is Key</h3>
<p>In Java, the keyword synchronized is used on methods or objects to implement thread safety, so that only one thread will access a particular resource at one time. The class instantiation is put within a synchronized block so that the method can only be accessed by one client at a given time.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ThreadSafeSingleton</span> </span>{
    <span class="hljs-comment">// initialize the instance as null.</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> ThreadSafeSingleton instance = <span class="hljs-keyword">null</span>;

    <span class="hljs-comment">// private constructor, so it cannot be instantiated outside this class.</span>
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">ThreadSafeSingleton</span><span class="hljs-params">()</span> </span>{  }

    <span class="hljs-comment">// check if the instance is null, within a synchronized block. If so, create the object</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> ThreadSafeSingleton <span class="hljs-title">getInstance</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">synchronized</span> (ThreadSafeSingleton.class) {
            <span class="hljs-keyword">if</span> (instance == <span class="hljs-keyword">null</span>) {
                instance = <span class="hljs-keyword">new</span> ThreadSafeSingleton();
            }
        }
        <span class="hljs-keyword">return</span> instance;
    }
}
</code></pre>
<p>The overhead for the synchronized method is high, and reduces the performance of the whole operation. </p>
<p>For example, if the instance variable has already been instantiated, then each time any client accesses the <code>getInstance()</code> method, the <code>synchronized</code> method is run and the performance drops. This just happens in order to check if the <code>instance</code> variables’ value is null. If it finds that it is, it leaves the method. </p>
<p>To reduce this overhead, double locking is used. The check is used before the <code>synchronized</code> method as well, and if the value is null alone, does the <code>synchronized</code> method run.</p>
<pre><code class="lang-java"><span class="hljs-comment">// double locking is used to reduce the overhead of the synchronized method</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> ThreadSafeSingleton <span class="hljs-title">getInstanceDoubleLocking</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">if</span> (instance == <span class="hljs-keyword">null</span>) {
        <span class="hljs-keyword">synchronized</span> (ThreadSafeSingleton.class) {
            <span class="hljs-keyword">if</span> (instance == <span class="hljs-keyword">null</span>) {
                instance = <span class="hljs-keyword">new</span> ThreadSafeSingleton();
            }
        }
    }
    <span class="hljs-keyword">return</span> instance;
}
</code></pre>
<p>Now onto the next classification.</p>
<h2 id="heading-type-2-structural-the-decorator-design-pattern">Type 2: Structural - The Decorator Design Pattern</h2>
<p>I’m gonna give you a small scenario to give a better context to why and where you should use the Decorator Pattern.</p>
<p>Say you own a coffee shop, and like any newbie, you start out with just two types of plain coffee, the house blend and dark roast. In your billing system, there was one class for the different coffee blends, which inherits the beverage abstract class. People actually start to come by and have your wonderful (albeit bitter?) coffee. Then there are the coffee newbs that, God forbid, want sugar or milk. Such a travesty for coffee!! ??</p>
<p>Now you need to have those two add-ons as well, both to the menu and unfortunately on the billing system. Originally, your IT person will make a subclass for both coffees, one including sugar, the other milk. Then, since customers are always right, one says these dreaded words:</p>
<p><em>“Can I get a milk coffee, with sugar, please?”</em></p>
<h3 id="heading-pz8">???</h3>
<p>There goes your billing system laughing in your face again. Well, back to the drawing board….</p>
<p>The IT person then adds milk coffee with sugar as another subclass to each parent coffee class. The rest of the month is smooth sailing, people lining up to have your coffee, you actually making money. ??</p>
<p>But wait, there’s more!</p>
<p>The world is against you once again. A competitor opens up across the street, with not just 4 types of coffee, but more than 10 add-ons as well!</p>
<p>You buy all those and more, to sell better coffee yourself, and just then remember that you forgot to update that dratted billing system. You quite possibly cannot make the infinite number of subclasses for any and all combinations of all the add-ons, with the new coffee blends too. Not to mention, the size of the final system.</p>
<p>Time to actually invest in a proper billing system. You find new IT personnel, who actually knows what they are doing and they say,</p>
<p><em>“Why, this will be so much easier and smaller if it used the decorator pattern.”</em></p>
<h3 id="heading-what-on-earth-is-that">What on earth is that?</h3>
<p>The decorator design pattern falls into the structural category, that deals with the actual structure of a class, whether is by inheritance, composition or both. The goal of this design is to modify an objects’ functionality at runtime. This is one of the many other design patterns that utilize abstract classes and interfaces with composition to get its desired result.</p>
<p>Let’s give Math a chance (shudder?) to bring this all into perspective.</p>
<p>Take 4 coffee blends and 10 add-ons. If we stuck to the generation of subclasses for each different combination of all the add-ons for one type of coffee. That’s:</p>
<p>(10–1)² = 9² = 81 subclasses</p>
<p>We subtract 1 from the 10, as you cannot combine one add-on with another of the same type, sugar with sugar sounds stupid. And that’s for just one coffee blend. Multiply that <strong>81 by 4</strong> and you get a whopping <strong>324</strong> different subclasses! Talk about all that coding…</p>
<p>But with the decorator pattern it will require only 16 classes in this scenario. Wanna bet?</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/07/decorator-class-diagram.png" alt="Image" width="600" height="400" loading="lazy">
<em>Decorator Design Pattern Class diagram</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/07/decorator-coffee-class-diagram.png" alt="Image" width="600" height="400" loading="lazy">
<em>Class diagram according to coffee shop scenario</em></p>
<p>If we map out our scenario according to the class diagram above, we get 4 classes for the 4 coffee blends, 10 for each add-on and 1 for the abstract component and 1 more for the abstract decorator. See! 16! Now hand over that $100.?? (jk, but it will not be refused if given… just saying)</p>
<p>As you can see from above, just as the concrete coffee blends are subclasses of the beverage abstract class, the AddOn abstract class also inherits its methods from it. The add-ons, that are its subclasses, in turn inherit any new methods to add functionality to the base object when needed.</p>
<p>Let’s get to coding, to see this pattern in use.</p>
<p>First to make the Abstract beverage class, that all the different coffee blends will inherit from:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Beverage</span> </span>{
    <span class="hljs-keyword">private</span> String description;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Beverage</span><span class="hljs-params">(String description)</span> </span>{
        <span class="hljs-keyword">super</span>();
        <span class="hljs-keyword">this</span>.description = description;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getDescription</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> description;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">double</span> <span class="hljs-title">cost</span><span class="hljs-params">()</span></span>;
}
</code></pre>
<p>Then to add both the concrete coffee blend classes.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HouseBlend</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Beverage</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">HouseBlend</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">super</span>(“House blend”);
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> <span class="hljs-title">cost</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-number">250</span>;
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DarkRoast</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Beverage</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">DarkRoast</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">super</span>(“Dark roast”);
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> <span class="hljs-title">cost</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-number">300</span>;
    }
}
</code></pre>
<p>The AddOn abstract class also inherits from the Beverage abstract class (more on this below).</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AddOn</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Beverage</span> </span>{
    <span class="hljs-keyword">protected</span> Beverage beverage;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">AddOn</span><span class="hljs-params">(String description, Beverage bev)</span> </span>{
        <span class="hljs-keyword">super</span>(description);
        <span class="hljs-keyword">this</span>.beverage = bev;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> String <span class="hljs-title">getDescription</span><span class="hljs-params">()</span></span>;
}
</code></pre>
<p>And now the concrete implementations of this abstract class:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Sugar</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">AddOn</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Sugar</span><span class="hljs-params">(Beverage bev)</span> </span>{
        <span class="hljs-keyword">super</span>(“Sugar”, bev);
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getDescription</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> beverage.getDescription() + “ with Mocha”;
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> <span class="hljs-title">cost</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> beverage.cost() + <span class="hljs-number">50</span>;
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Milk</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">AddOn</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Milk</span><span class="hljs-params">(Beverage bev)</span> </span>{
        <span class="hljs-keyword">super</span>(“Milk”, bev);
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getDescription</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> beverage.getDescription() + “ with Milk”;
    }

    <span class="hljs-meta">@Override</span>  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> <span class="hljs-title">cost</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> beverage.cost() + <span class="hljs-number">100</span>;
    }
}
</code></pre>
<p>As you can see above, we can pass any subclass of Beverage to any subclass of AddOn, and get the added cost as well as the updated description. And, since the AddOn class is essentially of type Beverage, we can pass an AddOn into another AddOn. This way, we can add any number of add-ons to a specific coffee blend.</p>
<p>Now to write some code to test this out.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CoffeeShop</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        HouseBlend houseblend = <span class="hljs-keyword">new</span> HouseBlend();
        System.out.println(houseblend.getDescription() + “: “ + houseblend.cost());

        Milk milkAddOn = <span class="hljs-keyword">new</span> Milk(houseblend);
        System.out.println(milkAddOn.getDescription() + “: “ + milkAddOn.cost());

        Sugar sugarAddOn = <span class="hljs-keyword">new</span> Sugar(milkAddOn);
        System.out.println(sugarAddOn.getDescription() + “: “ + sugarAddOn.cost());
    }
}
</code></pre>
<p>The final result is:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/07/decorator-final.PNG" alt="Image" width="600" height="400" loading="lazy">
<em>P.S. this is in Sri Lankan Rupees</em></p>
<p>It works! We were able to add more than one add-on to a coffee blend and successfully update its final cost and description, without the need to make infinite subclasses for each add-on combination for all coffee blends.</p>
<p>Finally, to the last category.</p>
<h2 id="heading-type-3-behavioral-the-command-design-pattern">Type 3: Behavioral - The Command Design Pattern</h2>
<p>A behavioral design pattern focuses on how classes and objects communicate with each other. The main focus of the command pattern is to inculcate a higher degree of loose coupling between involved parties (read: classes).</p>
<p><em>Uhhhh… What’s that?</em></p>
<p>Coupling is the way that two (or more) classes that interact with each other, well, interact. The ideal scenario when these classes interact is that they do not depend heavily on each other. That’s loose coupling. So, a better definition for loose coupling would be, classes that are interconnected, making the least use of each other.</p>
<p>The need for this pattern arose when requests needed to be sent without consciously knowing what you are asking for or who the receiver is.</p>
<p>In this pattern, the invoking class is decoupled from the class that actually performs an action. The invoker class only has the callable method execute, which runs the necessary command, when the client requests it.</p>
<p>Let’s take a basic real-world example, ordering a meal at a fancy restaurant. As the flow goes, you give your order (command) to the waiter (invoker), who then hands it over to the chef(receiver), so you can get food. Might sound simple… but a bit meh to code.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/07/chain-of-command-be-like-pop-snoke-im-going-to-27790631.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The idea is pretty simple, but the coding goes around the nose.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/07/command-class-diagram.PNG" alt="Image" width="600" height="400" loading="lazy">
<em>Command Design Pattern Class Diagram</em></p>
<p>The flow of operation on the technical side is, you make a concrete command, which implements the Command interface, asking the receiver to complete an action, and send the command to the invoker. The invoker is the person that knows when to give this command. The chef is the only one who knows what to do when given the specific command/order. So, when the execute method of the invoker is run, it, in turn, causes the command objects’ execute method to run on the receiver, thus completing necessary actions.</p>
<h3 id="heading-what-we-need-to-implement-is">What we need to implement is;</h3>
<ol>
<li>An interface Command</li>
<li>A class Order that implements Command interface</li>
<li>A class Waiter (invoker)</li>
<li>A class Chef (receiver)</li>
</ol>
<p>So, the coding goes like this:</p>
<h3 id="heading-chef-the-receiver">Chef, the receiver</h3>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Chef</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">cookPasta</span><span class="hljs-params">()</span> </span>{
        System.out.println(“Chef is cooking Chicken Alfredo…”);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">bakeCake</span><span class="hljs-params">()</span> </span>{
        System.out.println(“Chef is baking Chocolate Fudge Cake…”);
    }
}
</code></pre>
<h3 id="heading-command-the-interface">Command, the interface</h3>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Command</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">execute</span><span class="hljs-params">()</span></span>;
}
</code></pre>
<h3 id="heading-order-the-concrete-command">Order, the concrete command</h3>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Order</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Command</span> </span>{
    <span class="hljs-keyword">private</span> Chef chef;
    <span class="hljs-keyword">private</span> String food;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Order</span><span class="hljs-params">(Chef chef, String food)</span> </span>{
        <span class="hljs-keyword">this</span>.chef = chef;
        <span class="hljs-keyword">this</span>.food = food;
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">execute</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">if</span> (<span class="hljs-keyword">this</span>.food.equals(“Pasta”)) {
            <span class="hljs-keyword">this</span>.chef.cookPasta();
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-keyword">this</span>.chef.bakeCake();
        }
    }
}
</code></pre>
<h3 id="heading-waiter-the-invoker">Waiter, the invoker</h3>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Waiter</span> </span>{
    <span class="hljs-keyword">private</span> Order order;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Waiter</span><span class="hljs-params">(Order ord)</span> </span>{
        <span class="hljs-keyword">this</span>.order = ord;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">execute</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">this</span>.order.execute();
    }
}
</code></pre>
<h2 id="heading-you-the-client">You, the client</h2>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Client</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Chef chef = <span class="hljs-keyword">new</span> Chef();

        Order order = <span class="hljs-keyword">new</span> Order(chef, “Pasta”);
        Waiter waiter = <span class="hljs-keyword">new</span> Waiter(order);
        waiter.execute();

        order = <span class="hljs-keyword">new</span> Order(chef, “Cake”);
        waiter = <span class="hljs-keyword">new</span> Waiter(order);
        waiter.execute();
    }
}
</code></pre>
<p>As you can see above, the Client makes an Order and sets the Receiver as the Chef. The Order is sent to the Waiter, who will know when to execute the Order (i.e. when to give the chef the order to cook). When the invoker is executed, the Orders’ execute method is run on the receiver (i.e. the chef is given the command to either cook pasta ? or bake cake?).</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*gwsVqEIKFmBj01M7dXsQ_A.png" alt="Image" width="600" height="400" loading="lazy">
<em>Final Client Output</em></p>
<h2 id="heading-quick-recap">Quick recap</h2>
<p>In this post we went through:</p>
<ol>
<li>What a design pattern really is,</li>
<li>The different types of design patterns and why they are different</li>
<li>One basic or common design pattern for each type</li>
</ol>
<p>I hope this was helpful.  </p>
<p>Find the code repo for the post, <a target="_blank" href="https://github.com/samsam-026/Design_Patterns">here</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
