<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Giovanna Moeller</title>
    <description>The latest articles on DEV Community by Giovanna Moeller (@giovannamoeller).</description>
    <link>https://dev.to/giovannamoeller</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F789843%2Ffa40de9f-cdfe-49ef-a952-b4d479039a5f.png</url>
      <title>DEV Community: Giovanna Moeller</title>
      <link>https://dev.to/giovannamoeller</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/giovannamoeller"/>
    <language>en</language>
    <item>
      <title>The Single Responsibility Principle (SRP) of SOLID</title>
      <dc:creator>Giovanna Moeller</dc:creator>
      <pubDate>Thu, 08 Feb 2024 21:44:26 +0000</pubDate>
      <link>https://dev.to/giovannamoeller/the-single-responsibility-principle-srp-of-solid-2epj</link>
      <guid>https://dev.to/giovannamoeller/the-single-responsibility-principle-srp-of-solid-2epj</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;In this article, I will address the first principle of SOLID, known as the Single Responsibility Principle (SRP).&lt;/p&gt;

&lt;h2&gt;
  
  
  First, what is SOLID?
&lt;/h2&gt;

&lt;p&gt;SOLID is an acronym representing five fundamental principles of object-oriented software design and architecture, identified by Robert C. Martin (Uncle Bob) around the 2000s. The acronym SOLID was introduced by Michael Feathers, after observing that the five principles could fit into this word.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Following these principles can result in a system that is more comprehensible, flexible, and modular, which is easy to scale, modify, and test.&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Definition
&lt;/h2&gt;

&lt;p&gt;The Single Responsibility Principle (SRP), the first of the five principles of &lt;strong&gt;SOLID&lt;/strong&gt;, is a fundamental concept in object-oriented software development.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;This principle states that a class should have only one reason to change, meaning it should be responsible for only one part of the software's functionality.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;You should apply this principle not only to classes but also to functions, modules, etc.&lt;/p&gt;

&lt;h2&gt;
  
  
  An analogy for better understanding
&lt;/h2&gt;

&lt;p&gt;Imagine a team in a restaurant. In this team, we have various functions: cooks, waiters, and the manager. Each of these team members has a unique responsibility. The cooks prepare the food, the waiters serve the food to the customers, and the manager takes care of the restaurant's administration. Imagine the chaos if a single person tried to perform all these tasks, it would generate a totally inefficient and confusing system.&lt;/p&gt;

&lt;p&gt;Similarly, a class in software should specialize in a single functionality or responsibility. This makes maintenance easier, code comprehension better, and aids in reusability.&lt;/p&gt;

&lt;h2&gt;
  
  
  SRP in software development
&lt;/h2&gt;

&lt;p&gt;Let's observe an example that violates the SRP. The class below deals with user details and at the same time manages the storage logic of those details.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;UserManager&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;user_name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;email&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;user_name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;user_name&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;email&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;email&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;change_user_email&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;new_email&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="c1"&gt;# Logic to change the user's email
&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;save_user&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="c1"&gt;# Logic to save the user in the database
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this code, &lt;code&gt;UserManager&lt;/code&gt; is responsible for both managing user details and the storage logic (data persistence). This violates the SRP, as we have more than one reason to modify the class.&lt;/p&gt;

&lt;p&gt;To correct the SRP violation, we can divide the class into two: one to manage user details and another to handle data persistence.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;User&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;user_name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;email&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;user_name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;user_name&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;email&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;email&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;change_email&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;new_email&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="c1"&gt;# Logic to change the user's email
&lt;/span&gt;
&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;UserDataStorage&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;save_user&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;user&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="c1"&gt;# Logic to save the user in the database
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Shall we see another example?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Below, we have a class that generates reports on products and also saves them in a file. This class does too much by dealing with both formatting and data persistence.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ProductReport&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;products&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;products&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;products&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;generate_report&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="c1"&gt;# Logic to generate report
&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;save_report&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="c1"&gt;# Logic to save report
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To adhere to the SRP, we can create a separate class for generating the report and another for saving the report to a file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ProductReportGenerator&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;products&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;products&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;products&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;generate_report&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="c1"&gt;# Logic to generate report
&lt;/span&gt;
&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ReportSaver&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;save_report&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;report&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="c1"&gt;# Logic to save report
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Tips for applying the SRP to your project
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Identify responsibilities&lt;/strong&gt;: Analyze your classes to identify different responsibilities. Each responsibility is a potential axis of change.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Divide and conquer&lt;/strong&gt;: If a class has more than one responsibility, consider dividing it into smaller classes, each with its own responsibility.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Code reuse&lt;/strong&gt;: Classes with a single responsibility are easier to reuse because you can use them in different contexts without bringing unnecessary functionalities.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Testability&lt;/strong&gt;: Classes focused on a single responsibility are easier to test because you do not have to deal with multiple functionalities during the testing of a specific functionality.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;The Single Responsibility Principle is essential for sustainable and high-quality software development. Classes, functions, modules focused on a single responsibility ensure efficiency, maintainability, and clarity of code. By applying the SRP, you create a solid foundation for a robust software architecture, facilitating the evolution and maintenance of your project.&lt;/p&gt;

&lt;p&gt;Thank you so much for reading this far. Find me on other &lt;a href="https://bento.me/giovannatech"&gt;social networks&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>programming</category>
      <category>solidprinciples</category>
      <category>cleancode</category>
      <category>softwaredevelopment</category>
    </item>
    <item>
      <title>Generics in Swift: Expanding Flexibility and Code Reusability</title>
      <dc:creator>Giovanna Moeller</dc:creator>
      <pubDate>Tue, 06 Feb 2024 21:04:09 +0000</pubDate>
      <link>https://dev.to/giovannamoeller/generics-in-swift-expanding-flexibility-and-code-reusability-5816</link>
      <guid>https://dev.to/giovannamoeller/generics-in-swift-expanding-flexibility-and-code-reusability-5816</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Generics are a powerful feature in Swift that allow for the creation of flexible, reusable, and type-safe code, avoiding duplication and enhancing clarity. In this article, I will explore the motivation behind using generics, introduce their syntax, and fundamental concepts such as generic functions, classes, and structs, type constraints, and share an interesting curiosity of the language: the relationship between generics and optionals.&lt;/p&gt;

&lt;h2&gt;
  
  
  Motivation
&lt;/h2&gt;

&lt;p&gt;You might already know that Swift is a strongly typed language, meaning you must explicitly define the type of each variable, constant, parameter, and return value in your code.&lt;/p&gt;

&lt;p&gt;Although Swift also has type inference functionality (where the compiler automatically deduces the type of a variable based on the value assigned to it), the types are still well defined. If you declare that a function receives a value of type &lt;code&gt;String&lt;/code&gt;, you must pass a string and nothing else.&lt;/p&gt;

&lt;p&gt;See below a function that returns the first element of an array:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight swift"&gt;&lt;code&gt;&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="nv"&gt;names&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s"&gt;"Paul"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"Steve"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"Anna"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

&lt;span class="kd"&gt;func&lt;/span&gt; &lt;span class="nf"&gt;firstElement&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="nv"&gt;array&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;?&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;array&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;first&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="nv"&gt;firstName&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;firstElement&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;names&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;firstName&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the example above, we are defining that the type of elements that should compose the array is &lt;code&gt;String&lt;/code&gt;. And if I want to get the first element of an array of numbers? I would need to create another function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight swift"&gt;&lt;code&gt;&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="nv"&gt;numbers&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;15&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

&lt;span class="kd"&gt;func&lt;/span&gt; &lt;span class="nf"&gt;firstElement&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="nv"&gt;array&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kt"&gt;Int&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Int&lt;/span&gt;&lt;span class="p"&gt;?&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;array&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;first&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="nv"&gt;firstNumber&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;firstElement&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numbers&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;firstNumber&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A lot of code repetition, right? Well, without the use of generics, we would have to write multiple functions, one for each type, which leads to unnecessary code duplication.&lt;/p&gt;

&lt;h2&gt;
  
  
  Understanding Generics
&lt;/h2&gt;

&lt;p&gt;Generics allow writing functions and types that can work with any type, maintaining the type safety that Swift brings us. The same problem of returning the first element of the array can be solved with generics, as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight swift"&gt;&lt;code&gt;&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="nv"&gt;names&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s"&gt;"Gi"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"Daniel"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"Ana"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="nv"&gt;numbers&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;15&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

&lt;span class="kd"&gt;func&lt;/span&gt; &lt;span class="n"&gt;firstElement&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;T&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="nv"&gt;array&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kt"&gt;T&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;T&lt;/span&gt;&lt;span class="p"&gt;?&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;array&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;first&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="nv"&gt;firstName&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;firstElement&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;names&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;firstName&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="nv"&gt;firstNumber&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;firstElement&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numbers&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;firstNumber&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, &lt;code&gt;T&lt;/code&gt; is a type placeholder, representing &lt;strong&gt;any type&lt;/strong&gt; that will be provided when the function is called. You can use any placeholder name you wish, but &lt;code&gt;T&lt;/code&gt; is commonly used to represent a "type" generic.&lt;/p&gt;

&lt;h2&gt;
  
  
  Generic Functions
&lt;/h2&gt;

&lt;p&gt;The example you saw above is a generic function. Shall we see another example?&lt;/p&gt;

&lt;p&gt;Consider the following problem: you need to create a function that will create and return an array containing a certain value repeated a specific number of times. This can be useful in various situations, such as initializing an array with a default value or generating test data with repeated values.&lt;/p&gt;

&lt;p&gt;This value can be any type. Here's an example of how you can create this function using a generic type:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight swift"&gt;&lt;code&gt;&lt;span class="kd"&gt;func&lt;/span&gt; &lt;span class="n"&gt;makeArray&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;T&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;repeating&lt;/span&gt; &lt;span class="nv"&gt;item&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;T&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;numberOfTimes&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kt"&gt;T&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;var&lt;/span&gt; &lt;span class="nv"&gt;result&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kt"&gt;T&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;

    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="o"&gt;..&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;numberOfTimes&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;makeArray&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;repeating&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;numberOfTimes&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="c1"&gt;// [3, 3, 3, 3]&lt;/span&gt;
&lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;makeArray&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;repeating&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;"Hello"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;numberOfTimes&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="c1"&gt;// ["Hello", "Hello", "Hello"]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What's happening here? I'm creating a generic function that takes a generic type called &lt;code&gt;T&lt;/code&gt; and returns an array of type &lt;code&gt;T&lt;/code&gt;. Inside this function, I create an array of type &lt;code&gt;T&lt;/code&gt;, initially empty, and fill it with the item that was received as a parameter. Simple, right?&lt;/p&gt;

&lt;h2&gt;
  
  
  Generic Classes and Structs
&lt;/h2&gt;

&lt;p&gt;Swift also allows defining generic classes, structs, and even enums. See an example below of a generic class that implements a stack:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight swift"&gt;&lt;code&gt;&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="kt"&gt;Stack&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;T&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="k"&gt;var&lt;/span&gt; &lt;span class="nv"&gt;items&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kt"&gt;T&lt;/span&gt;&lt;span class="p"&gt;]()&lt;/span&gt;

    &lt;span class="kd"&gt;func&lt;/span&gt; &lt;span class="nf"&gt;push&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="nv"&gt;item&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;T&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;items&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="kd"&gt;func&lt;/span&gt; &lt;span class="nf"&gt;pop&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;T&lt;/span&gt;&lt;span class="p"&gt;?&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;items&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;popLast&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="nv"&gt;stack&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;Stack&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;Int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="n"&gt;stack&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;push&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;stack&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;push&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;stack&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;push&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;12&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;stack&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;pop&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;stack&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;items&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;// [3, 10]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notice the instance of this class &lt;code&gt;Stack&lt;/code&gt;, realized by the constant &lt;code&gt;stack&lt;/code&gt;. We cannot simply instantiate with a &lt;code&gt;Stack()&lt;/code&gt; as we would with a normal class; we need to define the type &lt;code&gt;T&lt;/code&gt;, hence we use &lt;code&gt;Stack&amp;lt;Int&amp;gt;()&lt;/code&gt;. If we opted for the type &lt;code&gt;String&lt;/code&gt; instead of &lt;code&gt;Int&lt;/code&gt;, we would do &lt;code&gt;Stack&amp;lt;String&amp;gt;()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The implementation with&lt;/p&gt;

&lt;p&gt;&lt;code&gt;struct&lt;/code&gt; would be the same way.&lt;/p&gt;

&lt;h2&gt;
  
  
  Type Constraints
&lt;/h2&gt;

&lt;p&gt;Swift allows you to specify type constraints on generic definitions, which restricts the types that can be used with a generic type or function. See the example below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight swift"&gt;&lt;code&gt;&lt;span class="kd"&gt;func&lt;/span&gt; &lt;span class="n"&gt;findIndex&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;T&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Equatable&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;from&lt;/span&gt; &lt;span class="nv"&gt;valueToBeFound&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;T&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="nv"&gt;array&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kt"&gt;T&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Int&lt;/span&gt;&lt;span class="p"&gt;?&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;index&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;array&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;enumerated&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;valueToBeFound&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;index&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;nil&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="nv"&gt;index&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;findIndex&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;from&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;in&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;index&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;// 2&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the code above, &lt;code&gt;T: Equatable&lt;/code&gt; ensures that &lt;code&gt;T&lt;/code&gt; implements the &lt;code&gt;Equatable&lt;/code&gt; protocol, allowing the values to be compared using &lt;code&gt;==&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;If you did not include the type constraint &lt;code&gt;T: Equatable&lt;/code&gt; in the definition of the function &lt;code&gt;findIndex&lt;/code&gt;, the Swift compiler would generate an error because it would not be able to guarantee that the types passed to the function support the equality operator (&lt;code&gt;==&lt;/code&gt;). Swift is a strongly typed language and requires that the operations performed on types are known and safe at compile time.&lt;/p&gt;

&lt;p&gt;Therefore, without the constraint &lt;code&gt;T: Equatable&lt;/code&gt;, Swift has no way of knowing if &lt;code&gt;T&lt;/code&gt; can be compared with &lt;code&gt;==&lt;/code&gt;. The &lt;code&gt;Equatable&lt;/code&gt; protocol declares the equality operator &lt;code&gt;==&lt;/code&gt;, meaning that any type that conforms to &lt;code&gt;Equatable&lt;/code&gt; can be compared for equality. Without this conformity, there's no guarantee that &lt;code&gt;T&lt;/code&gt; supports this operation.&lt;/p&gt;

&lt;p&gt;Let's see another example below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight swift"&gt;&lt;code&gt;&lt;span class="kd"&gt;func&lt;/span&gt; &lt;span class="n"&gt;encode&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;T&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Encodable&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="nv"&gt;item&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;T&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kt"&gt;JSONEncoder&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;encode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the example, the function &lt;code&gt;encode&lt;/code&gt; is a generic function that accepts any type &lt;code&gt;T&lt;/code&gt; as its parameter, with the condition that &lt;code&gt;T&lt;/code&gt; must conform to the &lt;code&gt;Encodable&lt;/code&gt; protocol.&lt;/p&gt;

&lt;p&gt;Remember, the &lt;code&gt;Encodable&lt;/code&gt; protocol is part of Swift's encoding and decoding data library, known as &lt;code&gt;Codable&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;To ensure that the function &lt;code&gt;JSONEncoder().encode(item)&lt;/code&gt; works, our parameter &lt;code&gt;item&lt;/code&gt; needs to be a type that conforms to the &lt;code&gt;Encodable&lt;/code&gt; protocol. For this reason, the function has a type constraint, to ensure that this function works as expected and does not cause a compilation error.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Relationship Between Optionals and Generics
&lt;/h2&gt;

&lt;p&gt;Did you know that optionals are actually a generic enum? That's right! The definition of &lt;code&gt;Optional&lt;/code&gt; is something similar to:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight swift"&gt;&lt;code&gt;&lt;span class="kd"&gt;enum&lt;/span&gt; &lt;span class="kt"&gt;Optional&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;Wrapped&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; 
    &lt;span class="k"&gt;case&lt;/span&gt; &lt;span class="k"&gt;none&lt;/span&gt; 
    &lt;span class="k"&gt;case&lt;/span&gt; &lt;span class="nf"&gt;some&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;Wrapped&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; 
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This means that when you declare a variable as &lt;code&gt;Int?&lt;/code&gt;, it's shorthand for &lt;code&gt;Optional&amp;lt;Int&amp;gt;&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight swift"&gt;&lt;code&gt;&lt;span class="k"&gt;var&lt;/span&gt; &lt;span class="nv"&gt;optionalInt&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Int&lt;/span&gt;&lt;span class="p"&gt;?&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;42&lt;/span&gt;
&lt;span class="c1"&gt;// Is equivalent to:&lt;/span&gt;
&lt;span class="k"&gt;var&lt;/span&gt; &lt;span class="nv"&gt;anotherOptionalInt&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Optional&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;Int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;some&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="k"&gt;switch&lt;/span&gt; &lt;span class="n"&gt;anotherOptionalInt&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="k"&gt;case&lt;/span&gt; &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="nv"&gt;none&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;  
    &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"nil"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;case&lt;/span&gt; &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;some&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="nv"&gt;value&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;  
    &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;// 42&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Generics are fundamental in Swift, allowing you to write cleaner, more flexible, and reusable code. They help us avoid duplication and maintain type safety. By learning and applying generics, you can take full advantage of Swift's powerful type features. Generics, therefore, are not just a tool for creating efficient code, but also a bridge to deeply understanding how Swift operates with types and values.&lt;/p&gt;

&lt;p&gt;Thank you so much for reading this far.&lt;/p&gt;

</description>
      <category>swift</category>
      <category>mobile</category>
      <category>programming</category>
      <category>ios</category>
    </item>
    <item>
      <title>Clean Code: Lições essenciais do terceiro capítulo</title>
      <dc:creator>Giovanna Moeller</dc:creator>
      <pubDate>Thu, 14 Dec 2023 19:01:10 +0000</pubDate>
      <link>https://dev.to/giovannamoeller/clean-code-licoes-essenciais-do-terceiro-capitulo-488a</link>
      <guid>https://dev.to/giovannamoeller/clean-code-licoes-essenciais-do-terceiro-capitulo-488a</guid>
      <description>&lt;p&gt;O capítulo 03 do livro “Código limpo” fala sobre como escrever boas funções. A principal questão é: como fazer uma função transmitir o seu propósito?&lt;/p&gt;

&lt;h2&gt;
  
  
  1. As funções devem ser pequenas
&lt;/h2&gt;

&lt;p&gt;As funções devem ser pequenas. E elas devem ser menores do que você provavelmente está imaginando.&lt;br&gt;
 &lt;br&gt;
O livro diz que uma função deve ter no máximo 20 linhas, e que uma linha de código  — independentemente do que seja  — deve ter no máximo 150 caracteres. &lt;/p&gt;

&lt;p&gt;As funções devem ter os seus objetivos declarados de forma transparente. Devem contar a sua história e devem te levar a próxima ordem/instrução.&lt;/p&gt;
&lt;h2&gt;
  
  
  2. Máximo de 2 níveis de indentação
&lt;/h2&gt;

&lt;p&gt;As funções não devem ter muitas estruturas aninhadas. Ou seja, if dentro de if, muitas condicionais, etc. O nível de indentação de uma função deve ser de no máximo 1 ou 2. Isso facilita a leitura e compreensão.&lt;/p&gt;

&lt;p&gt;Além disso, blocos dentro de instruções como if, else, while, devem ter apenas 1 linha, possivelmente uma chamada para outra função.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;If…
    if…
    else if…
else...
    if…
    else if…
    else..
        if…
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Evite isso!&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Faça apenas uma coisa
&lt;/h2&gt;

&lt;p&gt;Eu julgo este o princípio mais importante. As funções devem fazer apenas uma única coisa. Devem fazê-la bem. Devem fazer apenas ela. É o princípio da responsabilidade única.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Mantenha um nível de abstração
&lt;/h2&gt;

&lt;p&gt;A chave para entender se uma função está realmente fazendo "uma única coisa" está em olhar para o nível de abstração.&lt;/p&gt;

&lt;p&gt;Quando dizemos que uma função deve fazer "uma coisa", estamos nos referindo a manter todas as suas ações dentro do mesmo nível de abstração. Isso significa que todos os passos ou operações dentro da função devem contribuir diretamente para realizar o propósito geral da função, como indicado pelo seu nome.&lt;/p&gt;

&lt;p&gt;Você pode estar se perguntando: o que significa níveis de abstração?&lt;/p&gt;

&lt;p&gt;Um "nível de abstração" refere-se à camada ou nível de detalhamento e complexidade de um código ou de uma parte do código.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Alto nível de abstração: Isso é como olhar de um avião. Você vê a cidade, mas não as ruas individuais. Em termos de programação, é quando você lida com conceitos amplos e gerais, sem se preocupar com os detalhes específicos de implementação. Por exemplo, uma função chamada &lt;code&gt;processarPagamento()&lt;/code&gt; pode ser uma operação de alto nível, pois você não precisa saber imediatamente como o pagamento é processado, apenas que ele será processado.&lt;/li&gt;
&lt;li&gt;Baixo Nível de Abstração: Isso é como estar na rua, vendo cada detalhe ao seu redor. Em programação, isso envolve lidar com os detalhes específicos e complexidades de uma tarefa. Continuando o exemplo anterior, em um nível mais baixo, &lt;code&gt;processarPagamento()&lt;/code&gt; pode envolver validar os detalhes do cartão, comunicar-se com o banco, verificar o saldo, etc.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Misturar níveis de abstração pode gerar confusão.&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  5. Leia o código de cima para baixo: Regra decrescente
&lt;/h2&gt;

&lt;p&gt;A regra decrescente diz que a leitura do código deve ocorrer de cima para baixo, como uma narrativa, uma série de parágrafos.&lt;/p&gt;

&lt;h2&gt;
  
  
  6. Use nomes descritivos
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;Você sabe que está criando um código limpo quando cada rotina que você lê é como você esperava.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Metade do esforço para satisfazer esse princípio é escolher bons nomes para funções pequenas que fazem apenas uma coisa.&lt;/p&gt;

&lt;p&gt;Quando menor e mais centralizada for sua função, mais fácil será pensar em um nome pra ela. E não tenha medo de criar nomes extensos. &lt;/p&gt;

&lt;p&gt;Um nome longo e descritivo é melhor do que um comentário extenso e descritivo.&lt;/p&gt;

&lt;p&gt;Seja consistente nos nomes. Use as mesmas frases, substantivos e verbos.&lt;/p&gt;

&lt;h2&gt;
  
  
  7. Parâmetros de funções
&lt;/h2&gt;

&lt;p&gt;A quantidade de parâmetros ideal para uma função é zero. Caso não consiga ser zero, deve ser um. Caso não consiga ser um, deve ser dois. Sempre que possível, evite três (ou mais) parâmetros. A utilização de muitos parâmetros complica a interpretação do código.&lt;/p&gt;

&lt;p&gt;Parâmetros são difíceis de lidar em caso de teste também. Imagine a dificuldade em escrever um teste para uma função que requer três parâmetros. Precisamos escrever todos os casos de teste para certificar que todas as combinações de parâmetros funcionem adequadamente.&lt;/p&gt;

&lt;p&gt;Além disso, não use parâmetros lógicos, ou seja, valores booleanos. Esse tipo de parâmetro complica a função, mostrando que ela faz mais de uma coisa. Ela faz uma coisa se for verdadeiro, e outra se for falso. Separe em duas funções.&lt;/p&gt;

&lt;p&gt;Funções que recebem um único parâmetro são chamadas de mônades. Dois parâmetros, díades. Três parâmetros, tríades. &lt;/p&gt;

&lt;h2&gt;
  
  
  8. Objetos como parâmetros
&lt;/h2&gt;

&lt;p&gt;Quando uma função precisar de mais de dois ou três parâmetros, considere criar uma classe específica para eles. Exemplo:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight swift"&gt;&lt;code&gt;&lt;span class="kd"&gt;func&lt;/span&gt; &lt;span class="nf"&gt;createPerson&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;age&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;job&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="kd"&gt;func&lt;/span&gt; &lt;span class="nf"&gt;createPerson&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;person&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Person&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  9. Verbos e palavras-chave
&lt;/h2&gt;

&lt;p&gt;Escolher bons nomes para uma função pode contribuir muito para explicar a intenção da função e a ordem e intenção dos argumentos. A função e o argumento devem formar um par verbo/substantivo. Por exemplo: &lt;code&gt;write(name)&lt;/code&gt; é bastante claro. Um nome será escrito. Um nome ainda melhor seria &lt;code&gt;writeField(name)&lt;/code&gt;, que nos diz que nome é um campo.&lt;/p&gt;

&lt;h2&gt;
  
  
  10. Evite efeitos colaterais
&lt;/h2&gt;

&lt;p&gt;Evitar efeitos colaterais significa garantir que uma função ou método não altere nenhum estado fora de seu escopo ou cause mudanças inesperadas no sistema na qual não estão propostas a fazer dentro do escopo da função. &lt;/p&gt;

&lt;h2&gt;
  
  
  11. Separação comando-consulta
&lt;/h2&gt;

&lt;p&gt;As funções devem fazer ou responder algo, mas não ambos. Sua função ou altera o estado de um objeto ou retorna informações sobre ele. Efetuar as duas tarefas normalmente gera confusão.&lt;/p&gt;

&lt;h2&gt;
  
  
  12. Prefira exceções a retorno de códigos de erro
&lt;/h2&gt;

&lt;p&gt;Em vez de usar códigos de erro para sinalizar problemas ou falhas em uma função, você deve utilizar mecanismos de exceção. Assim, você obtém clareza do código, separação da lógica de erro da lógica de negócios e a prevenção de erros passando despercebidos.&lt;/p&gt;

&lt;p&gt;Além disso, extraia blocos try/catch, pois eles já são um código extenso e devem possuir sua própria função, uma função exclusiva para tratamento de erro/sucesso. Uma função que trata erros não deve fazer mais nada. &lt;/p&gt;

&lt;h2&gt;
  
  
  13. Evite repetição (DRY)
&lt;/h2&gt;

&lt;p&gt;DRY significa don’t repeat yourself, que basicamente diz para evitar duplicidade de código. &lt;/p&gt;

&lt;p&gt;A duplicação é um problema porque ela incha o código e exigirá uma modificação dupla caso o algoritmo precise mudar. Também representa uma oportunidade dupla para um erro de omissão.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusão
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;Programadores experientes veem os sistemas como histórias a serem contadas em vez de programas a serem escritos. &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Se seguir as regras descritas neste resumo, você terá funções mais curtas, bem nomeadas e organizadas. Lembre-se que seu objetivo verdadeiro é contar uma história. &lt;/p&gt;

</description>
      <category>cleancode</category>
      <category>programming</category>
      <category>softwareengineering</category>
    </item>
    <item>
      <title>Clean Code: Lições essenciais do segundo capítulo</title>
      <dc:creator>Giovanna Moeller</dc:creator>
      <pubDate>Thu, 16 Nov 2023 21:01:36 +0000</pubDate>
      <link>https://dev.to/giovannamoeller/clean-code-licoes-essenciais-do-segundo-capitulo-d82</link>
      <guid>https://dev.to/giovannamoeller/clean-code-licoes-essenciais-do-segundo-capitulo-d82</guid>
      <description>&lt;p&gt;O capítulo 02 do livro "Código limpo" fala sobre nomeação.&lt;/p&gt;

&lt;p&gt;Mas nomeação de que, exatamente? Bom, quando falamos em software, temos nomes em vários lugares: variáveis, funções, classes, parâmetros, módulos, arquivos-fonte, diretórios, etc.&lt;/p&gt;

&lt;p&gt;Portanto, vamos falar sobre criar bons nomes:&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Use nomes que revelem o seu propósito
&lt;/h2&gt;

&lt;p&gt;O nome de uma variável, função, classe, etc, deve dizer o porquê aquilo existe, o que ele faz e como é utilizado. Se um nome requer um comentário, então ele não revela seu propósito.&lt;/p&gt;

&lt;p&gt;Exemplo:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;Int&lt;/span&gt; &lt;span class="n"&gt;d&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// tempo decorrido em dias&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Isso não significa absolutamente nada. Nem mesmo o comentário está bom o bastante para entendermos. Tempo de quê estamos falando com esta variável?&lt;/p&gt;

&lt;p&gt;Um exemplo, seria nomear como &lt;code&gt;daysSinceFileCreation&lt;/code&gt;, que significaria o tempo de dias que se passaram desde que um arquivo foi criado, por exemplo. Muito melhor, não?&lt;/p&gt;

&lt;p&gt;Mesmo um código simples pode não ter um propósito, ou pelo menos você não consegue identificar este propósito porque as variáveis não estão definidas de forma com que mostrem pra que servem, o que fazem, por que existem, etc.&lt;/p&gt;

&lt;p&gt;Quando falo de variáveis, quero dizer qualquer coisa que pode ser nomeada.&lt;/p&gt;

&lt;p&gt;O ponto é: escolha nomes que não fique difícil entender o que está acontecendo. Seja extremamente explícito e não importa se o nome ficar muito grande, precisa ser descritivo.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Uma diferença entre um programador esperto e um programador profissional é que este entende que clareza é fundamental. Os profissionais escrevem códigos que outros possam entender.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  2. Evite informações erradas
&lt;/h2&gt;

&lt;p&gt;Se você criar uma variável chamada de &lt;code&gt;accountsList&lt;/code&gt;, mas se o que armazena as contas não for uma &lt;code&gt;List&lt;/code&gt; de verdade, é uma informação errada e pode confundir.&lt;/p&gt;

&lt;p&gt;Outro ponto: não utilize nomes muito parecidos, como &lt;code&gt;ControllerForEfficientHandlingOfStrings&lt;/code&gt; e &lt;code&gt;ControllerForEfficientStorageOfStrings&lt;/code&gt;. São muito semelhantes e passíveis de confusões.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Faça distinções significativas
&lt;/h2&gt;

&lt;p&gt;Como você diferencia uma função chamada de &lt;code&gt;getAccount&lt;/code&gt; para &lt;code&gt;getAccountInfo&lt;/code&gt;? Muito difícil, não? E como você diferencia uma classe chamada de &lt;code&gt;ProductData&lt;/code&gt; e &lt;code&gt;ProductInfo&lt;/code&gt;? Imagine que você acabou de chegar no projeto. Como você deve saber qual utilizar? Complicado, certo?&lt;/p&gt;

&lt;p&gt;Isso normalmente acontece pois não é possível usar o mesmo nome para referir-se a duas coisas diferentes num mesmo escopo, então há a alteração de forma meio "arbitrária", sem pensar. Não faça isso! Faça distinção dos nomes de uma forma que o leitor compreenda as diferenças.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Use nomes pronunciáveis
&lt;/h2&gt;

&lt;p&gt;Imagine criar uma variável &lt;code&gt;mdy&lt;/code&gt; para representar mês, dia e ano? Ou pior, uma variável chamada &lt;code&gt;gdymdym&lt;/code&gt; que representa "generate date, year, month, day, hour, minute"? Como isso seria pronunciável? Impossível, certo? Além de que não é nem um pouco descritível.&lt;/p&gt;

&lt;h2&gt;
  
  
  5. Use nomes passíveis de busca
&lt;/h2&gt;

&lt;p&gt;Imagine que você declare uma variável &lt;code&gt;s&lt;/code&gt; que realiza a soma dos salários de membros de uma equipe. Quando você for buscar pela variável &lt;code&gt;s&lt;/code&gt;, no seu código, irá se deparar com várias outras palavras que contém a letra s.&lt;/p&gt;

&lt;p&gt;Você deve preferir nomes com uma única letra apenas se forem usados como variáveis locais dentro de métodos pequenos, como por exemplo &lt;code&gt;i&lt;/code&gt; para referir ao index de um elemento de um array dentro de um loop.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;O tamanho de um nome deve ser proporcional ao tamanho do escopo.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  6. Nomes de classes
&lt;/h2&gt;

&lt;p&gt;Classes e objetos devem ter nomes com substantivo(s), como &lt;code&gt;Customer&lt;/code&gt;, &lt;code&gt;Account&lt;/code&gt;, &lt;code&gt;AddressParser&lt;/code&gt;, etc. Não deve ser um verbo e não deve ser genérico, como &lt;code&gt;Parser&lt;/code&gt;, &lt;code&gt;Data&lt;/code&gt;, &lt;code&gt;Info&lt;/code&gt;, etc.&lt;/p&gt;

&lt;h2&gt;
  
  
  7. Nomes de métodos
&lt;/h2&gt;

&lt;p&gt;Nomes de métodos devem possuir verbos indicando a ação realizada pelo método, como &lt;code&gt;deletePage&lt;/code&gt;, &lt;code&gt;savePage&lt;/code&gt;, &lt;code&gt;getBalanceFromAccount&lt;/code&gt;, etc.&lt;/p&gt;

&lt;p&gt;Use e abuse de prefixos, como &lt;code&gt;get&lt;/code&gt;, para recuperar um valor, &lt;code&gt;set&lt;/code&gt; para definir ou atualizar um valor, &lt;code&gt;is&lt;/code&gt; para métodos que verificam uma condição, retornando um booleano, etc.&lt;/p&gt;

&lt;h2&gt;
  
  
  8. Utilize uma palavra por conceito
&lt;/h2&gt;

&lt;p&gt;É essencial manter a clareza na nomenclatura. Considere, por exemplo, que em um projeto existem dois componentes distintos: um chamado &lt;code&gt;UserController&lt;/code&gt; e outro nomeado como &lt;code&gt;TransactionManager&lt;/code&gt;. Isso pode gerar confusão, especialmente para quem é novo na equipe.&lt;/p&gt;

&lt;p&gt;Afinal de contas, qual a real diferença entre um 'Controller' e um 'Manager'? Ambos não desempenham funções semelhantes no projeto? Essa ambiguidade de nomes pode levar a mal-entendidos desnecessários. Alguém pode até pensar que 'Controller' e 'Manager' representam conceitos de programação distintos e perder tempo procurando explicações para essa suposta diferença.&lt;/p&gt;

&lt;p&gt;Para evitar essa confusão, é necessário adotar uma abordagem consistente na escolha de nomes. Se um componente é denominado como 'Controller', então outros componentes com funções semelhantes devem seguir essa nomenclatura.&lt;/p&gt;

&lt;h2&gt;
  
  
  9. Adicione um contexto significativo
&lt;/h2&gt;

&lt;p&gt;Quando você tem um conjunto de variáveis como &lt;code&gt;firstName&lt;/code&gt;, &lt;code&gt;lastName&lt;/code&gt;, &lt;code&gt;street&lt;/code&gt;, &lt;code&gt;number&lt;/code&gt;, &lt;code&gt;city&lt;/code&gt;, &lt;code&gt;state&lt;/code&gt; e &lt;code&gt;zipcode&lt;/code&gt;, juntas elas claramente representam um endereço. No entanto, a situação muda quando você encontra uma dessas variáveis, como &lt;code&gt;state&lt;/code&gt;, ou &lt;code&gt;number&lt;/code&gt;, isoladamente em um método. Não é imediatamente óbvio que &lt;code&gt;state&lt;/code&gt; faz parte de um endereço.&lt;/p&gt;

&lt;p&gt;Uma forma de resolver isso é usar prefixos para dar contexto às variáveis. Por exemplo, &lt;code&gt;addressFirstName&lt;/code&gt;, &lt;code&gt;addressLastName&lt;/code&gt; e assim por diante. Esses prefixos ajudam a indicar que estas variáveis são partes de uma estrutura maior, no caso, um endereço.&lt;/p&gt;

&lt;p&gt;Entretanto, uma abordagem mais eficaz seria criar uma classe chamada &lt;code&gt;Address&lt;/code&gt;. Com essa classe, até o compilador reconheceria que estas variáveis pertencem a um contexto maior. Isso não só ajuda na organização do código, mas também melhora a legibilidade e a manutenção, pois torna explícito que essas variáveis estão agrupadas sob um conceito comum.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusão
&lt;/h2&gt;

&lt;p&gt;Para mim, o que mais tirei proveito desse capítulo foi: utilizar de nomes claros e descritivos que revelem o propósito/intenção do seu código.&lt;/p&gt;

&lt;p&gt;Entretanto, refatorar para nomes significativos é um processo que não é fácil. Às vezes, você escolhe um nome e pensa "está bom", e então amanhã, você consegue pensar em um outro nome melhor ainda. É um processo que leva tempo. E sempre há código a ser refatorado.&lt;/p&gt;

&lt;p&gt;Como você pode melhorar seu código hoje?&lt;/p&gt;

</description>
      <category>programming</category>
      <category>cleancode</category>
      <category>softwareengineering</category>
    </item>
    <item>
      <title>Clean Code: Lições essenciais do primeiro capítulo</title>
      <dc:creator>Giovanna Moeller</dc:creator>
      <pubDate>Thu, 09 Nov 2023 17:56:10 +0000</pubDate>
      <link>https://dev.to/giovannamoeller/clean-code-licoes-essenciais-do-primeiro-capitulo-4mo7</link>
      <guid>https://dev.to/giovannamoeller/clean-code-licoes-essenciais-do-primeiro-capitulo-4mo7</guid>
      <description>&lt;p&gt;O primeiro capítulo do livro começa com uma história sobre um aplicativo popular nas décadas passadas que declinou devido ao código confuso e não gerenciável, demorando muito tempo para lançar novas atualizações, corrigir bugs, etc. Isso serve como uma introdução ao problema central abordado no livro: os efeitos prejudiciais de um código ruim.&lt;/p&gt;

&lt;p&gt;Mas, afinal de contas, por que criamos códigos ruins? Foram criados sob pressão? Criados rapidamente? Você queria terminar a tarefa logo e pensou “depois eu refatoro e faço melhor”? Daí vem uma frase mostrada no livro que gostei muito: &lt;strong&gt;Mais tarde é igual a nunca.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;E quais as consequências de um código ruim? Conforme o tempo passa, a produtividade diminui. Uma equipe começa a perceber que o código que criaram rapidamente há alguns anos está dando prejuízo nos dias de hoje: cada alteração feita no código causa uma falha em outras partes do mesmo código, cada adição ao código faz com que códigos já existentes devem ser modificados, entre outros diversos problemas. A bagunça está feita.&lt;/p&gt;

&lt;p&gt;Dedicar tempo para escrever código limpo não é apenas eficaz em termos de custo, mas uma questão de &lt;strong&gt;sobrevivência profissional.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Tentamos nunca nos responsabilizar por ter criado um código ruim, sempre colocando a culpa em curtos prazos, pressões, clientes intolerantes, etc. Mas lembre-se: você é um profissional, e não é profissional que programadores cedam à vontade dos gerentes que não entendem os riscos de se gerar códigos confusos.&lt;/p&gt;

&lt;p&gt;Saber distinguir um código limpo de um código ruim não significa que você sabe escrever um código limpo. Escrever código limpo exige o uso disciplinado de diferentes técnicas. Essas técnicas estão relacionadas a como organizar e estruturar o código para que ele seja fácil de entender e manter. Com o tempo e a experiência, você desenvolve uma espécie de "senso" ou intuição para identificar o que torna um código mais "limpo" ou melhor.&lt;/p&gt;

&lt;p&gt;E o que significa um código limpo? Existem várias definições, e para responder essa pergunta, Robert C. Martin perguntou a diversos programadores experientes o que eles achavam.&lt;/p&gt;

&lt;p&gt;Bjarne Stroupstrup, criador do C++, diz que &lt;strong&gt;o código limpo faz bem apenas uma coisa&lt;/strong&gt;. Ele é centralizado.&lt;/p&gt;

&lt;p&gt;Uma metáfora expressa no livro que gostei muito foi&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;“Uma construção com janelas quebradas parece que ninguém cuida dela. Dessa forma, outras pessoas deixam de se preocupar com ela também. Elas permitem que as outras janelas es quebrem também. No final das contas, as próprias pessoas as quebram. Elas estragam a fachada com pichações e deixam acumular lixo. Uma única janela inicia o processo de degradação.”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Um código ruim incita o crescimento do caos num código. Quando outras pessoas alteram um código ruim, elas tendem a piorá-lo.&lt;/p&gt;

&lt;p&gt;Grady Booch, autor de um livro sobre orientação a objetos, diz que um código limpo é simples e direto, estando repleto de abstrações claras e linhas de controle objetivas. Deve ser decisivo, sem especulações. Deve expor claramente as questões do problema a ser solucionado.&lt;/p&gt;

&lt;p&gt;Dave Thomas, fundador da OTI, diz que um código sem testes não está limpo. Ressalta também que o código deve ser escrito de uma forma que seja inteligível (compreensível) aos seres humanos.&lt;/p&gt;

&lt;p&gt;Michael Feathers, autor de um livro sobre códigos legados, diz que um código limpo sempre parece que foi escrito por alguém que se importava com o que estava escrevendo.&lt;/p&gt;

&lt;p&gt;Ron Jeffries, autor de um livro C#, resume que o código limpo deve ser um código com testes, sem duplicação, entidades devem seguir o padrão de responsabilidade única (isto será abordado e discutido mais a frente), deve ser expressivo e com pequenas abstrações.&lt;/p&gt;

&lt;p&gt;Ward Cunningham, cocriador do eXtreme programming, diz que ao ler um código limpo nada deve te surpreender. O código é óbvio, simples e convincente. Cada módulo prepara o terreno para o seguinte.&lt;/p&gt;

&lt;p&gt;Por fim, o livro diz para não tornar este conhecimento descrito ao decorrer como “a única fonte da verdade”, você pode concordar ou discordar de certos pontos. E está tudo bem. Além disso, somos autores de códigos e todo autor tem leitores, com os quais uma boa comunicação é responsabilidade dos autores. Constantemente também lemos códigos antigos quando escrevemos novos.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Se quer que seu código seja de fácil escrita, torne-o de fácil leitura.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Não basta escrever um código bom. Ele precisa ser mantido sempre limpo. “Deixe a área do acampamento mais limpa do que como você a encontrou.”&lt;/p&gt;

&lt;p&gt;A refatoração para o código limpo nunca acaba. Sempre há código que pode ser melhorado.&lt;/p&gt;

</description>
      <category>cleancode</category>
      <category>softwaredevelopment</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
