<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://bpoplauschi.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://bpoplauschi.github.io/" rel="alternate" type="text/html" /><updated>2026-05-19T09:49:26+00:00</updated><id>https://bpoplauschi.github.io/feed.xml</id><title type="html">Bogdan Poplauschi’s blog</title><subtitle>Welcome to my personal blog. It contains posts based on my experience in the field of Software Developement and more.</subtitle><entry><title type="html">Software Development Book Recommendations</title><link href="https://bpoplauschi.github.io/2025/04/08/Software-dev-book-recommendations.html" rel="alternate" type="text/html" title="Software Development Book Recommendations" /><published>2025-04-08T05:00:00+00:00</published><updated>2025-04-08T05:00:00+00:00</updated><id>https://bpoplauschi.github.io/2025/04/08/Software-dev-book-recommendations</id><content type="html" xml:base="https://bpoplauschi.github.io/2025/04/08/Software-dev-book-recommendations.html"><![CDATA[<meta name="Timeless software‑engineering books that transformed my daily coding, from DDD to TDD." />

<p>If you’re a developer who wants evergreen guidance instead of the flavor‑of‑the‑month framework book, start here.</p>

<blockquote>
  <p>“The best way to predict the future is to create it.”<br />
— Abraham Lincoln.</p>
</blockquote>

<p>I believe most skills are acquired through hard work and discipline. And that successful people have a track record of applying these.<br />
To become a better version of yourself, you must find room to grow and fill it. By learning, by trying, by deciding to no longer tolerate your limitations.</p>

<p>One guaranteed way to learn and grow is by <strong>studying the great books from a certain domain</strong>.
I’ve compiled a top list of Software Development books, books that were simply <strong>transformational</strong>.
When it comes to learning, I prefer a proven track, so I mostly focus on <strong>timeless classics</strong> instead of following trends and the most recent publications.
These are mostly books that offer depth, explaining ideas, concepts, paradigms, techniques, patterns. Most of them are <strong>platform and language agnostic</strong>, so they are <strong>applicable to Software development in general</strong>.</p>

<p><strong>Disclaimer:</strong> I recommend <strong>studying</strong> these books, and <strong>learning</strong> from them, <strong>not just reading</strong>. This means <strong>reading more than once</strong>, <strong>taking notes</strong>, <strong>trying out</strong> the concepts in real life, trying to <strong>link the new knowledge to the one you already have</strong> (to make learning effective).</p>

<p><em>Format: I tried summarizing the book in one paragraph, define the book’s impact on me and listing my main takeaways.</em></p>

<h1><img src="https://images-na.ssl-images-amazon.com/images/I/71eC9gxlJAL._AC_UL232_SR232,232_.jpg" width="200" /></h1>
<h1 id="dependency-injection-in-net-by-mark-seeman"><a href="https://www.amazon.com/Dependency-Injection-NET-Mark-Seemann/dp/1935182501">Dependency Injection in .NET by Mark Seeman</a></h1>

<p>This book offers a thorough explanation of how to <strong>decouple</strong> software components by <strong>injecting</strong> their <strong>dependencies</strong> at runtime, enabling more flexible, testable, and maintainable code in applications.</p>

<p>For me, it has transformed the way I design and code apps, deeply understanding layering and dependencies, modularizing (based on the requirements), but also having a proven mechanism (Composition Root) to compose modules into different apps or flavors of the same app.</p>

<p>Takeaways:</p>
<ul>
  <li><strong>Manual DI</strong>: Constructor, Property or Method Injection.</li>
  <li><strong>Constructor Injection</strong> is the safest option in compiler-based languages, as the compiler won’t allow constructing an object unless its dependencies are provided.</li>
  <li><strong>Service Locator anti-pattern</strong> - widely used pattern which leads to high-coupling and can generate runtime errors when dependencies are missing.</li>
  <li>Choosing between <strong>Manual DI</strong> vs <strong>DI containers</strong> (the later should not be used in all app layers, but rather in the Composition Root only).</li>
  <li><strong>Modularity</strong> and how to <strong>compose an app using modules</strong> and <strong>a Composition Root</strong>.</li>
  <li><strong>Composition Root pattern</strong> = the lowest level and most concrete component, the app entry point.</li>
  <li>How to implement <strong>Cross-Cutting concerns</strong> with the <strong>Decorator pattern</strong>.</li>
</ul>

<h1 id="-1"><img src="https://images-na.ssl-images-amazon.com/images/I/81iVQ1bi-FL._AC_UL232_SR232,232_.jpg" width="200" /></h1>
<h1 id="working-effectively-with-legacy-code-by-michael-feathers"><a href="https://www.amazon.com/Working-Effectively-Legacy-Michael-Feathers/dp/0131177052">Working Effectively with Legacy Code by Michael Feathers</a></h1>

<p>If you’re a developer, you work with <strong>legacy code</strong>. This book highlights the <strong>high value of existing, functioning code</strong> and shows how to <strong>make small adjustments to make it testable and unlock refactoring</strong>.</p>

<p>This book transformed the way I look at code, especially legacy code. From running away from legacy code and being intimidated by such challenges, it flipped the narrative and allowed me to see all the opportunities to improve that already functioning code, following these battle-proven techniques and patterns. Having these skills makes me stand out as an engineer.</p>

<p>Takeaways:</p>
<ul>
  <li><strong>Legacy code</strong> = <strong>code without tests or with an unclear structure, regardless of age</strong>.</li>
  <li>Use the <strong>recipes</strong> in the book to make <strong>small safe changes that enable testability</strong>.</li>
  <li><strong>Seam</strong> = place where you can alter behavior without modifying existing code directly - essential for introducing tests and making controlled changes.</li>
  <li>Write <strong>Characterization Tests</strong> for legacy code which enable safe refactorings.</li>
  <li><strong>Sprout Method / Class</strong> - instead of modifying an existing method or class, you “sprout” a new one that safely holds new functionality.</li>
  <li><strong>Wrap Method / Class</strong>: Wrapper around existing entity to intercept or adjust behavior without changing the original one.</li>
  <li><strong>Breaking Dependencies</strong> - see techniques for dealing with problematic dependencies (like <em>singletons</em>, <em>static methods</em>, or <em>global variables</em>) so that you can isolate and test the units in question. Often involves introducing interfaces or employing DI.</li>
  <li><strong>Extract and Override Call</strong>: Move direct dependency call (e.g., to a difficult API) into separate method that you can override in a subclass, avoiding the real dependency in tests.</li>
  <li><strong>Extract Interface</strong>: Split an existing class into an interface and an implementation; the interface can then be mocked or substituted as needed.</li>
  <li><strong>Parameterize Constructor or Method</strong>: Let the constructor / method accept external dependencies (instead of hard-coding them).</li>
  <li><strong>Pull Up / Push Down Feature</strong>: Move a field or method from derived classes into a base class when it is shared logic; move the other way to isolate specialized behavior.</li>
  <li><strong>Extract Method</strong>: Pull out piece of logic from a larger method into a separate one.</li>
</ul>

<h1 id="-2"><img src="https://m.media-amazon.com/images/S/aplus-media-library-service-media/33cd7d27-7bca-4d52-aad6-698145aec419.__CR200,0,1200,1200_PT0_SX300_V1___.png" width="200" /></h1>
<h1 id="domain-driven-design-tackling-complexity-in-the-heart-of-software-by-eric-evans"><a href="https://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software-ebook/dp/B00794TAUG">Domain-Driven Design: Tackling Complexity in the Heart of Software by Eric Evans</a></h1>

<p>This book emphasizes structuring and implementing software around a deep understanding of the business domain, using a Ubiquitous Language and well-defined boundaries to create models that reflect real-world complexity effectively.</p>

<p>This book is incredibly deep, with very subtle but powerful concepts and examples. It made me push for a unified language between all the stakeholders involved in Software Development. And it enhanced the awareness I keep on the domain model and its separation from other layers.</p>

<p>Takeaways:</p>
<ul>
  <li><strong>Focus on the Core Domain</strong>: Invest time and resources in the core domain (business  strategic advantage) and model it with precision and clarity.</li>
  <li><strong>Iterative Model Refinement</strong>: Continuously refine the model as new insights emerge, using ongoing collaboration and domain exploration to keep it aligned with real-world needs.</li>
  <li><strong>Align Design and Implementation</strong>: Ensure that code structure reflects the domain model and that the model is kept in sync with the code - refactor the code to keep up.</li>
  <li><strong>Ubiquitous Language</strong>
    <ul>
      <li>A shared language between domain experts and developers.</li>
      <li>Ensures everyone speaks consistently about the model, preventing misunderstandings.</li>
    </ul>
  </li>
  <li><strong>Bounded Context</strong>
    <ul>
      <li>A boundary within which a particular domain model applies.</li>
      <li>Helps avoid confusion due to overlapping or duplicated concepts across different parts of the system.</li>
    </ul>
  </li>
  <li><strong>Associations</strong></li>
  <li><strong>Entities</strong>, <strong>Value Objects</strong>, <strong>Aggregates</strong>, <strong>Services</strong></li>
  <li><strong>Repositories</strong>, <strong>Factories</strong>, <strong>Domain Events</strong></li>
  <li><strong>Anti-Corruption Layer</strong></li>
  <li><strong>CQS at domain model level</strong></li>
</ul>

<h1 id="-3"><img src="https://m.media-amazon.com/images/I/41odjJlPgHL._AC_SF480,480_.jpg" width="200" /></h1>
<h1 id="refactoring-improving-the-design-of-existing-code-by-martin-fowler"><a href="https://www.amazon.com/Refactoring-Improving-Existing-Addison-Wesley-Signature/dp/0134757599">Refactoring: Improving the Design of Existing Code by Martin Fowler</a></h1>

<p>Refactoring is not rewriting; it’s a methodical process of cleaning up code with recipe-like steps. Think of this as the classic “recipe book” for refactoring.</p>

<p>I use it regularly, especially given the IDE I mostly use (Xcode) has very limited automated refactoring capabilities.
The most transformative concept for me was deeply understand what refactoring is and trying to refactor as much as possible ever since - of course, by preserving the code behavior.</p>

<p>As Kent Beck explained it, a developer can wear multiple hats, only one at a time. Changing functionality is done under a different hat than refactoring. Making this separation I believe to be making your output so much clearer.</p>

<p>Takeaways:</p>
<ul>
  <li><strong>Incremental Improvements</strong>: effective refactoring happens in <strong>small</strong>, <strong>safe</strong> steps:
    <ul>
      <li>make one change at a time</li>
      <li>run tests</li>
      <li>and proceed only if the system remains stable.</li>
    </ul>
  </li>
  <li><strong>Code Smells</strong> indicate where to refactor - e.g.  Long Method, Large Class, Primitive Obsession, Switch Statements, Divergent Change, Shotgun Surgery.</li>
  <li><strong>Automated Testing Is Essential</strong>: Having robust unit and integration tests enables you to refactor with confidence.</li>
  <li><strong>Refactoring Preserves Behavior</strong>: The goal is to change the structure, not the functionality; if system behavior changes, that’s not a pure refactoring.</li>
  <li><strong>Refactoring Improves Maintainability</strong>: Well-structured code is easier to understand, modify, and extend, ultimately saving time and effort in the long run.</li>
  <li><strong>Composition Over Inheritance</strong>: Wherever appropriate, prefer using composition to extend functionality rather than complex class hierarchies; this often reduces coupling.</li>
  <li><strong>Encapsulate What Varies</strong>:  Identify aspects of the code that might change or expand over time and encapsulate them (e.g., through design patterns like <strong>Strategy</strong> or <strong>Decorator</strong>).</li>
  <li><strong>Replace Conditionals with Polymorphism</strong>:  Frequent <code class="language-plaintext highlighter-rouge">if / else</code> or <code class="language-plaintext highlighter-rouge">switch</code> statements can often be replaced with polymorphic classes or methods to simplify control flow and make code more extensible.</li>
  <li><strong>Naming Matters</strong>: Consistent and meaningful names for variables, methods, and classes help communicate intent and maintain clarity.</li>
  <li><strong>Continuous Refactoring Culture</strong>: Treat refactoring as an ongoing, integral part of development rather than a one-time event—this keeps code healthy over its entire lifespan.</li>
</ul>

<h1 id="-4"><img src="https://m.media-amazon.com/images/I/413za4fzZLL._AC_SF480,480_.jpg" width="200" /></h1>
<h1 id="clean-code-a-handbook-of-agile-software-craftsmanship-by-robert-martin"><a href="https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882">Clean Code: A Handbook of Agile Software Craftsmanship by Robert Martin</a></h1>

<p>Clean Code emphasizes writing readable, maintainable, and elegant code by following core principles, best practices, and disciplined craftsmanship that leads to higher-quality software.</p>

<p>Reading Clean Code and Clean Coder was the point in time where I stopped being a “hacker” (in the sense of hacking things together so they work) and moved towards being a professional developer, that follows standards, metrics, rules, that takes pride of their work. In my case, it was an identity transformation.</p>

<p>Takeaways:</p>
<ul>
  <li><strong>SOLID principles</strong>: applying all the 5 principles is fundamental to writing maintainable, readable, testable code.</li>
  <li><strong>Readability Is Key</strong>: Code should be optimized for human comprehension first, ensuring that anyone can easily understand and modify it in the future.</li>
  <li><strong>Small, Focused Functions and Classes</strong>: Methods and classes should do exactly one thing and do it well, which keeps the codebase modular, testable, and easier to maintain.</li>
  <li><strong>Meaningful Names</strong>: Clear, descriptive naming for variables, functions, and classes significantly reduces confusion and improves overall readability.</li>
  <li><strong>Continuous Refactoring</strong>: Regularly improving existing code keeps it clean and up to date, preventing “code rot” and complexity from creeping in over time.</li>
  <li><strong>Emphasis on Testing</strong>: Testing (often through TDD) helps catch issues early and ensures the code’s design stays simple, robust, and reliable.</li>
  <li><strong>Error Handling</strong>: Handle errors gracefully and clearly. Use exceptions for exceptional conditions and provide context in error messages.</li>
  <li><strong>Code comments</strong>: Favor self-explanatory code over excessive comments. Use comments sparingly to clarify complex logic rather than to explain poorly written code.</li>
  <li><strong>Comments show our inability to express ourselves through code.</strong></li>
  <li><strong>Formatting and Consistency</strong>: Follow consistent formatting rules to help others (and your future self) navigate the code easily.</li>
  <li><strong>Boy Scout Rule: Leave the camp cleaner than you found it.</strong></li>
</ul>

<h1 id="-5"><img src="https://m.media-amazon.com/images/I/4192DPXrLJL._AC_SF480,480_.jpg" width="200" /></h1>
<h1 id="the-clean-coder-a-code-of-conduct-for-professional-programmers-by-robert-c-martin"><a href="https://www.amazon.com/Clean-Coder-Conduct-Professional-Programmers/dp/0137081073">The Clean Coder: A Code of Conduct for Professional Programmers by Robert C. Martin</a></h1>

<p>The Clean Coder emphasizes the ethics, mindset, and practices that distinguish professional programmers, focusing on responsibility, discipline, and clear communication to produce high-quality software.</p>

<p>Takeaways:</p>
<ul>
  <li><strong>Professionalism as a programmer, Standards and Accountability</strong></li>
  <li><strong>Clear communication and Boundaries</strong></li>
  <li><strong>Discipline in Coding Practices</strong>: TDD, Refactoring, CI</li>
  <li><strong>Handling timelines, pressure, estimations</strong></li>
  <li><strong>Continuous Learning and Improvement</strong></li>
</ul>

<h1 id="-6"><img src="https://m.media-amazon.com/images/I/41fijVG5x7L._AC_SF480,480_.jpg" width="200" /></h1>
<h1 id="clean-architecture-a-craftsmans-guide-to-software-structure-and-design-by-robert-c-martin"><a href="https://www.amazon.com/Clean-Architecture-Craftsmans-Software-Structure/dp/0134494164">Clean Architecture: A Craftsman’s Guide to Software Structure and Design by Robert C. Martin</a></h1>

<p>Clean Architecture describes principles and design practices for creating software systems that are resilient to changing requirements, easily testable, and maintainable over their entire lifecycle.</p>

<p>Takeaways:</p>
<ul>
  <li><strong>Separation of concerns</strong></li>
  <li><strong>SOLID Principles</strong> in detail, at the method, class and module levels.</li>
  <li><strong>Entities</strong></li>
  <li><strong>Business rules</strong></li>
  <li><strong>Usecases</strong></li>
  <li><strong>Frameworks and drivers</strong></li>
  <li><strong>Layers and Boundaries</strong></li>
  <li><strong>Plug-in Architecture</strong></li>
</ul>

<h1 id="-7"><img src="https://m.media-amazon.com/images/S/aplus-media/vc/9f54365c-c4c5-451f-a2c1-c9893fa4a45d.__CR0,104,1076,1076_PT0_SX300_V1___.png" width="200" /></h1>
<h1 id="ios-unit-testing-by-example-xctest-tips-and-techniques-using-swift-by-jon-reid"><a href="https://www.amazon.com/iOS-Unit-Testing-Example-Techniques/dp/1680506811">iOS Unit Testing by Example: XCTest Tips and Techniques Using Swift by Jon Reid</a></h1>

<p>This is a practical guide to writing maintainable and robust iOS applications through effective unit testing and test-driven development (TDD) principles, focusing on both Swift and Objective-C codebases.</p>

<p>Automated testing is such a complex domain and it requires so many other skills to be put to practice. More so TDD. It’s one thing to write some unit tests and another to choose between numerous types of tests, write clean concise tests, that exercise the behavior of the code and not its structure so that one can later refactor that code without breaking the tests.
With the help of this book and the iOS Lead Essentials program by Caio and Mike, I was able to take my testing skills to the next level. I became proficient with testing, capable of thinking strategically about testing strategies and their implementation using various types of tests.</p>

<p>Takeaways:</p>
<ul>
  <li><strong>TDD encourages Clean Code</strong></li>
  <li><strong>Clear test structure</strong> improves readability: use patterns like <strong>Arrange-Act-Assert (AAA)</strong> and give tests <strong>descriptive names</strong></li>
  <li>Using test doubles are essential skills: mocks, stubs, fakes</li>
  <li>Continuous testing boosts confidence: run these locally, while you develop, after every change. Also run them as part of the CI pipelines</li>
  <li><strong>Well-written, high-coverage</strong> <strong>tests</strong> serve as a <strong>safety net for refactoring</strong>, encouraging developers to improve design <strong>without fear</strong> of breaking existing functionality.</li>
</ul>

<h1 id="-8"><img src="https://images-na.ssl-images-amazon.com/images/I/71f1jieYHNL._AC_UL232_SR232,232_.jpg" width="200" /></h1>
<h1 id="the-pragmatic-programmer-your-journey-to-mastery-by-andrew-hunt-and-david-thomas"><a href="https://www.amazon.com/Pragmatic-Programmer-journey-mastery-Anniversary/dp/0135957052">The Pragmatic Programmer: Your Journey To Mastery by Andrew Hunt and David Thomas</a></h1>

<p>The Pragmatic Programmer provides practical guidance and a mindset for software developers to continually refine their craft, create robust solutions, and take ownership of all aspects of their code.</p>

<p>This book may seem trivial in some ways, but it has a subtle intelligence to it. It highlights an art of being balanced, pragmatic, of choosing wisely between quick and dirty and clean elaborate solutions. It highlights the need to be focused so you can choose from all the tools at your disposal. And it does a great job at showcasing many of these tools that were here many years ago when it was first published.</p>

<p>Takeaways:</p>
<ul>
  <li>Embrace <strong>continuous learning</strong>.</li>
  <li>Adopt a <strong>pragmatic mindset</strong> over dogmatic rules.</li>
  <li>Focus on <strong>clean design</strong> and <strong>DRY</strong>: minimize duplication, promote reusable components, and favor simplicity to reduce complexity.</li>
  <li>Take <strong>ownership</strong> and <strong>responsibility</strong>: Take pride in your work, own the quality of your code, and be proactive in identifying and fixing potential problems or misunderstandings.</li>
  <li>Refactor early and often.</li>
  <li><strong>Orthogonality</strong> and <strong>decoupling</strong>: Strive for independent components whose functionality does not overlap, making your system more adaptable, maintainable, and testable.</li>
  <li><strong>Tracer Bullets</strong>: Implement thin, end-to-end solutions to test architecture and feasibility early, guiding further development through continuous feedback.</li>
  <li><strong>Prototyping</strong>: Build quick, disposable implementations to explore ideas, verify assumptions, or confirm feasibility without committing to production-quality code right away.</li>
  <li><strong>Design by Contract</strong>: Define clear, enforceable contracts for functions, modules, or services (preconditions, postconditions, and invariants) to ensure correct behavior.</li>
  <li><strong>Automation</strong>: Invest in tools that automate repetitive or error-prone tasks (testing, builds, deployment) so you can focus on high-value work.</li>
  <li><strong>Coding Conventions and Standards</strong>: Maintain consistent naming, formatting, and architectural decisions to improve team collaboration and readability.</li>
  <li><strong>Collaboration and Communication</strong>: Write clear documentation, engage in effective code reviews, and communicate openly with team members to address issues early and improve collective knowledge.</li>
</ul>

<h1 id="-9"><img src="https://images-na.ssl-images-amazon.com/images/I/61Jdrn9cfpL._AC_UL232_SR232,232_.jpg" width="200" /></h1>
<h1 id="extreme-programming-explained-embrace-change-by-kent-beck"><a href="https://www.amazon.com/Extreme-Programming-Explained-Embrace-Change/dp/0321278658">Extreme Programming Explained: Embrace Change by Kent Beck</a></h1>

<p>Consider this the field manual on Extreme Programming (XP) and Test Driven Development (TDD).
XP is a lightweight, people-centric methodology that emphasizes rapid feedback, short development cycles, close collaboration, and continuous improvement to deliver high-quality software in the face of changing requirements.</p>

<p>Takeaways:</p>
<ul>
  <li><strong>Core XP Values: Communication, Simplicity, Feedback, Courage, Respect</strong>.</li>
  <li><strong>TDD</strong>: Writing automated tests before coding to guide design and validate functionality. Uses a Red - Green - Refactor cycle.</li>
  <li><strong>Pair Programming</strong>: Two or more developers share one workstation, continuously reviewing and improving each other’s work. Produces quality design, less defects, reduces need to use the classical code review workflow.</li>
  <li><strong>Continuous Integration</strong>: Frequent merging of code changes to identify integration problems early.</li>
  <li><strong>Refactoring</strong>: Systematic improvement of code structure without altering functionality.</li>
  <li><strong>Simple Design</strong>: Always aim for the simplest system that works, deferring complexity until necessary.</li>
  <li><strong>On-Site Customer</strong>: Having a real customer or representative available for immediate feedback and clarification.</li>
  <li><strong>Collective Code Ownership</strong>: Any team member can modify any part of the code at any time.</li>
  <li><strong>Whole Team</strong>: All roles (developers, testers, domain experts) collaborate continuously.</li>
  <li><strong>Sustainable Pace</strong>: Avoid burnout by maintaining a healthy, consistent work pace.</li>
</ul>

<h1 id="feedback">Feedback</h1>

<p>What are the books that have changed the way you work, the way you think? What’s your favorite learning from them?</p>

<p>What book from this list are you planning to read next? Why?</p>

<p>Let me know in the comments section. I’d be happy do discuss and learn from you too.</p>]]></content><author><name></name></author><category term="books" /><summary type="html"><![CDATA[]]></summary></entry><entry><title type="html">Git basics</title><link href="https://bpoplauschi.github.io/2023/02/21/Git-basics.html" rel="alternate" type="text/html" title="Git basics" /><published>2023-02-21T05:00:00+00:00</published><updated>2023-02-21T05:00:00+00:00</updated><id>https://bpoplauschi.github.io/2023/02/21/Git-basics</id><content type="html" xml:base="https://bpoplauschi.github.io/2023/02/21/Git-basics.html"><![CDATA[<h2 id="summary">Summary</h2>
<ul>
  <li>What is source control and how it works</li>
  <li>What is git and how it works</li>
  <li>The main git entities</li>
  <li>What are git hosting services</li>
  <li>The main git commands and flows</li>
</ul>

<h2 id="what-is-source--version-control">What is source / version control</h2>
<p>Version control, also known as source control, is the practice of tracking and managing changes to software source code. Version control systems are software tools that help software teams manage changes to source code over time. They do this by recording the changes to files over time.</p>

<p>Why? Because the source code is an important asset for any team, so protecting it is essential.
Source control systems allow:</p>
<ul>
  <li>Backing up code</li>
  <li>Having a history for each individual file, so we can go through each of these versions. The source control history is a piece of documentation that is updated along with the source code and ideally tracks and explains the reasons for each change made to the code</li>
  <li>You can preview previous states and decide to revert some or all the files to such a previous state</li>
  <li>Teams can parallelize development by allowing different members to work on different tasks (features, bugs, …). Source control allows integrating all these independent modifications to the code.</li>
  <li>Comparing and tracking changes over time, identify the exact time when a change was introduced and why</li>
</ul>

<h2 id="what-is-git">What is Git</h2>
<p>By far, the most widely used modern version control system in the world today is Git. Git is a mature, actively maintained open-source project originally developed in 2005 by Linus Torvalds, the famous creator of the Linux operating system kernel. A staggering number of software projects rely on Git for version control, including commercial projects as well as open source.</p>

<p>At the root of the git system is the concept of a repository. The repository is used to store different files and folders in a tree structure, like a miniature file system.</p>

<p>Most version control systems store the information as a list of file-based changes. 
Git works differently, as git organizes its data like a set of snapshots on a miniature file system. These snapshots are called git commits. Every time you create a new commit, you basically save the state of the project files in git and create a reference to that state. That is what a commit is.
Git is efficient and if some files have not changed from a previous snapshot, it will only link to the previous identical file it has already stored.
You can think about it as a stream of snapshots.</p>

<h3 id="text-and-binary-files">Text and binary files</h3>
<p>Git is very efficient in working with text files, such as source code files, plists, jsons, string files … This is because it can calculate the differences between text files and even apply compression to store them very efficiently.
Diff is a shorter version of difference, and we will use this term further to describe the differences between 2 versions of the same file.
Git can handle other non-text file types as binary files (images, videos, libraries, …), but it can’t apply the same optimizations as for text files. Storing many binary files, especially large ones, can impact the performance of git.
If that happens, you can look into the git large file system extension that is designed for large binary files.</p>

<h2 id="why-git">Why git?</h2>
<p>Simply because git is:</p>
<ul>
  <li>Distributed
    <ul>
      <li>Each developer has a clone of the whole repository</li>
      <li>Offline access</li>
      <li>Multiple back-ups</li>
      <li>No need to share unwanted changes - you can keep some changes local until they are ready</li>
      <li>Sharing is easy</li>
    </ul>
  </li>
  <li>Fast
    <ul>
      <li>Nearly all operations are performed locally → no need to constantly talk to the server → very fast</li>
      <li>Git uses gzip compression</li>
      <li>The only operation that is slower is the initial clone operation, where git is downloading the entire history of the repository</li>
    </ul>
  </li>
  <li>Preserves the integrity of the files
    <ul>
      <li>The data model that Git uses ensures the cryptographic integrity of every bit of your project.</li>
      <li>Every file and commit is checksummed and retrieved by its checksum when checked back out.</li>
      <li>It’s impossible to get anything out of Git apart from the exact bits you put in.</li>
    </ul>
  </li>
  <li>Supports non-linear development
    <ul>
      <li>Git allows and encourages you to have multiple local branches that can be entirely independent of each other.</li>
      <li>Keeps multiple streams of work independent of each other while also providing the facility to merge that work back together, enabling developers to verify that the changes on each branch do not conflict.</li>
      <li>Creating, merging and deleting these lines of development takes  seconds.</li>
    </ul>
  </li>
  <li>Scalable</li>
  <li>Simple, Free and Open source</li>
</ul>

<h2 id="git-hosting-services">Git hosting services</h2>
<p>Git is a version control system that can be viewed as a tool. To store git repositories, we need hosting services. These are called git hosting services, and they act like servers that host git repositories among other things (e.g. user-based access and permissions, repo statistics, …).
Famous ones include: GitHub, Bitbucket, GitLab.</p>

<p>In a simplified scenario, git can be used entirely locally on just one machine, but its greatest power is when it’s used across machines.</p>

<p>Most people will use git as a server - client, where one git server like GitHub will act as the single source of truth. All the clients will pull code from the server, make local changes and push the modified code to the same server. But that’s not the only way in which git can work. Being a distributed system, each machine having a copy of the repository can act as a server for other machines.</p>

<h2 id="main-git-entities">Main Git entities</h2>

<h3 id="repository">Repository</h3>
<p>The repository is a data structure that stores files and folders and corresponding metadata.
This metadata is saved in a special .git folder and is represented by all the versions of these files and folders over time.
Or you can look at a repository like a collection of commits.
Each client will have a full copy of the repository.</p>

<h3 id="working-copy">Working copy</h3>
<p>The working copy is a single checkout of one version of the project. These files are pulled out of the database in the .git directory and placed on disk for you to use or modify.</p>

<h3 id="commit">Commit</h3>
<p>The commit is a snapshot of your working copy at a certain time, identified by a revision number (hash). Besides the snapshot, it contains info such as the author, the date, and time and a message describing the changes done. Each commit can have from zero parents (the 1st commit in each repo), to 1 parent (linear structure) to more than 1 parent (where a merge was done).</p>

<h3 id="branch-and-tag">Branch and tag</h3>
<p>While for many version control systems, branches and tags are full copies of the repository content, in git, branches and tags are just commits with a name attached to them.
That is why it’s trivial to create / remove branches or even to update them aka change the commit with the name. The same is true for tags, even though git tag commands are a bit more restrictive.
From a theoretical standpoint, a branch supports an independent line of development. It has a lifetime, when the developers will use the branch to develop independently of other branches, commit their work and in the end, port their changes back to one of the main branches.</p>

<p><img src="/assets/git/git-branches-tags.png" alt="git branches and tags" /></p>

<p>In contrast, a tag is a label we attach to a version of the project that we want to preserve with time, so we can revisit later. For example, releasing a new version of the project is a good time to create such a label, so you know exactly the state of the source code used for that release. So in that line, tags are not meant to be modified.</p>

<h3 id="head">HEAD</h3>
<p>The HEAD is the name of the commit that’s currently checked out. In git, you can check out any commit at any time. Checkout means simply setting the repo files in the state of the commit you select.</p>

<h2 id="git-commands">Git commands</h2>
<p>Git uses many commands with different options that allow a multitude of operations. 
Any tool you use would still rely on these commands under the hood:
Git clients like Xcode’s git integration, SourceTree, GitHub’s Mac App, …
Or even editing the repo through a website (i.e. GitHub’s web interface)
They all work with the same git commands and show the same info from git.</p>

<h3 id="config">Config</h3>
<p>When you first install git on a machine, you need to configure it. Configuring git can be done through the git config command or by directly editing a file <code class="language-plaintext highlighter-rouge">~/.gitconfig</code>.
Using the commands will edit the same file we just mentioned.
You can at least set up your git username and email.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git config --global user.name "John McClane"
git config --global user.email "john@email.com"
</code></pre></div></div>

<h3 id="creating-a-new-repository">Creating a new repository</h3>
<p>To create a new local git repository, we will use the <code class="language-plaintext highlighter-rouge">git init</code> command in the folder that we want to be the root folder of the repository.
This will just initialize the git repository by creating a <code class="language-plaintext highlighter-rouge">.git</code> folder with some basic info. The repository is empty, there are no commits, no branches or other entities yet.</p>

<p>Hosting services like GitHub also have an option to create a new repository. Using this option will require you to answer a few questions like the name and location of the new repository and if it needs any template files like <code class="language-plaintext highlighter-rouge">README</code> or <code class="language-plaintext highlighter-rouge">LICENSE</code>. GitHub will create a new repository on its backing git system. It will also create a first commit with all the files you chose to create. 
And a branch called <code class="language-plaintext highlighter-rouge">main</code>. 
To use this new repository, you need to clone it on your machine.</p>

<h3 id="cloning-a-repository">Cloning a repository</h3>
<p>By using the <code class="language-plaintext highlighter-rouge">git clone &lt;URL&gt;</code> command, one can clone aka fully copy a repository on his / her machine. You require this to be able to make changes to the repository.
For the cloning to work, you will need permissions to that repository.
There are 2 main types of cloning - via <strong>HTTPS</strong> or <strong>SSH</strong>.</p>

<h4 id="via-https">Via HTTPS</h4>
<p>Using an HTTPS url like https://github.com/bpoplauschi/bpoplauschi.github.io.git will set up an HTTPS connection to the repo, so it will require a user and password authentication in order to clone it and for all future communications with the git server.</p>

<h4 id="via-ssh">Via SSH</h4>
<p>Using a SSH url like git@github.com:bpoplauschi/bpoplauschi.github.io.git will create an SSH connection which requires an SSH public - private key pair that is used for authentication.
You will need to set up your machine so it allows SSH connections to services like GitHub by creating a local SSH key pair or installing a key pair from another machine - see <a href="https://docs.github.com/en/authentication/connecting-to-github-with-ssh">Connecting to GitHub with SSH</a>. The public key needs to be added to your GitHub account, so the service has it so it will allow your connections using the private key.
You can easily verify your SSH setup is correct by running <code class="language-plaintext highlighter-rouge">ssh git@github.com</code>.</p>

<p>In either case, you need read access to the repository or just a public repository to perform the clone.</p>

<p>Now that you have a local repository (either by cloning or creating a new local repo), you can start editing it.</p>

<h3 id="status">Status</h3>
<p>You can always inspect the status of the repo using the <code class="language-plaintext highlighter-rouge">git status</code> command - this will output the current checked out branch and local changes, both non-staged and staged.</p>

<h3 id="staging-area">Staging area</h3>
<p>After you make changes to the files in your repository, you will need to commit those changes into the repository.
Git has a so-called “staging area” that is an intermediate area where commits can be formatted and reviewed before completing the commit.
You can add and remove to and from stage entire files or just some modified lines. 
<code class="language-plaintext highlighter-rouge">git add</code>
Some git tools (like Xcode’s git integration) will not show you the staging area, but it’s useful to know it’s there.
When you commit, you will commit all the content added to the staging area.</p>

<p>NOTE: any change to a file that is not committed can be lost if we change branches, merge, reset, … Only after we have committed, we are confident the data is safely stored in our repository. So commit as often as possible - this will help you avoid losing precious code.</p>

<p>NOTE: you can always drop changes and go back to the previous git state using different commands. One such command is <code class="language-plaintext highlighter-rouge">git reset –hard</code> that will undo all the local changes from the current <code class="language-plaintext highlighter-rouge">HEAD</code>.</p>

<h3 id="diff">Diff</h3>
<p>Moreover, you can view at any time a diff between the current head (currently checked out commit / branch) and the local changes made after that.
<code class="language-plaintext highlighter-rouge">git diff</code> or <code class="language-plaintext highlighter-rouge">git diff --cached</code> for staged changes.</p>

<h3 id="committing">Committing</h3>
<p>To save progress on our changes into the repository, we will create commits. This assures our changes are safe and can be retrieved later if needed.
<code class="language-plaintext highlighter-rouge">git commit -m “Message”</code>
This will create a new commit on the current branch with the message included and containing all the content from the staging area.
A good practice we encourage is to make small commits where we change only a few files and that has a single reason for change.</p>

<h3 id="checkout">Checkout</h3>
<p>You can always checkout any commit (aka get the repo files in the state they were at that commit): 
<code class="language-plaintext highlighter-rouge">git checkout &lt;COMMIT_HASH&gt;</code>
Note that checkout will result in all the files tracked by git being replaced with their version from the commit you are checking out. If you have local changes, you will need to do something with them (like commit), before you can checkout a different commit.</p>

<h3 id="log">Log</h3>
<p>To inspect the current git history using the command line, the simplest option is to use: 
<code class="language-plaintext highlighter-rouge">git log</code> or 
<code class="language-plaintext highlighter-rouge">git log --all --decorate --oneline --graph</code>
Or you can just use a git client with UI where we can visually inspect commits, branches …</p>

<h3 id="branching">Branching</h3>
<p>Remember, branching is useful to support multiple lines of development. A good practice is to create a branch for each line of development:</p>
<ul>
  <li>For each feature or partial feature</li>
  <li>For each bug or fix</li>
  <li>For each refactoring</li>
  <li>For each idea you try out
The big advantage is we can seamlessly switch from one branch to another and come back.
Using git branches allows us to:</li>
  <li>work on a feature</li>
  <li>then create a different branch for a bug fix we need to solve now</li>
  <li>then switch to another branch to review a colleague’s work</li>
  <li>and return to the branch for our feature
with little to no cost.</li>
</ul>

<p>If we have a repository created using a git hosting service like GitHub, it will have a <code class="language-plaintext highlighter-rouge">main</code> branch by default.
You can create as many other branches as you want without extra costs to the repo, as you know, branches are just names given to particular commits.
You can create a branch using 
<code class="language-plaintext highlighter-rouge">git branch &lt;BRANCH_NAME&gt;</code>
You can list all the existing branches using <code class="language-plaintext highlighter-rouge">git branch</code> (add <code class="language-plaintext highlighter-rouge">-v</code> for extra info)</p>

<p>Git allows and encourages you to have multiple local branches that can be entirely independent of each other.</p>

<p><img src="/assets/git/git-feature-branches.png" alt="git branches" /></p>

<p>You can switch between branches using 
<code class="language-plaintext highlighter-rouge">git checkout &lt;BRANCH_NAME&gt;</code>
This is very fast.
After you’re done with the work for a feature / bug / experiment, you can decide to share this branch with others or just discard it.</p>

<h3 id="merge">Merge</h3>
<p>Merging is Git’s way of putting a forked history back together again. The <code class="language-plaintext highlighter-rouge">git merge</code> command lets you take the independent lines of development and integrate them into a single branch.</p>

<p><img src="/assets/git/git-diverging.png" alt="git merge" /></p>

<p>So from 2 different lines of development, we can use git merge to combine them into a single branch, usually we develop on a feature / bug branch and then merge back to our default branch - in this case <code class="language-plaintext highlighter-rouge">main</code>.
Merge is important because from the time we start a branch from <code class="language-plaintext highlighter-rouge">main</code> until we integrate back to it, other branches might be integrated as well, so we have to combine all these changes together.
Sometimes, if the different lines of development change the same files, at merge we will see conflicts (these cannot be automatically resolved by git) that we must resolve on our own.</p>

<p><img src="/assets/git/git-merge.png" alt="git merge" /></p>

<h3 id="local-vs-remote">Local vs remote</h3>
<p>All these operations like initializing an empty repository, creating commits, creating or switching branches and even merging branches are local operations, and they don’t require a connection with a git service.</p>

<p>But we work in teams, so we usually store the git repositories on a service like GitHub, which means this is the central repository where everyone gets the latest changes from and where they upload their changes.</p>

<p>Git is designed to give each developer an entirely isolated development environment. This means that information is not automatically passed back and forth between repositories. Instead, developers need to manually pull upstream commits into their local repository or manually push their local commits back up to the central repository.</p>

<h3 id="remotes">Remotes</h3>
<p>So, a git remote is an external location that has a copy of the same repository we have locally. We can use git commands to pull changes from this remote or to push our changes. And using a git interface, we can compare the local state of the repo to the remote ones.</p>

<p>We can inspect the remotes on each local repository using 
<code class="language-plaintext highlighter-rouge">git remote –v</code>
If we have just a local repository (created using git init), we will have no remotes here.</p>

<p>If we have cloned the repository from another location, we will usually have one remote called origin.</p>

<p>NOTE: we can add / remove / edit these remotes and have more than 1 at a time.</p>

<h3 id="remote-branches">Remote branches</h3>
<p>As soon as we have a remote set up, git can access the branches from that remote.
For example, using <code class="language-plaintext highlighter-rouge">git branch -va</code> will show all the branches, local and remote.</p>

<h3 id="fetching-changes-to-remote-branches">Fetching changes to remote branches</h3>
<p>The <code class="language-plaintext highlighter-rouge">git fetch</code> command downloads commits, files, and branches from a remote repository into your local repo. Fetching is what you do when you want to see what everybody else has been working on.
But this is only informative, no changes will be applied to our local branches.</p>

<h3 id="pulling">Pulling</h3>
<p>The <code class="language-plaintext highlighter-rouge">git pull</code> command is used to fetch and download content from a remote repository and immediately update the local repository to match that content. Merging remote upstream changes into your local repository is a common task in Git-based collaboration workflows. The pull command is actually a combination of two other commands, fetch followed by merge.
<code class="language-plaintext highlighter-rouge">git pull = git fetch + git merge</code></p>

<p><img src="/assets/git/git-pull.png" alt="git pull" /></p>

<h3 id="pushing">Pushing</h3>
<p>The <code class="language-plaintext highlighter-rouge">git push</code> command is used to upload local repository content to a remote repository. Pushing is how you transfer commits from your local repository to a remote repo. It’s the counterpart to <code class="language-plaintext highlighter-rouge">git pull</code>, but whereas pull imports commits to local branches, pushing exports commits to remote branches.</p>

<p><img src="/assets/git/git-push.png" alt="git push" /></p>

<h3 id="pull-requests--merge-requests">Pull Requests / Merge Requests</h3>
<p>A Pull Request is a concept that exists only on GitHub (also called Merge Request on other services). From a git’s perspective, there are no pull requests.
These features exist on git hosting services like GitHub, and they make it easier for developers to collaborate.
Using a branch shared with other developers (this can be the <code class="language-plaintext highlighter-rouge">main</code> branch, a <code class="language-plaintext highlighter-rouge">develop</code> branch), you pull the latest changes so the <code class="language-plaintext highlighter-rouge">main</code> / <code class="language-plaintext highlighter-rouge">develop</code> branch is up-to-date.
Before making changes to it, you branch from it - creating a new local branch, then make some changes, push back the changes by creating a remote branch from your local branch. And now you want to integrate these changes back to the main / develop branch.
Usually, these branches are protected by GitHub, so you can’t push directly to them, so instead you express your intention of pulling your changes into the main / develop branch by creating a Pull Request.
The Pull Request object exists only on the GitHub service, your local git repository has no notion about PRs.
Other developers on your team can review your PR, comment, and request changes. When it’s approved, the PR can be merged using GitHub’s interface, which will result in a merge commit on the main / develop branch that merges the new branch you created back into its original branch. This is a regular git merge, only created by GitHub. So, you have to pull from the main / develop branch to get this.</p>

<h3 id="forks">Forks</h3>
<p>Services like GitHub have many features, among which is a very detailed and granular access control. A project’s admin can allow some users to read / fetch the repo’s contents but not push to it (read-only) while only a few have write / push permissions.
GitHub has public repositories that can be read by every user and private repositories that limit the users that can access them.
To facilitate collaboration between users, GitHub and other services have the option to Fork a repository. When a user forks a repository, he creates their own server-side copy of that repository. The difference is the user has full access to their fork repo.
So, they can create branches, delete branches, push and pull code.
Forks are really useful when you want to contribute to repos where you don’t have push permissions.
If you have forked a repository, you can track it locally via a new remote (besides the origin one pointing at the main repository).
GitHub and other services allow creating PRs on the main repository from branches pushed to forks. Once the team maintaining that repo approves the PR and merge it, your changes will be integrated into that central repo - just like any other merge operation.</p>

<h3 id="ignored-files">Ignored files</h3>
<p>Git will ignore files or folders that follow certain conditions of name or path.
These regex filters can be added in a <code class="language-plaintext highlighter-rouge">.gitignore</code> file contained in each repo and in a <code class="language-plaintext highlighter-rouge">~/.gitignore_global</code> file that exists under your Mac local account and affects all repositories. Make sure what you add to these files, as the files and folders matching these patterns will be entirely ignored by git.
While the <code class="language-plaintext highlighter-rouge">.gitignore</code> file is checked in the repo and will affect all the other repo copies, the <code class="language-plaintext highlighter-rouge">.gitignore_global</code> is local to your machine and this can make git behave differently on your machine than on others.</p>

<h2 id="recap">Recap</h2>

<p><img src="/assets/git/git-summary.png" alt="Git Summary" /></p>

<h2 id="recommendations">Recommendations</h2>
<p>Every team will have its preference. It’s up to you to decide, but here are our recommendations:</p>

<h3 id="commit-as-often-as-possible">Commit as often as possible</h3>
<p>We recommend you make small commits, as often as possible. Then commit should modify only a handful of files, and it should have one very specific reason / goal. Make sure you describe this reason in the commit message.</p>

<p>These commits will act like checkpoints you can go back to when things get messy.
Don’t rely on UNDO, or you’ll lose work. It’s similar to playing a video game, you want to save often, so you can continue from a safe state which is very close to the current one.</p>

<p>Moreover, consider these commits might be reverted if the change turns out to be temporary or inappropriate. So make your commits with this in mind.
It’s very hard to partially revert a large commit.</p>

<h3 id="write-good-commit-messages">Write good commit messages</h3>
<p>It’s essential to write descriptive and clear commit messages describing the intent of the changes, not the actual implementation. For example, it’s clear from the code that we are adding 2 new functions to a class. What is not clear is why we are doing it.
Git commit messages will serve as a documentation for all the changes made to the source code and the reasons for these changes.</p>

<h3 id="tag-releases">Tag releases</h3>
<p>It’s very useful to use tags to mark the commit representing each release you make, whether it’s internal or external. It will also add context to your repo, of all the releases you made.
And when a problem occurs in a previous release, you can checkout and inspect exactly the state of the code you used for that release.</p>

<h3 id="periodical-clean-up">Periodical clean up</h3>
<p>Make a habit of cleaning up git. Delete unused branches, both locally and from the remote repo.</p>

<h2 id="references">References</h2>
<ul>
  <li><a href="https://git-scm.com/">Git Documentation</a></li>
  <li><a href="https://git-scm.com/docs">Git Reference (all commands)</a></li>
  <li><a href="https://www.atlassian.com/git/tutorials">Git Tutorials and Training by Atlassian</a></li>
  <li><a href="https://education.github.com/git-cheat-sheet-education.pdf">Git Cheat Sheet by GitHub</a></li>
</ul>]]></content><author><name></name></author><category term="git" /><category term="source control" /><summary type="html"><![CDATA[Summary What is source control and how it works What is git and how it works The main git entities What are git hosting services The main git commands and flows]]></summary></entry><entry><title type="html">Advanced Static vs Dynamic libraries and frameworks on iOS (and macOS)</title><link href="https://bpoplauschi.github.io/2021/10/25/Advanced-static-vs-dynamic-libraries-and-frameworks.html" rel="alternate" type="text/html" title="Advanced Static vs Dynamic libraries and frameworks on iOS (and macOS)" /><published>2021-10-25T05:00:00+00:00</published><updated>2021-10-25T05:00:00+00:00</updated><id>https://bpoplauschi.github.io/2021/10/25/Advanced-static-vs-dynamic-libraries-and-frameworks</id><content type="html" xml:base="https://bpoplauschi.github.io/2021/10/25/Advanced-static-vs-dynamic-libraries-and-frameworks.html"><![CDATA[<p>When building apps on any platform (Apple platforms included), we have to deal with system frameworks, packaging our own code, using 3rd party code and many more. Many developers work with static and / or dynamic frameworks / libraries, but don’t fully understand them, and thus, can’t get the best out of them. So I decided to share my knowledge, hoping I can help clarify these notions.</p>

<p>Let’s take a quick look at how I structured this info:</p>

<ul>
  <li><em>Definitions: what is a library, what is a framework, what is linking, what do static and dynamic linking mean (Part 1)</em></li>
  <li><em>iOS and macOS linking differences (Part 1)</em></li>
  <li>Implications of using static vs dynamic on app binary size and launch time</li>
  <li>The most common ways to integrate 3rd party code and how static vs dynamic linking applies to them</li>
</ul>

<p>Before jumping in to the more advanced topics of dynamic vs static linking, make sure you know what’s the difference between a library and a framework, between a static framework and a dynamic one, what does the linker do, …
Read <a href="../../../2021/10/24/Intro-to-static-and-dynamic-libraries-frameworks.html">Part 1 - Introduction to static and dynamic, libraries and frameworks on iOS (and macOS)</a> before continuing.</p>

<h2 id="summary-of-static-vs-dynamic-linking">Summary of static vs dynamic linking</h2>

<table>
  <thead>
    <tr>
      <th>Type of linking and platform / Impact</th>
      <th>App Size</th>
      <th>App Launch Time</th>
      <th>Safety</th>
      <th>Independent deployment</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Static linking - iOS and macOS</td>
      <td>Small app size (per optimizations).</td>
      <td>Fastest (all the symbols are within the same module, no extra loading required).</td>
      <td>Safe (all symbols are resolved at build time).</td>
      <td>Not available</td>
    </tr>
    <tr>
      <td>Dynamic linking - iOS</td>
      <td>Largest (embedded modules, no compiler optimizations).</td>
      <td>Slowest</td>
      <td>Risky, as the dynamic modules can be omitted from the binary (if not configured correctly) =&gt; runtime crash.</td>
      <td>Not available</td>
    </tr>
    <tr>
      <td>Dynamic linking - macOS</td>
      <td>Smallest, if sharing the modules separately. Biggest, if the modules are embedded into the app.</td>
      <td>Slowest</td>
      <td>Risky, since the modules may not exist at runtime, or even have the wrong version =&gt; crash or undefined behavior.</td>
      <td>Possible, by installing the modules in a shared location.</td>
    </tr>
  </tbody>
</table>

<h3 id="app-size">App Size</h3>

<ul>
  <li><em>smallest app size when using the macOS dynamic linking + sharing your dynamic modules separately (instead of embedding them into the app)</em></li>
  <li>using static linking results in a smaller app size than using dynamic embedded modules (the compiler can optimise by excluding unused symbols)</li>
  <li>biggest app size: using dynamic linking + embedding the modules in the app (the compiler cannot optimize, all the symbols have to be included)</li>
</ul>

<h4 id="app-launch-time">App Launch Time</h4>

<ul>
  <li>statically linked modules are fastest to load (loading non-system dynamic frameworks is pretty expensive while system frameworks are optimized). When using static linking, all the symbols are within the same module, so the app start is fast.</li>
  <li>dynamically linked modules are slower to load, especially on iOS. 
Known issue: loading dynamic modules is expensive, especially at start time. Apple recommended in WWDC to use a max of 6 dynamic frameworks. See details in the iOS increased App Launch Time section below.</li>
  <li>I didn’t find any reference of a limit of dynamic frameworks for macOS apps, probably because Macs have better hardware and this is no longer an issue. But even here, static linking will probably result in a quicker app start.</li>
</ul>

<h3 id="safety-of-symbols-existing-at-runtime">Safety (of symbols existing at runtime)</h3>

<ul>
  <li>All the code linked statically is checked and copied at build time, so we have the guarantee it works. The client code can’t get out of sync with the library APIs.</li>
  <li>iOS - even if the modules used by the app are checked by the compiler, one can simply forget to embed them, resulting in a crash at runtime <code class="language-plaintext highlighter-rouge">Library not loaded ... Reason: image not found</code></li>
  <li>macOS + shared modules: since we relly on resolving dependencies at runtime, we add extra risks. The dependencies might not exist or, exist, but have a different version than we expect. Both situations could result in a crash.</li>
</ul>

<h3 id="independent-deployment">Independent deployment</h3>

<ul>
  <li>Static linking: everything is delivered in one app binary, so there’s no way to deploy just some dependencies / modules.</li>
  <li>iOS doesn’t allow independent deployment of libs / frameworks.</li>
  <li>macOS: if modules are installed at a shared location (like the system ones), there’s the posibility to deploy and update them independently of the apps using them.</li>
</ul>

<h2 id="when-to-use-dynamic-linking">When to use dynamic linking</h2>

<p>So if statically linked modules result in a smaller app size and are faster at loading, why would we want to use dynamically loaded modules?</p>

<p>Here are a few situations.</p>

<h3 id="sharing-libraries--frameworks-on-macos">Sharing libraries / frameworks on macOS</h3>

<p>When you want to share the same binary (library / framework) between multiple apps, you can install it in a shared location and use it as any other system dynamic module.</p>

<h3 id="multiple-static-modules-depending-on-the-same-module">Multiple static modules depending on the same module</h3>

<p>Let’s say you have a module (your own or 3rd party) named <code class="language-plaintext highlighter-rouge">Common</code> that is used by other modules in your app.
<code class="language-plaintext highlighter-rouge">FeatureA</code> -&gt; <code class="language-plaintext highlighter-rouge">Common</code> and <code class="language-plaintext highlighter-rouge">FeatureB</code> -&gt; <code class="language-plaintext highlighter-rouge">Common</code>.
If <code class="language-plaintext highlighter-rouge">FeatureA</code>, <code class="language-plaintext highlighter-rouge">FeatureB</code> and <code class="language-plaintext highlighter-rouge">Common</code> are static libraries / frameworks, you’ll see a warning at app runtime in the console <code class="language-plaintext highlighter-rouge">duplicate symbol MY_COMMON_SYMBOL in ... FeatureA and ... FeatureB</code>. This happens because when linking statically to <code class="language-plaintext highlighter-rouge">Common</code>, both <code class="language-plaintext highlighter-rouge">FeatureA</code> and <code class="language-plaintext highlighter-rouge">FeatureB</code> binaries will contain the symbols from <code class="language-plaintext highlighter-rouge">Common</code>. So at runtime, the loader will not know which one is should use.</p>

<p>In this case, unless you have other things to consider, making <code class="language-plaintext highlighter-rouge">Common</code> a dynamic module will solve the problem, as both <code class="language-plaintext highlighter-rouge">FeatureA</code> and <code class="language-plaintext highlighter-rouge">FeatureB</code> will just reference <code class="language-plaintext highlighter-rouge">Common</code>, expecting at runtime to find an implementations for its symbols.</p>

<h2 id="ios-increased-app-launch-time-when-using-many-dynamic-libs--frameworks">iOS increased App Launch Time when using many dynamic libs / frameworks</h2>

<p>I’ve mentioned using many 3rd party dynamic libraries / frameworks probably leads to an increased app launch time on iOS.</p>

<p>This was detailed in WWDC 2016 Session 406 - Optimizing App Startup Time (I can only find the transcript of that session on <a href="https://asciiwwdc.com/2016/sessions/406">asciiwwdc</a>). Apple explained how each dynamic module adds to the total app launch time and we should keep the number of dynamic modules to a max of 6.
See <a href="https://developer.apple.com/documentation/xcode/reducing-your-app-s-launch-time/">Apple’s Reducing Your App’s Launch Time article</a> that mentiones all of that, except for an exact number of dynamic frameworks (perhaps over time the 6 limit became harder to keep and, since hardwares evolved, the limit might have increased).</p>

<p>The matter is simple: just test it out. Older Xcode versions required adding <code class="language-plaintext highlighter-rouge">DYLD_PRINT_STATISTICS</code> to the ENV variables to print stats regarding the app launch time and how much each step took. See <a href="https://developer.apple.com/library/archive/documentation/DeveloperTools/Conceptual/DynamicLibraries/100-Articles/LoggingDynamicLoaderEvents.html">Apple’s Logging Dynamic Loader Events</a>.
Looks like this:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Total pre-main time:  95.07 milliseconds (100.0%)
         dylib loading time:  25.00 milliseconds (26.3%)
        rebase/binding time:  19.75 milliseconds (20.7%)
            ObjC setup time:   6.85 milliseconds (7.2%)
           initializer time:  43.45 milliseconds (45.7%)
           slowest intializers :
             libSystem.B.dylib :   8.43 milliseconds (8.8%)
   libBacktraceRecording.dylib :   9.00 milliseconds (9.4%)
    libMainThreadChecker.dylib :  22.05 milliseconds (23.1%)
</code></pre></div></div>

<p>Or you can use Instruments, as explained in <a href="https://developer.apple.com/documentation/xcode/reducing-your-app-s-launch-time/">Apple’s Reducing Your App’s Launch Time article</a>.</p>

<p>Please consider there are 2 types of app starts <em>Cold App Start</em> and <em>Warm App Start</em>. 
A cold start is when you app starts for the 1st time (after a phone reboot) and is usually the slowest start. 
After that, even if you close the app, the system will cache some of the memory footprint (in case you closed the app by mistake). The next time you start the app will be a faster, warm start.
So to measure reliably, measure your app launch after a phone reboot (cold start).</p>

<p>If you find your app is taking a long time starting (Apple recommended 500 miliseconds for a seamless user experience), take a look at what is holding your app from launching. It can be many things, as executing some code on the <code class="language-plaintext highlighter-rouge">AppDelegate</code> or <code class="language-plaintext highlighter-rouge">SceneDelegate</code> methods, having a huge Launch storyboard, … 
If the problem lies with <code class="language-plaintext highlighter-rouge">dylib loading time</code>, you can look into changing some dynamic libraries / frameworks to static ones.</p>

<p>Should you want to dig deeper into this issue, there’s a very good thread on a GitHub open source app called Eigen by Artsy: https://github.com/artsy/eigen/issues/586</p>

<h2 id="static--dynamic-with-different-integrations-techniques">Static / dynamic with different integrations techniques</h2>

<p>Since nowadays many projects have a lot of 3rd party dependencies, let’s look at how these dependency managers work and how we can control their linking related behavior.</p>

<h3 id="own-targets-or-projects-linked-directly">Own targets or projects linked directly</h3>

<p>If the targets are in your repo or in other repos, but are linked to your project, you can go in and change the way they are built and linked through Build Settings.</p>

<p>You just need to change the value of the <code class="language-plaintext highlighter-rouge">MACH_O_TYPE</code> Build Setting between Static Library (<code class="language-plaintext highlighter-rouge">staticlib</code>) and Dynamic Library (<code class="language-plaintext highlighter-rouge">mh_dylib</code>).</p>

<p>To change between a library and a framework, you need to change the type of Product the target outputs (not sure how to do that from settings, but I find it easiest to just create a new Framework target and moving everything inside it).</p>

<p><img src="/assets/Mach-O Type.png" alt="Mach-O Type" /></p>

<h3 id="cocoapods">CocoaPods</h3>

<p>By default, CocoaPods (no mention of <code class="language-plaintext highlighter-rouge">use_frameworks!</code>) will build and link all the dependencies as static libraries.</p>

<p>If we add <code class="language-plaintext highlighter-rouge">use_frameworks!</code> to our Podfile, CP will instead build and link the dependencies as dynamic frameworks.</p>

<p>We can use <code class="language-plaintext highlighter-rouge">use_frameworks! :linkage =&gt; :static</code> to make CP build and link dependencies as static frameworks.</p>

<p>See https://guides.cocoapods.org/syntax/podfile.html#use_frameworks_bang.</p>

<p>NOTE: of course, all these apply to dependencies that CocoaPods builds from sources. If you are referencing a pod that is precompiled, there is no way for CocoaPods to change how that pod is packaged. Most packages distributed as precompiled binaries will be static libraries or static frameworks.</p>

<h3 id="swift-package-manager">Swift Package Manager</h3>

<p>SPM does not allow any control over how the dependencies are build and linked - they are all static libraries.
You can, however, specify how to build your own packages via <code class="language-plaintext highlighter-rouge">Package.swift</code> where you can specify <code class="language-plaintext highlighter-rouge">type: .dynamic</code>, but of course, this works only if you are the maintainer of that package.</p>

<h3 id="carthage">Carthage</h3>

<p>By default, <a href="https://github.com/Carthage/Carthage#supporting-carthage-for-your-framework">Carthage uses dynamic frameworks to build your dependencies</a>, but there is an <a href="https://github.com/Carthage/Carthage#build-static-frameworks-to-speed-up-your-apps-launch-times">option to change them to be built and linked statically</a>.</p>

<h2 id="conclusion">Conclusion</h2>

<p>As you might have deduced already, there’s no silver bullet and you have to choose what applies best to each situation. What is important is that you understand the impact your decision has.</p>

<p>Make sure to check out <a href="https://www.youtube.com/watch?v=IqsKGyklmL0">Differences in Dynamic &amp; Static Frameworks/Libraries by EssentialDeveloper</a>, that does a great job going through some real examples and explaining what each setting does / changes.</p>]]></content><author><name></name></author><category term="static" /><category term="dynamic" /><category term="framework" /><category term="library" /><category term="linker" /><category term="iOS" /><category term="macOS" /><category term="CocoaPods" /><category term="Carthage" /><category term="SPM" /><summary type="html"><![CDATA[When building apps on any platform (Apple platforms included), we have to deal with system frameworks, packaging our own code, using 3rd party code and many more. Many developers work with static and / or dynamic frameworks / libraries, but don’t fully understand them, and thus, can’t get the best out of them. So I decided to share my knowledge, hoping I can help clarify these notions.]]></summary></entry><entry><title type="html">Introduction to Static vs Dynamic libraries and frameworks on iOS (and macOS)</title><link href="https://bpoplauschi.github.io/2021/10/24/Intro-to-static-and-dynamic-libraries-frameworks.html" rel="alternate" type="text/html" title="Introduction to Static vs Dynamic libraries and frameworks on iOS (and macOS)" /><published>2021-10-24T05:00:00+00:00</published><updated>2021-10-24T05:00:00+00:00</updated><id>https://bpoplauschi.github.io/2021/10/24/Intro-to-static-and-dynamic-libraries-frameworks</id><content type="html" xml:base="https://bpoplauschi.github.io/2021/10/24/Intro-to-static-and-dynamic-libraries-frameworks.html"><![CDATA[<h2 id="introduction">Introduction</h2>

<p>When building apps on any platform (Apple platforms included), we have to deal with system frameworks, packaging our own code, using 3rd party code and many more. Many developers work with static and / or dynamic frameworks / libraries, but don’t fully understand them, and thus, can’t get the best out of them. So I decided to share my knowledge, hoping I can help clarify these notions.</p>

<p>Let’s take a quick look at how I structured this info:</p>

<ul>
  <li>Definitions: what is a library, what is a framework, what is linking, what do static and dynamic linking mean</li>
  <li>iOS and macOS linking differences</li>
  <li><em>Implications of using static vs dynamic on app binary size and launch time (Part 2)</em></li>
  <li><em>The most common ways to integrate 3rd party code and how static vs dynamic linking applies to them (Part 2)</em></li>
</ul>

<p>Before diving in, let’s clear up the terminology we use: <strong>we will refer to libraries and frameworks from a point of view of packaging and linking</strong>.</p>

<p>Another angle of looking at library vs framework looks at flow control: <em>your code calls libraries, frameworks call your code (after registering with them).</em>
We don’t care much about this second interpretation for now.</p>

<h2 id="what-is-a-library">What is a library</h2>

<p><a href="https://en.wikipedia.org/wiki/Library_(computing)">A library</a> is a collection of non-volatile resources used by computer programs. This can include source code. 
Most of the libraries we see for macOS or iOS contain code (compiled for one or more architectures).
Libraries can be linked statically (called static libraries) or dynamically (dynamic libraries). We’ll look at what linking means in a few.</p>

<p>When trying to ship resources (like string files, images, …), iOS / macOS libraries are delivered together with bundles containing these resources.
I don’t know of a way to include resources in iOS / macOS libraries.</p>

<h3 id="examples">Examples</h3>

<p>Static libraries usually look like <code class="language-plaintext highlighter-rouge">lib*.a</code> files, for example: <code class="language-plaintext highlighter-rouge">libGoogleAnalytics.a </code> (you might have used this one).
Dynamic libraries use the <code class="language-plaintext highlighter-rouge">*.dylib</code> extension.</p>

<h2 id="what-is-the-cpu-architecture">What is the (CPU) architecture</h2>

<p>In the context of iOS / macOS compiled binaries, the architecture refers to the <a href="https://docs.elementscompiler.com/Platforms/Cocoa/CpuArchitectures/">CPU architecture</a>. We need to compile our binaries for all the different CPU architectures they will be used on.</p>

<p>Currently, macOS has support for two architectures:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">x86_64</code> the architecture of Intel’s 64-bit CPUs. It is the architecture for all Intel Macs shipped between 2005 and 2021.</li>
  <li><code class="language-plaintext highlighter-rouge">arm64</code> is the architecture used by newer Macs built on Apple Silicon (2020+).</li>
</ul>

<p>iOS simulators run on macOS, so they use the same architectures.</p>

<p>iOS supported more architectures over time:</p>

<ul>
  <li>Old iOS devices shipped before 2009 had <code class="language-plaintext highlighter-rouge">armv6</code> CPUs, which are no longer supported by current iOS SDKs.</li>
  <li><code class="language-plaintext highlighter-rouge">armv7</code> an older variation of the 32-bit ARM CPU, as used in the A5 and earlier.</li>
  <li><code class="language-plaintext highlighter-rouge">armv7s</code> being used in Apple’s A6 and A6X chips on iPhone 5, iPhone 5C and iPad 4</li>
  <li><code class="language-plaintext highlighter-rouge">arm64</code> is the current 64-bit ARM CPU architecture, as used since the iPhone 5S and later (SE, 6, 7, …), the iPad Air, Air 2 and Pro, with the A7 and later chips.</li>
</ul>

<p>You can see the architecture(s) set for an Xcode target by looking at Build Settings -&gt; Architectures (<code class="language-plaintext highlighter-rouge">ARCHS</code>). It’s preset by Xcode to <code class="language-plaintext highlighter-rouge">Standard Architectures</code> (on Xcode 12.5 and an iOS target, this resolves to <code class="language-plaintext highlighter-rouge">arm64 armv7</code>).</p>

<p><img src="/assets/xcode-architectures.png" alt="xcode-architectures" /></p>

<h2 id="what-is-a-framework">What is a framework</h2>

<p><a href="https://en.wikipedia.org/wiki/Software_framework">A framework</a> is a package that can contain resources such as precompiled code (libraries), string files, images, storyboards etc. (if it contains other frameworks, it’s called an <em>umbrella framework</em>).
Apple’s frameworks are organized into bundles (have a predefined folder structure on disk). They can be accessed via <code class="language-plaintext highlighter-rouge">Bundle</code> class from code and, unlike most bundle files, can be browsed in the file system (easy for developers to inspect the contents).</p>

<p>Check out <a href="https://developer.apple.com/library/archive/documentation/CoreFoundation/Conceptual/CFBundles/BundleTypes/BundleTypes.html#//apple_ref/doc/uid/10000123i-CH101-SW1">Apple’s Bundle Programming Guide</a>.</p>

<p><img src="/assets/framework-example.png" alt="framework-example" /></p>

<p><em>Frameworks</em> are also bundles ending with <code class="language-plaintext highlighter-rouge">.framework</code> extension. 
Note: With Xcode 11, Apple added <code class="language-plaintext highlighter-rouge">xcframework</code> extensions, also bundles with multiple architectures and platforms.</p>

<h3 id="static-framework">Static framework</h3>

<p>A framework that embeds a static library has to be linked statically, so we call it a static framework.</p>

<h3 id="dynamic-framework">Dynamic framework</h3>

<p>A framework that embeds a dynamic library has to be linked dynamically, so we call it a dynamic framework.</p>

<h3 id="umbrella-framework">Umbrella framework</h3>

<p>A framework embedding other frameworks inside. It is not officially supported on iOS and that is why it <strong>is not recommended</strong> for developers to create them <a href="https://developer.apple.com/library/archive/technotes/tn2435/_index.html#//apple_ref/doc/uid/DTS40017543-CH1-PROJ_CONFIG-APPS_WITH_DEPENDENCIES_BETWEEN_FRAMEWORKS">Official doc</a>.</p>

<h3 id="example">Example</h3>

<p>They all look like <code class="language-plaintext highlighter-rouge">*.framework</code> folders, for example: <code class="language-plaintext highlighter-rouge">FirebaseAnalytics.framework </code> (you might have used this one).</p>

<h2 id="linking">Linking</h2>

<p><a href="https://en.wikipedia.org/wiki/Linker_(computing)">A <strong>linker</strong> or <strong>link editor</strong></a> is a program that takes one or more object files (generated by a compiler or an assembler) and combines them into a single executable file, library file, or another “object” file.</p>

<p>Usually, the linking phase happens right after the compilation phase, and even if they are different and executed by separate components, we simplify by referring to both processes together as “compiling” or “building”.</p>

<p>If you look at a build log, you’ll see that a section like “Build target MyApp” contains several steps, one is probably “Compile Swift source files” and soon comes “Link MyApp” (if you expand the Link command, you’ll see a <code class="language-plaintext highlighter-rouge">Ld ...</code> long command).</p>

<h2 id="dynamic-linking">Dynamic linking</h2>

<p>Many OS environments allow dynamic linking, deferring the resolution of some undefined symbols until a program is run.
Shortly, dynamic linking means adding references from one module (your app) to another module (library / framework). This dependency will be provided and resolved at runtime.
This is the way most system frameworks work - when building your app with <code class="language-plaintext highlighter-rouge">UIKit</code>, the app binary references <code class="language-plaintext highlighter-rouge">UIKit</code>, but doesn’t include its symbols. The system “knows” a version of <code class="language-plaintext highlighter-rouge">UIKit</code> will be available at runtime (and uses <code class="language-plaintext highlighter-rouge">dyld</code> to load it). This version is shared by all apps and is delivered as part of the OS.</p>

<p>Of course, there is a possibility the referenced binary doesn’t exist on the system, so trying to resolve it will result in a crash.
I haven’t seen this happen on iOS or macOS, but people using Windows may remember the <code class="language-plaintext highlighter-rouge">msvcrt.dll was not found</code> crash, especially when playing games (an example of dynamic linking gone bad).</p>

<h2 id="static-linking">Static linking</h2>

<p>Static linking is the result of the linker copying all the module’s (library / framework) routines used by the app into the executable.
An advantage of static linking is the linker can determine which symbols are needed by the app and only include these (instead of all the symbols from the module).</p>

<h2 id="static-and-dynamic-linking-on-ios--macos">Static and dynamic linking on iOS / macOS</h2>

<p>Static linking on iOS / macOS is very similar to other platforms - the linker will copy all the symbols needed by a binary into that binary. This means copying all the symbols that your app needs from other (static) modules into your app binary.</p>

<h3 id="dynamic-linking-on-macos">Dynamic linking on macOS</h3>

<p>Dynamic linking on macOS is also similar to other platforms, where the OS has shared dynamic libraries / frameworks and users can install their own dynamic modules too and share them between apps.</p>

<h3 id="dynamic-linking-on-ios">Dynamic linking on iOS</h3>

<p>On iOS, all the system modules are linked dynamically. Examples: <code class="language-plaintext highlighter-rouge">Foundation</code>, <code class="language-plaintext highlighter-rouge">UIKit</code>, <code class="language-plaintext highlighter-rouge">CoreGraphics</code>, <code class="language-plaintext highlighter-rouge">libsqlite</code>, …</p>

<p>This means they are shared by all apps and each OS version has an embedded version of these modules.</p>

<p>What is different from other platforms is there is no way for a developer to install their dynamic modules in a shared location and use them from different apps. This is because apps run in a “Sandbox” and cannot install modules to other parts of the system.</p>

<p>The impact of this limitation is that you can use dynamic modules, but you have to embed them in your app’s binary.</p>

<h3 id="embed-modules-in-the-app-binary">Embed modules in the app binary</h3>

<p>By choosing to embed a module in your app (Target - General - Frameworks, Libraries, and Embedded Content), you enable the <code class="language-plaintext highlighter-rouge">Embed Frameworks</code> Build Phase that copies the modules into your app binary (the <code class="language-plaintext highlighter-rouge">.app</code> will contain a <code class="language-plaintext highlighter-rouge">Frameworks</code> folder with them).</p>

<p><img src="/assets/framework-embed.png" alt="framework-embed" /></p>

<h3 id="how-to-find-out-if-a-library--framework-3rd-party-is-static-or-dynamic">How to find out if a library / framework (3rd party) is static or dynamic</h3>

<p>If you are looking at a binary library / framework (perhaps it’s precompiled by a 3rd party) and want to know if it’s a static or dynamic binary, just use <code class="language-plaintext highlighter-rouge">file</code> command with the path to the binary file.
Example (static framework) - static binaries are usually marked with ar archive or similar.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>file FirebaseAnalytics.framework/FirebaseAnalytics 
FirebaseAnalytics.framework/FirebaseAnalytics: Mach-O universal binary with 2 architectures: [arm_v7:current ar archive] [arm64:current ar archive]
FirebaseAnalytics.framework/FirebaseAnalytics (for architecture armv7):	current ar archive
FirebaseAnalytics.framework/FirebaseAnalytics (for architecture arm64):	current ar archive
</code></pre></div></div>

<p>Example (dynamic framework) - usually mentioned dynamically linked</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>file SDWebImage.framework/SDWebImage              
SDWebImage.framework/SDWebImage: Mach-O universal binary with 2 architectures: [x86_64:Mach-O 64-bit dynamically linked shared library x86_64] [arm64:Mach-O 64-bit dynamically linked shared library arm64]
SDWebImage.framework/SDWebImage (for architecture x86_64):	Mach-O 64-bit dynamically linked shared library x86_64
SDWebImage.framework/SDWebImage (for architecture arm64):	Mach-O 64-bit dynamically linked shared library arm64
</code></pre></div></div>

<h2 id="final-thoughts">Final thoughts</h2>

<p>This should give you a better understanding on what libraries and frameworks are and how they are linked.
If you want to dive deeper, <a href="../../../2021/10/25/Advanced-static-vs-dynamic-libraries-and-frameworks.html">Part 2 of this article</a> deals with more advanced concepts like the impact on dynamic / static linking on performance, how dependency managers deal with these and more.</p>]]></content><author><name></name></author><category term="static" /><category term="dynamic" /><category term="framework" /><category term="library" /><category term="linker" /><category term="iOS" /><category term="macOS" /><summary type="html"><![CDATA[Introduction]]></summary></entry><entry><title type="html">Clean Architecture on iOS</title><link href="https://bpoplauschi.github.io/2021/09/21/Clean-Architecture-on-iOS.html" rel="alternate" type="text/html" title="Clean Architecture on iOS" /><published>2021-09-21T05:00:00+00:00</published><updated>2021-09-21T05:00:00+00:00</updated><id>https://bpoplauschi.github.io/2021/09/21/Clean-Architecture-on-iOS</id><content type="html" xml:base="https://bpoplauschi.github.io/2021/09/21/Clean-Architecture-on-iOS.html"><![CDATA[<p>This is a continuation of the <a href="../20/Clean-Code-on-iOS.html">Clean Code on iOS post</a>, going into the topic of Clean Architecture.</p>

<h2 id="1-traits-of-a-clean-architecture">1. Traits of a Clean architecture</h2>

<p>There are different variations of architectures that are considered clean, but they all have the following characteristics:</p>

<ul>
  <li>
    <p>Independent of frameworks</p>

    <blockquote>
      <p>The architecture does not depend on the existence of some library of feature-laden software. This allows you to use such frameworks as tools, rather than forcing you to cram your system into their limited constraints.</p>
    </blockquote>
  </li>
  <li>
    <p>Testable</p>

    <blockquote>
      <p>The business rules can be tested without the UI, database, web server, or any other external element.</p>
    </blockquote>
  </li>
  <li>
    <p>Independent of UI</p>

    <blockquote>
      <p>The UI can change easily, without changing the rest of the system. A web UI could be replaced with a console UI, for example, without changing the business rules.</p>
    </blockquote>
  </li>
  <li>
    <p>Independent of the database</p>

    <blockquote>
      <p>You can swap out Oracle or SQL Server for Mongo, BigTable, CouchDB, or something else. Your business rules are not bound to the database.</p>
    </blockquote>
  </li>
  <li>
    <p>Independent of any external agency</p>

    <blockquote>
      <p>In fact, your business rules don’t know anything at all about the interfaces to the outside world.</p>
    </blockquote>
  </li>
</ul>

<h2 id="2-onion-layer-diagram">2. Onion-layer diagram</h2>

<p><img src="/assets/clean-architecture.jpeg" alt="clean-architecture" /></p>

<ul>
  <li>Enterprise Business Rules represented by Entities
    <ul>
      <li>agnostic of app</li>
      <li>apply to the entire business domain</li>
      <li>have no dependencies</li>
    </ul>
  </li>
  <li>App Business Rules represented by Use Cases or Interactors
    <ul>
      <li>apply to the application domain</li>
      <li>can depend on Entities</li>
    </ul>
  </li>
  <li>Interface Adapters: Controllers, Presenters, Gateways, …
    <ul>
      <li>depend on Use cases / Interactors</li>
    </ul>
  </li>
  <li>Frameworks and drivers: Devices, DB, Web, UI, …
    <ul>
      <li>depend on the rest of the system</li>
    </ul>
  </li>
</ul>

<p>NOTE: The arrows (dependencies) always point inward, so the frameworks and drivers depend on the rest of the system, but nothing else depends on them.</p>

<h2 id="3-solid-principles">3. SOLID Principles</h2>

<h3 id="3a-single-responsibility-principle">3a. Single Responsibility Principle</h3>
<blockquote>
  <p>A module should have one, and only one, reason to change.</p>
</blockquote>

<p>can be rephrased as</p>

<blockquote>
  <p>A module should be responsible to one, and only one, user or stakeholder.</p>
</blockquote>

<p>The simplest definition of a module is a source file.</p>

<p>Why is SRP important:</p>

<ul>
  <li>leads to small components</li>
  <li>that are easy to read and composable</li>
  <li>avoid conflicts</li>
</ul>

<p>SRP is different than the lower level principle of refactoring large functions into smaller ones (aka a function should do one thing).</p>

<p>The best way to understand this principle is by lookign at the symptoms of violating it.</p>

<h4 id="symptom-1---accidental-duplication">Symptom 1 - Accidental Duplication</h4>

<p>Let’s imagine an <code class="language-plaintext highlighter-rouge">Employee</code> class with 3 methods: <code class="language-plaintext highlighter-rouge">calculatePay</code>, <code class="language-plaintext highlighter-rouge">reportHours</code> and <code class="language-plaintext highlighter-rouge">save</code>.
This class violates the SRP because those 3 methods are responsible for 3 very different actors:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">calculatePay</code> is specified by the accounting department, which reports to the CFO</li>
  <li><code class="language-plaintext highlighter-rouge">reportHours</code> is specified and used by the HR department, which reports to the COO</li>
  <li><code class="language-plaintext highlighter-rouge">save</code> is specified by the DBAs, who report to the CTO</li>
</ul>

<p>By putting the source code for these three methods into a single <code class="language-plaintext highlighter-rouge">Employee</code> class, the developers have coupled each of these actors to the others. This coupling can cause the actions of the CFO’s team to affect something that the COO’s team depends on.
Let’s assume the <code class="language-plaintext highlighter-rouge">calculatePay</code> function and the <code class="language-plaintext highlighter-rouge">reportHours</code> function share a common algorithm for calculating the non-overtime hours. The developers will naturally extract that common algorithm into a function <code class="language-plaintext highlighter-rouge">regularHours</code> called by both <code class="language-plaintext highlighter-rouge">calculatePay</code> and <code class="language-plaintext highlighter-rouge">reportHours</code>. When one team (for example the CFO’s team) needs to change the <code class="language-plaintext highlighter-rouge">regularHours</code> algorithm, they will affect (and possibly break) the reports the COO’s team is generating.</p>

<h4 id="symptom-2---merges">Symptom 2 - Merges</h4>

<p>Merges usually happen in source files that contain many different methods, especially likely if they are responsible for different actors.
For example, the CTO’s team of DBAs wanting to change the schema of the <code class="language-plaintext highlighter-rouge">Employee</code> table and the COO’s team of HR clerks want to change the hours report formatting. This means at least 2 developers will make changes to the same file at the same time, probably resulting in a conflict that requires a merge.</p>

<p>Merges are risky affairs, even if we now have tools that handle some cases, we will still end-up with having to resolve conflicts. Unless we really understand what the other team changes are, there’s a good chance we won’t resolve the conflicts properly and introduce issues.</p>

<h4 id="solutions">Solutions</h4>

<p>There are many different solutions to this problem. Each moves the functions into different classes.</p>

<p><img src="/assets/SRP_employee.png" alt="SRP" /></p>

<p>The simplest and most obvious one is to separate the data from the functions. So we create the <code class="language-plaintext highlighter-rouge">Employee Data</code>, <code class="language-plaintext highlighter-rouge">PayCalculator</code>, <code class="language-plaintext highlighter-rouge">HourReporter</code> and <code class="language-plaintext highlighter-rouge">EmployeeSaver</code> classes, now the last 3 classes that have encapsuled different pieces of logic are separated from each other.</p>

<p>The downside is that now developers need to instantiate and track all 3 classes. A common solution for this dilemma is to use the <code class="language-plaintext highlighter-rouge">Facade</code> pattern by creating an <code class="language-plaintext highlighter-rouge">EmployeeFacade</code> that will act as a proxy to each of the dedicated classes.</p>

<h3 id="3b-open--closed-principle">3b. Open / Closed Principle</h3>
<blockquote>
  <p>A system should be open for extension but closed for modification.</p>
</blockquote>

<p>OCP is interconnected with SRP and DIP. When we make sure each class has a single responsibility (SRP) and we make it depend on abstractions instead of concrete types (DIP), OCP quickly follows. Now it’s easy to create new implementations of the abstractions and inject them without having to change the initial class.</p>

<p>OCP is gained by following all the other principles.</p>

<p>Adding new features should be done by adding code / components and changing very little of the existing ones.</p>

<p>Why is OCP important:</p>

<ul>
  <li>makes the system changeable and testable</li>
  <li>keeps changes contained to one part of the system</li>
</ul>

<h4 id="example-1">Example 1</h4>

<p><img src="/assets/OCP_feedVC.png" alt="OCP" /></p>

<p>Classic example: we want a screen that displays a list of feed items.</p>

<p><code class="language-plaintext highlighter-rouge">FeedViewController</code> depends on an abstraction <code class="language-plaintext highlighter-rouge">FeedLoader</code>. We can have as many implementation as we want:</p>

<ul>
  <li>at first, mock with dummy data</li>
  <li>remote that fetches the data from the network</li>
  <li>local that loads from local storage</li>
  <li>even a composed remote with fallback on local variant</li>
</ul>

<p>We can compose the <code class="language-plaintext highlighter-rouge">FeedViewController</code> with any of them, while it remains closed for modifications, but open for future extensions.</p>

<h4 id="example-2---enums">Example 2 - Enums</h4>

<p>Enums break OCP because the client code needs to be updated on every change to the enum.
The <code class="language-plaintext highlighter-rouge">Router</code> code is coupled with the current enum cases and is also a dependency magnet, as it references 3 concrete types.</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">enum</span> <span class="kt">DeeplinkType</span> <span class="p">{</span>
    <span class="k">case</span> <span class="n">home</span>
    <span class="k">case</span> <span class="n">profile</span>
    <span class="k">case</span> <span class="n">settings</span>
<span class="p">}</span>

<span class="kd">protocol</span> <span class="kt">Deeplink</span> <span class="p">{</span>
    <span class="k">var</span> <span class="nv">type</span><span class="p">:</span> <span class="kt">DeeplinkType</span> <span class="p">{</span> <span class="k">get</span> <span class="p">}</span>
<span class="p">}</span>

<span class="kd">class</span> <span class="kt">SettingsDeeplink</span><span class="p">:</span> <span class="kt">Deeplink</span> <span class="p">{</span>
    <span class="k">let</span> <span class="nv">type</span><span class="p">:</span> <span class="kt">DeeplinkType</span> <span class="o">=</span> <span class="o">.</span><span class="n">settings</span>

    <span class="kd">func</span> <span class="nf">executeSettings</span><span class="p">()</span> <span class="p">{</span>
        <span class="c1">// Presents the Settings Screen</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="kd">class</span> <span class="kt">Router</span> <span class="p">{</span>
    <span class="kd">func</span> <span class="nf">execute</span><span class="p">(</span><span class="n">_</span> <span class="nv">deeplink</span><span class="p">:</span> <span class="kt">Deeplink</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">switch</span> <span class="n">deeplink</span><span class="o">.</span><span class="n">type</span> <span class="p">{</span>
        <span class="k">case</span> <span class="o">.</span><span class="nv">home</span><span class="p">:</span>
            <span class="p">(</span><span class="n">deeplink</span> <span class="k">as?</span> <span class="kt">HomeDeepLink</span><span class="p">)?</span><span class="o">.</span><span class="nf">executeHome</span><span class="p">()</span>
        <span class="k">case</span> <span class="o">.</span><span class="nv">profile</span><span class="p">:</span>
            <span class="p">(</span><span class="n">deeplink</span> <span class="k">as?</span> <span class="kt">ProfileDeepLink</span><span class="p">)?</span><span class="o">.</span><span class="nf">executeProfile</span><span class="p">()</span>
        <span class="k">case</span> <span class="o">.</span><span class="nv">settings</span><span class="p">:</span>
            <span class="p">(</span><span class="n">deeplink</span> <span class="k">as?</span> <span class="kt">SettingsDeeplink</span><span class="p">)?</span><span class="o">.</span><span class="nf">executeSettings</span><span class="p">()</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Using polymorphism makes the <code class="language-plaintext highlighter-rouge">Router</code> agnostic of which <code class="language-plaintext highlighter-rouge">Deeplink</code> type is it really handling.
<code class="language-plaintext highlighter-rouge">Router</code> is closed for modification but open for extension - we can easily add or remove <code class="language-plaintext highlighter-rouge">Deeplink</code> implementations without affecting any of the existing code.</p>

<h3 id="3c-liskov-substitution-principle">3c. Liskov Substitution Principle</h3>
<blockquote>
  <p>Derived classes must be substitutable for their base classes.</p>
</blockquote>

<p>Any of <code class="language-plaintext highlighter-rouge">MockFeedLoader</code>, <code class="language-plaintext highlighter-rouge">RemoteFeedLoader</code>, <code class="language-plaintext highlighter-rouge">LocalFeedLoader</code>, … can be used and <code class="language-plaintext highlighter-rouge">FeedViewController</code> must work just fine.</p>

<p>Another example: <code class="language-plaintext highlighter-rouge">UIPageViewController</code> or <code class="language-plaintext highlighter-rouge">UINavigationController</code> work with any APIs that require a <code class="language-plaintext highlighter-rouge">UIViewController</code> (because they subclass it).</p>

<p>Why is LSP important? It Allows composing the components in any way we want / need.</p>

<h3 id="3d-interface-segregation-principle">3d. Interface Segregation Principle</h3>
<blockquote>
  <p>Make fine grained interfaces that are client specific.</p>
</blockquote>

<p>Don’t make clients depend on details they don’t need!</p>

<p>Why is this principle important:</p>

<ul>
  <li>We end up with smaller interfaces which are composable</li>
  <li>Less code dependencies, especially when they are not needed</li>
</ul>

<p>A common violation of ISP is creating interfaces with many functions, some optional or unneeded by their clients.</p>

<p>One reason for wanting segregated interfaces is to avoid source code dependencies that are not needed (thus requiring more time to compile and the need to redeploy a bunch of modules on a very small change to just one of them).</p>

<h4 id="example">Example</h4>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">protocol</span> <span class="kt">GestureProtocol</span> <span class="p">{</span>
    <span class="kd">func</span> <span class="nf">didTap</span><span class="p">()</span>
    <span class="kd">func</span> <span class="nf">didDoubleTap</span><span class="p">()</span>
    <span class="kd">func</span> <span class="nf">didLongPress</span><span class="p">()</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Splitting a 3 methods <code class="language-plaintext highlighter-rouge">GestureProtocol</code> into 3 individual ones, thus allowing clients to conform to 1, 2 or all those protocols without having to add empty method implementations. Also, a class like <code class="language-plaintext highlighter-rouge">MyButton</code> can have different properties for each action type (i.e. a <code class="language-plaintext highlighter-rouge">tapHandler</code> property of type <code class="language-plaintext highlighter-rouge">TapProtocol</code> and a <code class="language-plaintext highlighter-rouge">doubleTapHandler</code> property of type <code class="language-plaintext highlighter-rouge">DoubleTapProtocol</code>).</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">protocol</span> <span class="kt">TapProtocol</span> <span class="p">{</span>
    <span class="kd">func</span> <span class="nf">didTap</span><span class="p">()</span>
<span class="p">}</span>

<span class="kd">protocol</span> <span class="kt">DoubleTapProtocol</span> <span class="p">{</span>
    <span class="kd">func</span> <span class="nf">didDoubleTap</span><span class="p">()</span>
<span class="p">}</span>

<span class="kd">protocol</span> <span class="kt">LongPressProtocol</span> <span class="p">{</span>
    <span class="kd">func</span> <span class="nf">didLongPress</span><span class="p">()</span>
<span class="p">}</span>

<span class="kd">class</span> <span class="kt">MyButton</span><span class="p">:</span> <span class="kt">UIButton</span> <span class="p">{}</span>

<span class="kd">extension</span> <span class="kt">MyButton</span><span class="p">:</span> <span class="kt">TapProtocol</span> <span class="p">{</span>
    <span class="kd">func</span> <span class="nf">didTap</span><span class="p">()</span> <span class="p">{</span> <span class="o">...</span> <span class="p">}</span>
<span class="p">}</span>

<span class="kd">extension</span> <span class="kt">MyButton</span><span class="p">:</span> <span class="kt">DoubleTapProtocol</span> <span class="p">{</span>
    <span class="kd">func</span> <span class="nf">didDoubleTap</span><span class="p">()</span> <span class="p">{</span> <span class="o">...</span> <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>We can implement those protocols in multiple classes or just one, but <code class="language-plaintext highlighter-rouge">MyButton</code> is agnostic of those details.</p>

<h4 id="counterexamples">Counterexamples</h4>

<p>Apple’s frameworks often break ISP by having protocols like <code class="language-plaintext highlighter-rouge">UITableViewDataSource</code> or <code class="language-plaintext highlighter-rouge">UITableViewDelegate</code> with many methods not needed by most of their clients.</p>

<p>Also, they mix together multiple concepts like data source, prealoading, styling, …</p>

<h3 id="3e-dependency-inversion-principle">3e. Dependency Inversion Principle</h3>
<blockquote>
  <p>Depend on abstractions, not on concretions.</p>
</blockquote>

<p>High-level modules should not depend on low-level modules both should depend on Abstractions. (Abstractions should not depend upon details. Details should depend upon abstractions).</p>

<p>We apply DIP to most of our dependencies, especially volatile ones.</p>

<p>Why is DIP important:</p>

<ul>
  <li>The system is easy to compose diferently</li>
  <li>Low coupling (as we are not bound to concrete types)</li>
</ul>

<p>There are always cases where we will need to depend on concrete types - can’t make everything into an abstraction. No problem, refactor later.</p>

<p>One very useful application of DIP is to protect our business code from (3rd party) frameworks. Instead of making our code depend on a framework, we create an abstraction and depend upon it. Then the framework will conform to that abstraction, thus inverting the dependency (Inversion of Control).</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">protocol</span> <span class="kt">FeedLoader</span> <span class="p">{</span>
    <span class="kd">typealias</span> <span class="kt">Items</span> <span class="o">=</span> <span class="p">[</span><span class="kt">FeedItem</span><span class="p">]</span>
    <span class="kd">typealias</span> <span class="kt">Result</span> <span class="o">=</span> <span class="kt">Swift</span><span class="o">.</span><span class="kt">Result</span><span class="o">&lt;</span><span class="kt">Items</span><span class="p">,</span> <span class="kt">Error</span><span class="o">&gt;</span>
    <span class="kd">func</span> <span class="nf">loadFeed</span><span class="p">(</span><span class="kd">@escaping</span> <span class="p">(</span><span class="kt">Result</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kt">Void</span><span class="p">)</span>
<span class="p">}</span>

<span class="kd">class</span> <span class="kt">FeedViewController</span><span class="p">:</span> <span class="kt">UIViewController</span> <span class="p">{</span>
    <span class="kd">private</span> <span class="k">let</span> <span class="nv">loader</span><span class="p">:</span> <span class="kt">FeedLoader</span>
    
    <span class="nf">init</span><span class="p">(</span><span class="nv">loader</span><span class="p">:</span> <span class="kt">FeedLoader</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">self</span><span class="o">.</span><span class="n">loader</span> <span class="o">=</span> <span class="n">loader</span>
    <span class="p">}</span>
    
    <span class="k">override</span> <span class="kd">func</span> <span class="nf">viewDidLoad</span><span class="p">()</span> <span class="p">{</span>
        <span class="k">super</span><span class="o">.</span><span class="nf">viewDidLoad</span><span class="p">()</span>
        <span class="o">...</span>
        <span class="k">let</span> <span class="nv">items</span> <span class="o">=</span> <span class="n">loader</span><span class="o">.</span><span class="nf">loadFeed</span><span class="p">()</span>
        <span class="o">...</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="c1">// URLSession based loader</span>
<span class="kd">class</span> <span class="kt">RemoteFeedLoader</span><span class="p">:</span> <span class="kt">FeedLoader</span> <span class="p">{</span>
    <span class="c1">// ...</span>
<span class="p">}</span>

<span class="c1">// or, even an Alamofire based loader</span>
<span class="kd">import</span> <span class="kt">Alamofire</span>
<span class="kd">extension</span> <span class="kt">SessionManager</span><span class="p">:</span> <span class="kt">FeedLoader</span> <span class="p">{</span>
    <span class="c1">// ...</span>
<span class="p">}</span>
</code></pre></div></div>

<h2 id="4-composition-over-inheritance">4. <a href="https://en.wikipedia.org/wiki/Composition_over_inheritance"><strong>Composition over inheritance</strong></a></h2>
<h4 id="inheritance">Inheritance</h4>

<p>Inheritance: “is a” relationship.</p>

<p>Inheritance is the highest form of coupling.</p>

<p>Inheritance breaks encapsulation (allows subclasses to access internal details).</p>

<p>The compilation time and run time for inheritance is bigger, because of virtual tables.</p>

<p>Inheritance is resolved at compile time.</p>

<h4 id="composition">Composition</h4>

<p>Composition: “has a” relationship.</p>

<p>Composition is resolved at runtime (you can compose your types differently depending on platform / environment / …).</p>

<p>To achieve low coupling, prefer composition.</p>

<p>This doesn not mean avoid polymorphism (which is a strong programming tool), but rather separate responsibilities into small entities that are composed, also keeping them clean of inherited behavior / interface.</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// inheritance</span>
<span class="kd">class</span> <span class="kt">Device</span> <span class="p">{</span>
    <span class="k">let</span> <span class="nv">name</span><span class="p">:</span> <span class="kt">String</span>
    <span class="k">let</span> <span class="nv">operatingSystem</span><span class="p">:</span> <span class="kt">String</span>
<span class="p">}</span>

<span class="kd">class</span> <span class="kt">Smartphone</span><span class="p">:</span> <span class="kt">Device</span> <span class="p">{}</span>
<span class="kd">class</span> <span class="kt">Computer</span><span class="p">:</span> <span class="kt">Device</span> <span class="p">{}</span>

<span class="c1">// composition</span>
<span class="kd">protocol</span> <span class="kt">SystemProtocol</span> <span class="p">{</span>
    <span class="k">var</span> <span class="nv">operatingSystem</span><span class="p">:</span> <span class="kt">String</span> <span class="p">{</span> <span class="k">get</span> <span class="p">}</span>
<span class="p">}</span>
<span class="kd">protocol</span> <span class="kt">Nameable</span> <span class="p">{</span>
    <span class="k">var</span> <span class="nv">name</span><span class="p">:</span> <span class="kt">String</span> <span class="p">{</span> <span class="k">get</span> <span class="p">}</span>
<span class="p">}</span>

<span class="kd">struct</span> <span class="kt">Smartphone</span><span class="p">:</span> <span class="kt">Nameable</span><span class="p">,</span> <span class="kt">SystemProtocol</span> <span class="p">{</span>
    <span class="k">var</span> <span class="nv">name</span><span class="p">:</span> <span class="kt">String</span>
    <span class="k">var</span> <span class="nv">operatingSystem</span><span class="p">:</span> <span class="kt">String</span>
<span class="p">}</span>
<span class="kd">struct</span> <span class="kt">Camera</span><span class="p">:</span> <span class="kt">Nameable</span> <span class="p">{</span>
    <span class="k">var</span> <span class="nv">name</span><span class="p">:</span> <span class="kt">String</span>
<span class="p">}</span>
</code></pre></div></div>

<h2 id="5-the-main-component-aka-composition-root">5. The Main component aka Composition Root</h2>

<p>In every system, there is at least one component that creates, coordinates, and oversees the others. We call this the Main Component or, it’s also known as the Composition Root pattern.</p>

<p>The Main component is the ultimate detail - the lowest-level policy. It’s the initial entry point of the sytem. Nothing, other than the operating system, depends on it.
It’s job is to create all the Factories, Strategies, and other global facilities, and then hand control over to the high-level abstract portions of the system.</p>

<p>You can have multiple Main components: one for each configuration, platform or target.</p>

<p>The Composition Root is made of many components (Factories, Adapters, Decorators, …).</p>

<p>Why is the Composition Root important?</p>

<ul>
  <li>It’s where we define how our system should operate (depending on the conditions)</li>
  <li>We can deal with low level concepts here (current configuration, platform, device vs simulator, target, …)</li>
</ul>

<h2 id="6-frameworks-are-just-details">6. Frameworks are just details</h2>

<p>As the Clean Architecture “onion layers” diagram shows, frameworks live at the outer boundary of the system because they are just details.
Clean systems should not depend on one or more frameworks becase:</p>

<ul>
  <li>coupling the business code with framework details makes it harder to write, read and test
    <ul>
      <li>just think about frameworks that ask you to subclass their classes</li>
    </ul>
  </li>
  <li>the frameworks often change with a different agenda than our project’s</li>
  <li>if the system is coupled with the frameworks, this change is very hard to do</li>
  <li>they should allow us to switch between one framework to another</li>
</ul>

<p>Examples:</p>

<ul>
  <li>you should be able to easily change your data storage from in memory, local file storage, <code class="language-plaintext highlighter-rouge">UserDefaults</code>, <code class="language-plaintext highlighter-rouge">Keychain</code>, <code class="language-plaintext highlighter-rouge">CoreData</code>, <code class="language-plaintext highlighter-rouge">SQLite</code>, <code class="language-plaintext highlighter-rouge">Realm</code>, … or a combination of them</li>
  <li>changing the UI of the app should be easy and require just changes to the UI layer: from <code class="language-plaintext highlighter-rouge">UIKit</code> to <code class="language-plaintext highlighter-rouge">SwiftUI</code>or even a simple Command-Line tool without UI</li>
  <li>functional / reactive frameworks (<code class="language-plaintext highlighter-rouge">Combine</code>, <code class="language-plaintext highlighter-rouge">RxSwift</code>, … ) should be interchangeable and decoupled from the business layers - used only in the <code class="language-plaintext highlighter-rouge">CompositionRoot</code> because of the way they offer out-of-the-box patterns for Adapters / Factories / …</li>
  <li>same for networking: <code class="language-plaintext highlighter-rouge">URLSession</code>, <code class="language-plaintext highlighter-rouge">Alamofire</code>, <code class="language-plaintext highlighter-rouge">AFNetworking</code>, <code class="language-plaintext highlighter-rouge">Moya</code>, …</li>
</ul>

<p>Postpone the decision about which framework / library to use for as much as possible - so you have as much info as possible.</p>

<p>You can use test doubles (mocks or stubs) and you have a low coupling with the actual framework.</p>

<h2 id="7-handling-many-3rd-party-dependencies">7. Handling many 3rd party dependencies</h2>
<p>It’s become very normal that iOS projects have a lot of dependencies, especially 3rd parties.</p>

<ul>
  <li>
    <p>We need a networking component, but not sure what we need from that component? No problem, just add a 3rd party.</p>
  </li>
  <li>
    <p>We want to do “analytics”? Sure, add a few more 3rd parties.</p>
  </li>
  <li>Here’s a cool utility belt library - add it!</li>
  <li>Need a draggable table view cell? Of course there’s a library for that.</li>
</ul>

<p>Before you know it, your project has a dozen of those dependencies, most likely through different dependency management systems (manual, git submodules, SPM, CocoaPods, Carthage), it takes a large amount of time to clone the project and build it.</p>

<p>A few problems with this approach:</p>

<ul>
  <li>you’re adding a lot of uncontrollable risks: each library has it’s own roadmap, hidden issues, …</li>
  <li>what do you do when a 3rd party project is abandoned or doesn’t fix the most outstanding issues you have?</li>
  <li>having so many dependencies + a lot of them are not designed for a modular and testable integration results in very hard to test code</li>
</ul>

<p>I recommend you:</p>

<ul>
  <li>limit the number as much as possible</li>
  <li>postpone the decision</li>
  <li>protect from them by inverting the dependencies and make the 3rd parties depend on your code.</li>
</ul>

<h2 id="8-ui-layer-patterns---a-classical-ios-debate">8. UI layer patterns - a classical iOS debate</h2>

<p><strong>MVC</strong>, <strong>MVVM</strong>, <strong>MVP</strong>, <strong>VIPER</strong> are just design patterns for the UI layer. 
They don’t solve the problem of who should handle many other responsibilities like: business rules, data access and storage, notifications, navigation and deeplinking, …
Evem though our community is constantly debating which pattern is best and new ones keep coming out, there’s hardly any evidence for it.
Indeed, certain patterns are better matches for specific constraints:</p>

<ul>
  <li>for example, MVC is better suited for <code class="language-plaintext highlighter-rouge">UIKit</code> components as they are already built around the <code class="language-plaintext highlighter-rouge">UIViewController</code> subtypes</li>
  <li>MVVM seems to fit better when working with <code class="language-plaintext highlighter-rouge">SwiftUI</code></li>
</ul>

<p><img src="/assets/mvc_again.jpg" alt="MVC" /></p>

<h3 id="8a-the-issue-of-massive-components">8a. The issue of massive components</h3>

<p><img src="/assets/MassiveViewControllers.jpeg" alt="MVC" /></p>

<p>But none of those patterns will protect us from the problem of Massive components. Massive View Controller can quickly become Massive View Model or Massive View Presenter. Clean architecture principles help us better separate our code into components and avoid this issue.</p>

<h2 id="9-cross-cutting-concerns">9. Cross-cutting concerns</h2>

<p>Examples: threading, logging, authentication, analytics, security …</p>

<p>Those concerns are usually spread through the codebase and they are duplicated most of the time.</p>

<h4 id="example---threading">Example - threading</h4>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="kt">MainQueueDispatchDecorator</span><span class="p">:</span> <span class="kt">FeedLoader</span> <span class="p">{</span>
    <span class="kd">private</span> <span class="k">let</span> <span class="nv">decoratee</span><span class="p">:</span> <span class="kt">FeedLoader</span>
    
    <span class="nf">init</span><span class="p">(</span><span class="nv">decoratee</span><span class="p">:</span> <span class="kt">FeedLoader</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">self</span><span class="o">.</span><span class="n">decoratee</span> <span class="o">=</span> <span class="n">decoratee</span>
    <span class="p">}</span>

    <span class="kd">func</span> <span class="nf">load</span><span class="p">(</span><span class="nv">completion</span><span class="p">:</span> <span class="kd">@escaping</span> <span class="p">(</span><span class="kt">FeedLoader</span><span class="o">.</span><span class="kt">Result</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kt">Void</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">decoratee</span><span class="o">.</span><span class="n">load</span> <span class="p">{</span> <span class="n">result</span> <span class="k">in</span>
            <span class="k">if</span> <span class="kt">Thread</span><span class="o">.</span><span class="n">isMainThread</span> <span class="p">{</span>
                <span class="nf">completion</span><span class="p">(</span><span class="n">result</span><span class="p">)</span>
            <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
                <span class="kt">DispatchQueue</span><span class="o">.</span><span class="n">main</span><span class="o">.</span><span class="k">async</span> <span class="p">{</span>
                    <span class="nf">completion</span><span class="p">(</span><span class="n">result</span><span class="p">)</span>
                <span class="p">}</span>
            <span class="p">}</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>When composing the <code class="language-plaintext highlighter-rouge">FeedViewController</code>, we can pass an instance of <code class="language-plaintext highlighter-rouge">MainQueueDispatchDecorator</code> as a <code class="language-plaintext highlighter-rouge">FeedLoader</code>, while keeping all the <code class="language-plaintext highlighter-rouge">FeedLoader</code> implementations clean of threading.</p>

<h4 id="example---analytics--logging">Example - analytics / logging</h4>

<p>Instead of having each <code class="language-plaintext highlighter-rouge">ViewModel</code> do analytics or logging, we can decorate the <code class="language-plaintext highlighter-rouge">ViewModel</code> with analytics / logging behavior, keeping it clean of this cross-cutting concern.</p>

<h2 id="10-references">10. References</h2>
<ul>
  <li><a href="https://iosacademy.essentialdeveloper.com/p/ios-lead-essentials/">iOS Lead Essentials program</a> - Online program meticulously thought out for iOS developers who want to become world-class senior developers and be part of the highest-paid iOS devs in the world. Focuses on key concepts like Swift, TDD, BDD, DDD, Clean Architecture, Design Patterns, Git, Automation, CI/CD, and Modular Design.</li>
  <li><a href="https://www.goodreads.com/book/show/10284614-the-clean-coder">The Clean Coder by Robert C. Martin</a></li>
  <li><a href="https://www.goodreads.com/en/book/show/44416307-dependency-injection-principles-practices-and-patterns">Dependency Injection: Principles, Practices, and Patterns by Mark Seemann and Steven van Deursen</a></li>
  <li><a href="https://www.goodreads.com/book/show/387190.Test_Driven_Development">Test Driven Development: By Example by Kent Beck</a></li>
  <li><a href="https://www.goodreads.com/book/show/44919.Working_Effectively_with_Legacy_Code">Working Effectively with Legacy Code by Michael C. Feathers</a></li>
  <li><a href="https://www.goodreads.com/book/show/85009.Design_Patterns">Design Patterns by Gamma, Johnson, Vlissides, Helm</a></li>
  <li><a href="https://www.goodreads.com/book/show/18043011-clean-architecture">Clean Architecture by Robert C. Martin</a></li>
  <li><a href="https://www.goodreads.com/book/show/6518085-pro-git">Pro Git by Scott Chacon</a></li>
</ul>]]></content><author><name></name></author><category term="SOLID" /><category term="Clean Architecture" /><summary type="html"><![CDATA[This is a continuation of the Clean Code on iOS post, going into the topic of Clean Architecture.]]></summary></entry><entry><title type="html">Clean Code on iOS</title><link href="https://bpoplauschi.github.io/2021/09/20/Clean-Code-on-iOS.html" rel="alternate" type="text/html" title="Clean Code on iOS" /><published>2021-09-20T05:00:00+00:00</published><updated>2021-09-20T05:00:00+00:00</updated><id>https://bpoplauschi.github.io/2021/09/20/Clean-Code-on-iOS</id><content type="html" xml:base="https://bpoplauschi.github.io/2021/09/20/Clean-Code-on-iOS.html"><![CDATA[<h2 id="why">Why</h2>

<p>I have been doing iOS development for many years and I worked on many projects (including some open source). I have seen many codebases become hard to manage and just unpleasant to work with.</p>

<p>A while back, I became passionate about the concepts of Clean Code and Clean Architecture, so I tried to apply them to my projects.</p>

<p>I learned a lot from Robert Martin’s books and from the <a href="https://iosacademy.essentialdeveloper.com/p/ios-lead-essentials/">iOS Lead Essentials program</a>.</p>

<p>Why Clean Code and Clean Architecture?</p>

<ul>
  <li>IMO, it’s a fundamental part of building great software</li>
  <li>It’s agnostic of platform, language, technology</li>
  <li>Has a great impact on the lifetime and maintainability of systems</li>
</ul>

<p>Here’s what I learned so far.</p>

<h2 id="1-hard-to-change-codebases">1. Hard to change codebases</h2>

<p>How many times did you see codebases that with time are getting harder and harder to maintain / change?</p>

<p>They come with legacy code (code without tests), many flavours of code, many patterns, multiple languages (Swift, ObjC and more), they have huge files, unused code and resources, and most of the time, have some parts that nobody touches (because the guy that worked on that has left the team and nobody known how to work with that).</p>

<p>It’s definitely not profitable for a company to own such a codebase, so the ones that need to be maintained over years usually get to a point where they need to be rebuilt from scratch.</p>

<p>The problem with that (besides the obvious) is, without changing our principles, the new codebase will soon have the same issues as the old one.</p>

<p><img src="/assets/onlyGodknows.jpeg" alt="only-god-knows" /></p>

<h2 id="2-what-is-software">2. What is Software</h2>

<blockquote>
  <p>“Software” is a compound word = “soft” (changeable) + “ware” (product).
The software must be changeable. It should be cheap and easy to make changes to the system.</p>
</blockquote>

<h2 id="3-changeable-software">3. Changeable software</h2>
<p>How do you get changeable software?
According to Robert Martin:</p>

<ul>
  <li>you keep it clean</li>
  <li>you better have a really good suite of tests</li>
</ul>

<h2 id="4-who-is-robert-c-martin">4. Who is Robert C Martin</h2>

<p><img src="/assets/RobertMartin.jpg" alt="Robert-Martin" /></p>

<p><strong>Robert Cecil Martin</strong> colloquially called “Uncle Bob” is an American software engineer, instructor, and best-selling author. He is most recognized for developing many software design principles and for being a founder of the influential <a href="https://en.wikipedia.org/wiki/Agile_Manifesto">Agile Manifesto</a>.</p>

<p>He’s had a substantial role in stating the SOLID principles.</p>

<p>He’s authored several books, among which The Clean Coder, Clean Code, Clean Architecture.</p>

<p>Robert Martin had a continuous quest for what Clean code is and to establish industry standards for Software Development.</p>

<p>Many of Robert Martin’s teachings are applied for iOS in detail in the <a href="https://iosacademy.essentialdeveloper.com/p/ios-lead-essentials/">iOS Lead Essentials program</a>.</p>

<h2 id="5-what-is-clean-code">5. What is clean code</h2>

<blockquote>
  <p><strong>Clean code is simple and direct. Clean code reads like well-written prose.</strong> Clean code never obscures the designer’s intent but rather is full of crisp abstractions and straightforward lines of control.
– Grady Booch author of Object Oriented Analysis and Design with Applications</p>
</blockquote>

<blockquote>
  <p><strong>Clean code always looks like it was written by someone who cares.</strong>
– Michael Feathers, author of Working Effectively with Legacy Code</p>
</blockquote>

<blockquote>
  <p>You know you are working on clean code when <strong>each routine you read turns out to be pretty much what you expected</strong> … 
– Ward Cunningham, coauthor of the Manifesto For Agile Software Development</p>
</blockquote>

<blockquote>
  <p>Indeed, <strong>the ratio of time spent reading versus writing is well over 10 to 1</strong>. <strong>We are constantly reading old code as part of the effort to write new code. …[Therefore,] making it easy to read makes it easier to write.</strong> 
– Robert C. Martin</p>
</blockquote>

<p><img src="/assets/clean-code-image.png" alt="clean-code-image" /></p>

<h2 id="6-principles-of-clean-code">6. Principles of clean code</h2>

<h3 id="6a-the-boy-scouts-rule">6a. The Boy Scouts rule</h3>

<p>Leave the campground cleaner than you found it.</p>

<p>With every change (commit), we make the codebase just a bit better: fix a warning, remove a todo or an obsolete comment, add a test, improve a name, split a component that is getting too big, …</p>

<h3 id="6b-kiss-keep-it-simple-stupid">6b. <a href="https://en.wikipedia.org/wiki/KISS_principle"><strong>KISS</strong></a>: Keep It Simple Stupid</h3>

<p>A design principle originating from the U.S. Navy that goes back to 1960 already.</p>

<p>It states that most systems should be kept as simple as possible.</p>

<p>In my opinion, the art of designing code lies in simplicity - the simpler and easier to read / change code is, the better it is designed.</p>

<h3 id="6c-dry-dont-repeat-yourself">6c. <a href="https://en.wikipedia.org/wiki/Don't_repeat_yourself"><strong>DRY</strong></a>: Don’t Repeat Yourself</h3>
<p>It states that every piece of code must have a single, unambiguous, authoritative representation within a system.</p>

<p>There’s a catch: duplication is usually the enemy, but similar (even identical code) doesn’t always mean duplication. We need to also look at the reasons to change.</p>

<p>Example: the representation of the API response (that changes when the API schema changes) and the business model that your core uses (that changes when the business requirements change). Even though they might start as duplicates, it’s good to have them separate so we can protect our business rules from API schema changes (otherwise on any change like that, we’ll have many changes to apply to other layers of the code).</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// model object representing a feed item</span>
<span class="kd">struct</span> <span class="kt">FeedItem</span> <span class="p">{</span>
    <span class="k">let</span> <span class="nv">title</span><span class="p">:</span> <span class="kt">String</span>
    <span class="k">let</span> <span class="nv">createdAt</span><span class="p">:</span> <span class="kt">Date</span>
<span class="p">}</span>

<span class="c1">// network response representation of the feed item</span>
<span class="kd">struct</span> <span class="kt">RemoteFeedItem</span><span class="p">:</span> <span class="kt">Decodable</span> <span class="p">{</span>
    <span class="k">let</span> <span class="nv">title</span><span class="p">:</span> <span class="kt">String</span>
    <span class="k">let</span> <span class="nv">created_at</span><span class="p">:</span> <span class="kt">String</span>
<span class="p">}</span>
</code></pre></div></div>

<h3 id="6d-keep-things-small">6d. Keep things small</h3>
<p>By things I mean all kinds of entities: functions, classes, interfaces (protocols), enums, structs, clojures, etc.
Small pieces of code are easier to write, maintain and, most importantly, read and understand.
There are guidelines used to increase readability about what those numbers should be: including max number of lines per function, per file, max characters per line and more.</p>

<p>Recommendations compiled by Robert Martin:</p>
<ul>
  <li>50 or less lines of code per file (on average)
    <ul>
      <li>keeping most files under 100 lines</li>
    </ul>
  </li>
  <li>30-40 or less characters per line
    <ul>
      <li>“It’s rude to make your readers scroll to the right”</li>
    </ul>
  </li>
  <li>how small should a function be?
    <ul>
      <li>It should do one thing</li>
      <li>like a few lines of code with 1 or a max of 2 levels of indentation</li>
    </ul>
  </li>
  <li>how many arguments should a function have?
    <ul>
      <li>Ideally 0</li>
      <li>1 and 2 are good</li>
      <li>from 3 arguments the function becomes a bit harder to understand and it might be doing too much</li>
    </ul>
  </li>
</ul>

<h3 id="6e-command-query-separation">6e. Command-Query Separation</h3>

<p>Side effects are changes the state of the system.</p>

<p>Functions with side effects (commands) usually come in pairs: <code class="language-plaintext highlighter-rouge">open</code> / <code class="language-plaintext highlighter-rouge">close</code>, <code class="language-plaintext highlighter-rouge">malloc</code> / <code class="language-plaintext highlighter-rouge">free</code>, <code class="language-plaintext highlighter-rouge">init</code> / <code class="language-plaintext highlighter-rouge">dealloc</code>, …</p>

<p>A command aka a function that returns void has side effects, otherwise it would do nothing. 
A query aka a function that returns a value should have no side effects.</p>

<p>Don’t create functions that return values and have side effects, they are very confusing.</p>

<h3 id="6f-prefer-exceptions-to-error-codes-or-optional-returns">6f. Prefer exceptions to error codes or optional returns</h3>
<p>We prefer exceptions to error codes because they are more explicit.</p>

<p>When dealing with <code class="language-plaintext highlighter-rouge">do</code> / <code class="language-plaintext highlighter-rouge">catch</code>, we should not add more logic in a function than the <code class="language-plaintext highlighter-rouge">do</code> / <code class="language-plaintext highlighter-rouge">catch</code> block, so that function does one thing: handle errors.</p>

<p>Recommendation: don’t use nested <code class="language-plaintext highlighter-rouge">do</code> / <code class="language-plaintext highlighter-rouge">catch</code>.</p>

<p>See in the following example where the <code class="language-plaintext highlighter-rouge">init</code> throws instead of returning an optional <code class="language-plaintext highlighter-rouge">CoreDataFeedStore</code> (which would say nothing about why the API failed).</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">final</span> <span class="kd">class</span> <span class="kt">CoreDataFeedStore</span> <span class="p">{</span>
    <span class="kd">private</span> <span class="kd">static</span> <span class="k">let</span> <span class="nv">modelName</span> <span class="o">=</span> <span class="s">"..."</span>
    <span class="kd">private</span> <span class="kd">static</span> <span class="k">let</span> <span class="nv">model</span><span class="p">:</span> <span class="kt">NSManagedObjectModel</span><span class="p">?</span> <span class="o">=</span> <span class="o">...</span>
    <span class="kd">private</span> <span class="k">let</span> <span class="nv">container</span><span class="p">:</span> <span class="kt">NSPersistentContainer</span>
    <span class="kd">private</span> <span class="k">let</span> <span class="nv">context</span><span class="p">:</span> <span class="kt">NSManagedObjectContext</span>

    <span class="kd">enum</span> <span class="kt">StoreError</span><span class="p">:</span> <span class="kt">Error</span> <span class="p">{</span>
        <span class="k">case</span> <span class="n">modelNotFound</span>
        <span class="k">case</span> <span class="nf">failedToLoadPersistentContainer</span><span class="p">(</span><span class="kt">Error</span><span class="p">)</span>
    <span class="p">}</span>

    <span class="kd">public</span> <span class="nf">init</span><span class="p">(</span><span class="nv">storeURL</span><span class="p">:</span> <span class="kt">URL</span><span class="p">)</span> <span class="k">throws</span> <span class="p">{</span>
        <span class="k">guard</span> <span class="k">let</span> <span class="nv">model</span> <span class="o">=</span> <span class="kt">CoreDataFeedStore</span><span class="o">.</span><span class="n">model</span> <span class="k">else</span> <span class="p">{</span>
            <span class="k">throw</span> <span class="kt">StoreError</span><span class="o">.</span><span class="n">modelNotFound</span>
        <span class="p">}</span>
        
        <span class="k">do</span> <span class="p">{</span>
            <span class="n">container</span> <span class="o">=</span> <span class="k">try</span> <span class="kt">NSPersistentContainer</span><span class="o">.</span><span class="nf">load</span><span class="p">(</span><span class="nv">name</span><span class="p">:</span> <span class="kt">CoreDataFeedStore</span><span class="o">.</span><span class="n">modelName</span><span class="p">,</span> <span class="nv">model</span><span class="p">:</span> <span class="n">model</span><span class="p">,</span> <span class="nv">url</span><span class="p">:</span> <span class="n">storeURL</span><span class="p">)</span>
            <span class="n">context</span> <span class="o">=</span> <span class="n">container</span><span class="o">.</span><span class="nf">newBackgroundContext</span><span class="p">()</span>
        <span class="p">}</span> <span class="k">catch</span> <span class="p">{</span>
            <span class="k">throw</span> <span class="kt">StoreError</span><span class="o">.</span><span class="nf">failedToLoadPersistentContainer</span><span class="p">(</span><span class="n">error</span><span class="p">)</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<h3 id="6g-proper-use-of-access-control-modifiers">6g. Proper use of access control modifiers</h3>

<p>Many projects avoid using access control modifiers and just go with the default one (which currently in Swift is <code class="language-plaintext highlighter-rouge">internal</code>), but properly using access control has its advantages:</p>

<ul>
  <li>first of all, they help us better express in code. When you see a type having <code class="language-plaintext highlighter-rouge">private</code>, <code class="language-plaintext highlighter-rouge">internal</code> and <code class="language-plaintext highlighter-rouge">public</code> properties / methods, it is very clear which ones were created to be used by outer layers and types and which are implementation details.</li>
  <li>testing our types through their public interface only (no use of <code class="language-plaintext highlighter-rouge">@testable import</code>) keeps the tests decoupled from the production code, allowing us to refactor the internal and private implementations without breaking the public contract</li>
  <li>it’s easier to spot entities that have too many responsibilities by looking at their <code class="language-plaintext highlighter-rouge">public</code> interface</li>
</ul>

<h2 id="7-choosing-good-names">7. Choosing good names</h2>
<p>Names are everywhere (files, directories, programs, classes, variables, arguments, …).
Because we do so much of it … we’d better do it well!</p>

<p>It is said that choosing good names is one of the most difficult tasks when writing code. 
Remember this is an iterative process and the names in your projects will evolve with time. 
Remember the Boy Scouts rule: leave the compound a cleaner then you found it.</p>

<p>The rules for naming recommended by Uncle Bob are based on Tim Ottinger’s Rules for Variable and Class Naming:</p>

<h3 id="7a-reveal-your-intent">7a. Reveal your intent</h3>
<ul>
  <li>a name that requires a comment does not reveal it’s intent: <code class="language-plaintext highlighter-rouge">var d: Int // elapsed time in days</code></li>
  <li>the name of a variable should tell us the significance of what that variable contains <code class="language-plaintext highlighter-rouge">var elapsedTimeInDays: Int</code></li>
</ul>

<h3 id="7b-use-consistency-when-naming-entities">7b. Use consistency when naming entities</h3>

<ul>
  <li>it’s confusing to see functions with get, retrieve, load, fetch, …</li>
</ul>

<h3 id="7c-rule-for-variable-names">7c. Rule for variable names</h3>
<p>“A variable name should be proportional to the size of the scope that contains it.”</p>

<h3 id="7d-short-scope">7d. Short scope</h3>
<ul>
  <li>if the scope is very small, like 1 line, a single letter name is fine
    <div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">switch</span> <span class="p">(</span><span class="n">lhs</span><span class="p">,</span> <span class="n">rhs</span><span class="p">)</span> <span class="p">{</span>
  <span class="k">case</span> <span class="p">(</span><span class="o">.</span><span class="nf">failure</span><span class="p">(</span><span class="n">l</span><span class="p">),</span> <span class="o">.</span><span class="nf">failure</span><span class="p">(</span><span class="n">r</span><span class="p">)):</span> <span class="k">return</span> <span class="n">l</span> <span class="o">==</span> <span class="n">r</span> <span class="c1">// one line scope, using single letter names</span>
<span class="p">}</span>
</code></pre></div>    </div>
  </li>
  <li>this is because the scope is limited, so you don’t need the name to remind you of anything, the (name of the) function that generated the value should be enough</li>
  <li>inside an if statement, so maybe a couple of lines of code, the variable names inside should be very short
    <div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span> <span class="k">let</span> <span class="nv">data</span> <span class="o">=</span> <span class="n">cacheData</span> <span class="p">{</span>
  <span class="k">let</span> <span class="nv">cache</span> <span class="o">=</span> <span class="k">try</span> <span class="n">decoder</span><span class="o">.</span><span class="nf">decode</span><span class="p">(</span><span class="kt">Cache</span><span class="o">.</span><span class="k">self</span><span class="p">,</span> <span class="nv">from</span><span class="p">:</span> <span class="n">data</span><span class="p">)</span> <span class="c1">// scope limited to the if, using one word names</span>
  <span class="nf">completion</span><span class="p">(</span><span class="n">cache</span><span class="p">)</span>
<span class="p">}</span>
</code></pre></div>    </div>
  </li>
  <li>inside a while loop, the variables should be very short</li>
  <li>if you have a function (maybe 4 lines long), the variables inside should be pretty short, maybe a bit longer than the previous ones, maybe a word would be good for an argument</li>
  <li>instance variables that live inside a class have a longer scope (the scope of the class) so it should be long-ish: 2 words maybe
    <div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">struct</span> <span class="kt">FeedItem</span> <span class="p">{</span>
  <span class="k">let</span> <span class="nv">name</span><span class="p">:</span> <span class="kt">String</span>
  <span class="k">let</span> <span class="nv">imageURL</span><span class="p">:</span> <span class="kt">URL</span>
<span class="p">}</span>
</code></pre></div>    </div>
  </li>
  <li>the arguments to a member function probably one word
    <div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">func</span> <span class="nf">save</span><span class="p">(</span><span class="n">_</span> <span class="nv">feed</span><span class="p">:</span> <span class="p">[</span><span class="kt">FeedItem</span><span class="p">],</span> <span class="nv">completion</span><span class="p">:</span> <span class="kd">@escaping</span> <span class="p">(</span><span class="kt">SaveResult</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kt">Void</span><span class="p">)</span>
</code></pre></div>    </div>
  </li>
</ul>

<h3 id="7e-large-scope">7e. Large scope</h3>
<ul>
  <li>long scopes need long names</li>
  <li>global variables have a huge scope, so they should probably be very long
    <div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// I don't think using global variables is a good practice, but as an exercise ...</span>
<span class="kd">public</span> <span class="k">let</span> <span class="nv">testsDefaultTimeoutInSeconds</span><span class="p">:</span> <span class="kt">Int</span> <span class="o">=</span> <span class="mi">1</span>
</code></pre></div>    </div>
  </li>
</ul>

<h3 id="7f-rule-for-function-names">7f. Rule for function names</h3>
<p>“The name of a function is inversely proportional to the size of the scope that contains it.”</p>
<ul>
  <li>as the scope gets larger, we want to shrink the name because it will be called a lot, from all over the place.</li>
  <li>also, if the function has a larger scope, it’s probably dealing with a high-level abstraction</li>
  <li>we would not want to call the <code class="language-plaintext highlighter-rouge">open()</code> function if the name was <code class="language-plaintext highlighter-rouge">openFileAndThrowExceptionIfNotFound()</code></li>
  <li>as the scope decreases, the names start to get longer</li>
  <li>the instance methods of a class will probably have slightly bigger names</li>
  <li>private functions called by public functions will have even longer names</li>
  <li>private functions called by private functions will have even longer names</li>
  <li>this rule can apply recursively, as you go deeper the names will get longer</li>
  <li>as you keep extracting functions, those get smaller and more precise, that you need more words to specify</li>
</ul>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">func</span> <span class="nf">purgeAllData</span><span class="p">()</span> <span class="p">{</span> <span class="o">...</span> <span class="p">}</span>

<span class="kd">public</span> <span class="kd">final</span> <span class="kd">class</span> <span class="kt">DataManager</span><span class="p">:</span> <span class="kt">DataManagerInterface</span> <span class="p">{</span>
    <span class="kd">public</span> <span class="kd">func</span> <span class="n">loadObject</span><span class="o">&lt;</span><span class="kt">T</span><span class="p">:</span> <span class="kt">Codable</span><span class="o">&gt;</span><span class="p">(</span><span class="n">from</span> <span class="nv">storageType</span><span class="p">:</span> <span class="kt">DataStorageType</span><span class="p">,</span> <span class="n">with</span> <span class="nv">key</span><span class="p">:</span> <span class="kt">String</span><span class="p">,</span> <span class="nv">completion</span><span class="p">:</span> <span class="kd">@escaping</span> <span class="p">(</span><span class="kt">Result</span><span class="o">&lt;</span><span class="kt">T</span><span class="p">,</span> <span class="kt">Error</span><span class="o">&gt;</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kt">Void</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">switch</span> <span class="n">storageType</span> <span class="p">{</span>
        <span class="k">case</span> <span class="o">.</span><span class="nv">secure</span><span class="p">:</span>
            <span class="nf">loadObjectFromKeychain</span><span class="p">(</span><span class="nv">for</span><span class="p">:</span> <span class="n">key</span><span class="p">,</span> <span class="nv">completion</span><span class="p">:</span> <span class="n">completion</span><span class="p">)</span>
        <span class="k">case</span> <span class="kd">let</span> <span class="o">.</span><span class="nf">disk</span><span class="p">(</span><span class="n">directory</span><span class="p">):</span>
            <span class="nf">loadObjectFromDisk</span><span class="p">(</span><span class="nv">in</span><span class="p">:</span> <span class="n">directory</span><span class="p">,</span> <span class="nv">with</span><span class="p">:</span> <span class="n">key</span><span class="p">,</span> <span class="nv">completion</span><span class="p">:</span> <span class="n">completion</span><span class="p">)</span>
        <span class="k">case</span> <span class="o">.</span><span class="nv">memory</span><span class="p">:</span>
            <span class="nf">loadObjectFromMemory</span><span class="p">(</span><span class="nv">with</span><span class="p">:</span> <span class="n">key</span><span class="p">,</span> <span class="nv">completion</span><span class="p">:</span> <span class="n">completion</span><span class="p">)</span>
        <span class="k">case</span> <span class="o">.</span><span class="nv">userDefaults</span><span class="p">:</span>
            <span class="nf">loadObjectFromUserDefaults</span><span class="p">(</span><span class="nv">with</span><span class="p">:</span> <span class="n">key</span><span class="p">,</span> <span class="nv">completion</span><span class="p">:</span> <span class="n">completion</span><span class="p">)</span>
        <span class="p">}</span>
    <span class="p">}</span>
  
    <span class="kd">private</span> <span class="kd">func</span> <span class="n">loadObjectFromKeychain</span><span class="o">&lt;</span><span class="kt">T</span><span class="p">:</span> <span class="kt">Codable</span><span class="o">&gt;</span><span class="p">(</span><span class="k">for</span> <span class="nv">key</span><span class="p">:</span> <span class="kt">String</span><span class="p">,</span> <span class="nv">completion</span><span class="p">:</span> <span class="kd">@escaping</span> <span class="p">(</span><span class="kt">Result</span><span class="o">&lt;</span><span class="kt">T</span><span class="p">,</span> <span class="kt">Error</span><span class="o">&gt;</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kt">Void</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">guard</span> <span class="nf">verifyKeychainStoreIsValid</span><span class="p">()</span> <span class="k">else</span> <span class="p">{</span> <span class="k">return</span> <span class="p">}</span>
        <span class="n">keychainStorage</span><span class="o">.</span><span class="nf">retrieve</span><span class="p">(</span><span class="nv">forKey</span><span class="p">:</span> <span class="n">key</span><span class="p">)</span> <span class="p">{</span> <span class="n">result</span> <span class="k">in</span>
            <span class="o">...</span>
        <span class="p">}</span>
    <span class="p">}</span>
  
    <span class="kd">private</span> <span class="kd">func</span> <span class="nf">verifyKeychainStoreIsValid</span><span class="p">()</span> <span class="o">-&gt;</span> <span class="kt">Bool</span> <span class="p">{</span> <span class="o">...</span> <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<h3 id="7g-rule-for-class-names">7g. Rule for class names</h3>
<p>“The name of a class is inversely proportional to the size of the scope that contains it.”</p>
<ul>
  <li>classes at the global scope have one word names</li>
  <li>derived classes have multiple word names</li>
  <li>inner classes have multiple word names</li>
  <li>as the scope shrinks, the name grows
    <div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">protocol</span> <span class="kt">Store</span> <span class="p">{}</span>
<span class="kd">protocol</span> <span class="kt">FeedStore</span><span class="p">:</span> <span class="kt">Store</span> <span class="p">{}</span>
<span class="kd">final</span> <span class="kd">class</span> <span class="kt">CodableFeedStore</span><span class="p">:</span> <span class="kt">FeedStore</span> <span class="p">{}</span>
<span class="kd">final</span> <span class="kd">class</span> <span class="kt">InMemoryFeedStore</span><span class="p">:</span> <span class="kt">FeedStore</span> <span class="p">{}</span>
</code></pre></div>    </div>
  </li>
</ul>

<h3 id="7h-code-example">7h. Code Example</h3>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="nc">List</span><span class="o">&lt;</span><span class="kt">int</span><span class="o">[]&gt;</span> <span class="nf">getThem</span><span class="o">()</span> <span class="o">{</span>
    <span class="nc">List</span><span class="o">&lt;</span><span class="kt">int</span><span class="o">[]&gt;</span> <span class="n">list1</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">ArrayList</span><span class="o">&lt;</span><span class="kt">int</span> <span class="o">[]&gt;();</span>
    <span class="k">for</span> <span class="o">(</span><span class="kt">int</span><span class="o">[]</span> <span class="n">x</span> <span class="o">:</span> <span class="n">theList</span><span class="o">)</span>
        <span class="k">if</span> <span class="o">(</span><span class="n">x</span><span class="o">[</span><span class="mi">0</span><span class="o">]</span> <span class="o">==</span> <span class="mi">4</span><span class="o">)</span>
            <span class="n">list1</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">x</span><span class="o">);</span>
    <span class="k">return</span> <span class="n">list1</span><span class="o">;</span>
<span class="o">}</span>
</code></pre></div></div>
<ul>
  <li>this code isn’t complicated</li>
  <li>but it’s not explicit. It reveals no intent</li>
  <li>the names do not explicitly reveal the context of the problem being solved</li>
</ul>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="nc">List</span><span class="o">&lt;</span><span class="kt">int</span><span class="o">[]&gt;</span> <span class="nf">getFlaggedCells</span><span class="o">()</span> <span class="o">{</span>
    <span class="nc">List</span><span class="o">&lt;</span><span class="kt">int</span><span class="o">[]&gt;</span> <span class="n">flaggedCells</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">ArrayList</span><span class="o">&lt;</span><span class="kt">int</span><span class="o">[]&gt;();</span>
    <span class="k">for</span> <span class="o">(</span><span class="kt">int</span><span class="o">[]</span> <span class="n">cell</span> <span class="o">:</span> <span class="n">gameBoard</span><span class="o">)</span>
        <span class="k">if</span> <span class="o">(</span><span class="n">cell</span><span class="o">[</span><span class="no">STATUS_VALUE</span><span class="o">]</span> <span class="o">==</span> <span class="no">FLAGGED</span><span class="o">)</span>
            <span class="n">flaggedCells</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">cell</span><span class="o">);</span>
    <span class="k">return</span> <span class="n">flaggedCells</span><span class="o">;</span>
<span class="o">}</span>
</code></pre></div></div>
<ul>
  <li>only the names have changed and the meaning is far clearer</li>
  <li>now we know the list represents the game board and the function gets all the cells from a list that have the status flagged</li>
  <li>a good naming system will tell you more than the context of the function</li>
</ul>

<h3 id="7i-disambiguate">7i. Disambiguate</h3>
<ul>
  <li>What’s the difference between the following?
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>XYZControllerForEfficientHandlingOfStrings
XYZControllerForEfficientStorageOfStrings
</code></pre></div>    </div>
  </li>
  <li>Would you pick the right one from a code completion list?</li>
  <li>And watch out for symbols that look alike
    <div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">int</span> <span class="n">a</span> <span class="o">=</span> <span class="mi">1</span><span class="o">;</span>
<span class="k">if</span> <span class="o">(</span><span class="no">O</span> <span class="o">==</span> <span class="n">l</span><span class="o">)</span>
  <span class="n">a</span> <span class="o">=</span> <span class="nc">Ol</span><span class="o">;</span>
<span class="k">else</span>
  <span class="n">l</span> <span class="o">=</span> <span class="mo">01</span><span class="o">;</span>
</code></pre></div>    </div>
  </li>
</ul>

<h3 id="7j-avoid-convenient-mispellings">7j. Avoid convenient mispellings</h3>
<ul>
  <li><code class="language-plaintext highlighter-rouge">klass</code> vs <code class="language-plaintext highlighter-rouge">aClass</code> or <code class="language-plaintext highlighter-rouge">theClass</code></li>
  <li>avoid situations where the code will break if a spelling error is fixed</li>
</ul>

<h3 id="7k-number-series">7k. Number series</h3>
<ul>
  <li>the opposite of intentional naming</li>
  <li>provide no clue into the author’s intent
    <div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">copyChars</span><span class="o">(</span><span class="kt">char</span> <span class="n">a1</span><span class="o">[],</span> <span class="kt">char</span> <span class="n">a2</span><span class="o">[])</span> <span class="o">{</span>
  <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">a1</span><span class="o">.</span><span class="na">length</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span>
      <span class="n">a2</span><span class="o">[</span><span class="n">i</span><span class="o">]</span> <span class="o">=</span> <span class="n">a1</span><span class="o">[</span><span class="n">i</span><span class="o">];</span>
  <span class="o">}</span>
<span class="o">}</span>
</code></pre></div>    </div>
  </li>
</ul>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">copyChars</span><span class="o">(</span><span class="kt">char</span> <span class="n">source</span><span class="o">[],</span> <span class="kt">char</span> <span class="n">destination</span><span class="o">[])</span> <span class="o">{</span>
    <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">source</span><span class="o">.</span><span class="na">length</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span>
        <span class="n">destination</span><span class="o">[</span><span class="n">i</span><span class="o">]</span> <span class="o">=</span> <span class="n">source</span><span class="o">[</span><span class="n">i</span><span class="o">];</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<h3 id="7l-noise-words">7l. Noise words</h3>
<ul>
  <li>suffixes
    <div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">var</span> <span class="nv">product</span><span class="p">:</span> <span class="kt">Product</span>
<span class="k">var</span> <span class="nv">pd</span><span class="p">:</span> <span class="kt">ProductData</span>
<span class="k">var</span> <span class="nv">pi</span><span class="p">:</span> <span class="kt">ProductInfo</span>
</code></pre></div>    </div>
  </li>
  <li>data is completly redundant</li>
  <li>what is the difference between <code class="language-plaintext highlighter-rouge">Product</code>, <code class="language-plaintext highlighter-rouge">ProductData</code> and <code class="language-plaintext highlighter-rouge">ProductInfo</code>? the names don’t tell the difference</li>
  <li>prefixes
    <div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">var</span> <span class="nv">aProduct</span><span class="p">:</span> <span class="kt">Product</span>
<span class="k">var</span> <span class="nv">theProduct</span><span class="p">:</span> <span class="kt">Product</span>
</code></pre></div>    </div>
  </li>
</ul>

<h3 id="7m-distinguish-names-meaningfully">7m. Distinguish names meaningfully</h3>
<ul>
  <li>how to know which function to call
    <div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">func</span> <span class="nf">getActiveAccount</span><span class="p">()</span> <span class="o">-&gt;</span> <span class="kt">Account</span>
<span class="kd">func</span> <span class="nf">getActiveAccounts</span><span class="p">()</span> <span class="o">-&gt;</span> <span class="p">[</span><span class="kt">Account</span><span class="p">]</span>
<span class="kd">func</span> <span class="nf">getActiveAccountInfo</span><span class="p">()</span> <span class="o">-&gt;</span> <span class="p">[</span><span class="kt">Account</span><span class="p">]</span>
</code></pre></div>    </div>
  </li>
</ul>

<h3 id="7n-make-sure-names-are-pronounceable">7n. Make sure names are pronounceable</h3>
<ul>
  <li>Imagine you have the variable <code class="language-plaintext highlighter-rouge">genymdhms</code> (Generation date, year, month, day, hour, minute and second) and you need talk about this variable calling it “gen why emm dee aich emm ess”.</li>
  <li>that should be renamed to <code class="language-plaintext highlighter-rouge">generationTimestamp</code></li>
</ul>

<h2 id="8-comments">8. Comments</h2>

<p>The purpose of comments is to explain code that cannot explain itself.</p>

<p>Nothing can be quite as helpful as a good comment. 
Nothing can be quite as obscure as a bad comment. 
Comments are not “pure good”.</p>

<p>The proper use of comments is: <strong>to compensate for our failure to express ourselves in code</strong>. 
Every use of a comment represents a failure. So don’t comment <em>first</em>. Try everything else, then comment as a <em>last resort</em>.</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// Check to see if the employee is eligible for full benefits</span>
<span class="k">if</span> <span class="p">((</span><span class="n">employee</span><span class="o">.</span><span class="n">flags</span> <span class="o">&amp;</span> <span class="kt">HOURLY_FLAG</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">)</span> <span class="o">&amp;&amp;</span> <span class="p">(</span><span class="n">employee</span><span class="o">.</span><span class="n">age</span> <span class="o">&gt;</span> <span class="mi">65</span><span class="p">)</span> <span class="p">{</span>
    <span class="c1">// ...</span>
<span class="p">}</span>
</code></pre></div></div>

<p>VS</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span> <span class="n">employee</span><span class="o">.</span><span class="nf">isEligibleForFullBenefits</span><span class="p">()</span> <span class="p">{</span>
    <span class="c1">// ...</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Acceptable comments: copyrights, informative comments, warning of consequences, documentation comments in public APIs</p>

<h3 id="8a-todos">8a. TODOs</h3>

<p><code class="language-plaintext highlighter-rouge">TODO</code>s are a nice IDE feature, but it’s recommended not to check them in, so fix them before, otherwise, they become <code class="language-plaintext highlighter-rouge">DONTDO</code>s</p>

<h3 id="8b-use-explanatory-code-instead-of-comments">8b. Use explanatory code instead of comments</h3>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// does the module from the global list &lt;mod&gt;</span>
<span class="c1">// depend on the subsystem we are part of?</span>
<span class="k">if</span> <span class="o">(</span><span class="n">smodule</span><span class="o">.</span><span class="na">getDependSubsystems</span><span class="o">().</span><span class="na">contains</span><span class="o">(</span><span class="n">subSysMod</span><span class="o">.</span><span class="na">getSubSystem</span><span class="o">()))</span> <span class="o">{</span>
    <span class="c1">// ...</span>
<span class="o">}</span>
</code></pre></div></div>

<p>extract variables to explain things</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">ArrayList</span><span class="o">&lt;</span><span class="nc">Module</span><span class="o">&gt;</span> <span class="n">moduleDependees</span> <span class="o">=</span> <span class="n">smodule</span><span class="o">.</span><span class="na">getDependSubsystems</span><span class="o">();</span>
<span class="nc">Module</span> <span class="n">ourSubSystem</span> <span class="o">=</span> <span class="n">subSysMod</span><span class="o">.</span><span class="na">getSubSystem</span><span class="o">();</span>
<span class="k">if</span> <span class="o">(</span><span class="n">moduleDependees</span><span class="o">.</span><span class="na">contains</span><span class="o">(</span><span class="n">ourSubSystem</span><span class="o">))</span> <span class="o">{</span>
    <span class="c1">// ...</span>
<span class="o">}</span>
</code></pre></div></div>

<h3 id="8c-commented-out-code">8c. Commented out code</h3>

<ul>
  <li>few practices are as odious.</li>
  <li>don’t do this!</li>
</ul>

<h2 id="9-references">9. References</h2>
<ul>
  <li><a href="https://iosacademy.essentialdeveloper.com/p/ios-lead-essentials/">iOS Lead Essentials program</a> - Online program meticulously thought out for iOS developers who want to become world-class senior developers and be part of the highest-paid iOS devs in the world. Focuses on key concepts like Swift, TDD, BDD, DDD, Clean Architecture, Design Patterns, Git, Automation, CI/CD, and Modular Design.</li>
  <li><a href="https://www.goodreads.com/book/show/10284614-the-clean-coder">The Clean Coder by Robert C. Martin</a></li>
  <li><a href="https://www.goodreads.com/book/show/3735293-clean-code">Clean Code by Robert C. Martin</a></li>
  <li><a href="https://www.goodreads.com/book/show/387190.Test_Driven_Development">Test Driven Development: By Example by Kent Beck</a></li>
  <li><a href="https://www.goodreads.com/book/show/44919.Working_Effectively_with_Legacy_Code">Working Effectively with Legacy Code by Michael C. Feathers</a></li>
  <li><a href="https://www.goodreads.com/book/show/85009.Design_Patterns">Design Patterns by Gamma, Johnson, Vlissides, Helm</a></li>
  <li><a href="https://www.goodreads.com/book/show/6518085-pro-git">Pro Git by Scott Chacon</a></li>
</ul>]]></content><author><name></name></author><category term="Clean Code" /><summary type="html"><![CDATA[Why]]></summary></entry><entry><title type="html">Professional iOS Development</title><link href="https://bpoplauschi.github.io/2021/08/06/Professional-iOS-Development.html" rel="alternate" type="text/html" title="Professional iOS Development" /><published>2021-08-06T12:00:00+00:00</published><updated>2021-08-06T12:00:00+00:00</updated><id>https://bpoplauschi.github.io/2021/08/06/Professional-iOS-Development</id><content type="html" xml:base="https://bpoplauschi.github.io/2021/08/06/Professional-iOS-Development.html"><![CDATA[<h1 id="professional-ios-development">Professional iOS Development</h1>

<p>What traits do professional developers possess, and how do they apply to the world of iOS and other Apple platforms?
What standards do you use for iOS development compared to other platforms?
I don’t know the full answer, but I know enough to start the conversation.
I’d like to have a talk about Clean code, Clean architecture and modular design, SOLID principles, automated testing, TDD, CI and CD, and more.</p>

<h2 id="about-robert-c-martin">About Robert C Martin</h2>

<blockquote>
  <p><strong>Robert Cecil Martin</strong>, colloquially called “Uncle Bob” is an American <a href="https://en.wikipedia.org/wiki/Software_engineer">software engineer</a>, instructor, and best-selling author. He is most recognised for developing many software design principles and for being a founder of the influential <a href="https://en.wikipedia.org/wiki/Agile_Manifesto">Agile Manifesto</a>.
Five of Martin’s principles have become known collectively as the SOLID principles. He is a proponent of software craftsmanship, agile software development, and test-driven development.</p>
</blockquote>

<p>He has authored a series of books on Clean Code and Architecture.</p>

<h2 id="what-makes-a-professional-developer">What makes a professional developer</h2>
<ul>
  <li>Robert Martin is on a continuous quest to answer this question and establish industry standards</li>
  <li>see The Clean Coder</li>
  <li>what makes a professional in other fields: medicine, research, sports? They adhere to clear work guidelines, have rules, ethics and committees that verify their output</li>
</ul>

<h2 id="professionalism-is-about-taking-responsibility">Professionalism is about taking responsibility</h2>
<ul>
  <li>Do no harm: don’t create bugs (almost impossible, but still…). Analogy: software systems are very complex and thus impossible to be bug-free. But the human body is also incredibly complex, but doctors still take the oath to do no harm</li>
  <li>QA should find nothing: delivering faulty code is just unprofessional</li>
  <li>You must know it works: automated tests</li>
  <li>Work ethic: your career is your responsibility (trainings, conferences, books, … and the time needed to learn)</li>
  <li>Know your field:
    <ul>
      <li>design patterns: GOF</li>
      <li>design principles: SOLID</li>
      <li>methods: XP, Scrum, Kanban, Waterfall, …</li>
      <li>disciplines: TDD, OOD, Structured programming, CI, Pair programming</li>
      <li>artifacts: UML, State Transition Diagrams and tables, flow charts, …</li>
    </ul>
  </li>
  <li>Practice</li>
  <li>Collaboration</li>
  <li>Mentoring</li>
  <li>Know your domain</li>
  <li>Humility</li>
</ul>

<h2 id="saying-no-and-saying-yes">Saying No and Saying Yes</h2>
<ul>
  <li>Professionals have the courage to say No to their managers, and they work hard to find creative ways to make Yes possible.</li>
  <li>Your manager is counting on you to defend your objectives as aggressively as they defend theirs. Both you and your manager need to get to the best possible outcome through negotiation.</li>
  <li>Professionals pursue and defend their objectives as aggressively as they can.</li>
  <li>Recognize lack of commitment words and phrases like “hope” and “Let’s see if we can get this done…”. A sincere commitment sounds like “I will do something… by this certain date…”</li>
  <li>Bring up blockers or red flags as soon as they come up — actively communicate.</li>
</ul>

<h2 id="coding">Coding</h2>
<ul>
  <li>Coding is an intellectually challenging and exhausting activity.</li>
  <li>If you are tired, worried, or distracted, do not code. Your code will have bugs or a bad structure.</li>
  <li>Spend personal time before work trying to resolve or mitigate personal issues or demands, so you can focus your mental energy on being a productive problem solver at work.</li>
  <li>Be prepared to be interrupted and help someone — it’s the professional thing to do.</li>
  <li>Ask for and ask to give help - be a mentor.</li>
</ul>

<h2 id="test-driven-development">Test-Driven Development</h2>
<ul>
  <li>Writing your tests first:</li>
  <li>Good tests function like good documentation.</li>
  <li>TDD is a discipline that enhances certainty, courage, defect reduction, documentation, and design.</li>
</ul>

<h2 id="practice-practice-practice">Practice, Practice, Practice</h2>
<ul>
  <li>When performance matters, professionals practice.</li>
  <li>All professionals practice their art by engaging in skill-sharpening exercises.</li>
  <li>Doing anything quickly requires practice. It’s not always wise to go fast, but sometimes it is better to do it as fast as possible and is highly productive.</li>
  <li>Practice coding outside of work by doing katas.</li>
  <li>Open source: Take on some pro bono work by contributing to an open-source project.</li>
</ul>

<h2 id="testing-strategies">Testing Strategies</h2>
<p>Every professional development team needs a good testing strategy, and we can start by following the “Test Pyramid”:
(image)</p>
<ul>
  <li>Unit tests</li>
  <li>Component tests</li>
  <li>Integration tests</li>
  <li>System tests</li>
  <li>Manual tests</li>
</ul>

<h2 id="time-management">Time Management</h2>
<ul>
  <li>What strategies can you use to ensure that you don’t waste time?</li>
  <li>Meetings are both necessary and huge time wasters. You do not have to attend every meeting — be careful about which ones you decline and those you choose to attend.</li>
  <li>Use tools like the Pomodoro Technique.</li>
  <li>Evaluate the priority of each task, disregarding personal fears and desires, and execute those tasks in priority order.</li>
</ul>

<h2 id="estimation">Estimation</h2>
<ul>
  <li>Estimation is one of the simplest, yet most frightening activities that software professionals face.</li>
  <li>Know the difference between estimates and commitments.</li>
  <li>A commitment is something you must achieve. An estimate is a guess.</li>
  <li>Learn methods to get better estimates like PERT, Fingers in the Air and Planning Poker</li>
  <li>Always include error bars with your estimates so that the business understands the uncertainty.</li>
  <li>Don’t make commitments unless you know you can achieve them.</li>
</ul>

<h2 id="stay-cool-under-pressure">Stay Cool Under Pressure</h2>
<ul>
  <li>The professional developer is calm and decisive under pressure.</li>
  <li>Under pressure? Be sure to manage your commitments, follow disciplines, keep code clean, communicate, and ask for help.</li>
  <li>Don’t succumb to the temptation to create a mess to move quickly.</li>
</ul>

<h2 id="collaborate">Collaborate</h2>
<ul>
  <li>Programming is all about working with people. It’s unprofessional to be a loner or a recluse on a team.</li>
  <li>Often, programmers have difficulty working closely with other programmers. That’s no excuse. Being a developer means working with people.</li>
  <li>Meet the needs - collaborate with your managers, business analysts, testers, and other team members to deeply understand the business goals.</li>
  <li>Pairing is a great way to share knowledge and the best way to review code.</li>
</ul>

<h2 id="get-aligned-with-your-teams">Get Aligned with Your Teams</h2>
<ul>
  <li>Strive to have a “gelled” team.</li>
  <li>A gelled team is one that forms relationships, collaborates, and learns each other’s quirks and strengths.</li>
  <li>Teams are harder to build than projects. It’s better to form persistent teams that move together from one project to the next and can take on more than one project at a time.</li>
</ul>

<h2 id="mentoring-apprenticeship-and-craftsmanship">Mentoring, Apprenticeship, and Craftsmanship</h2>
<ul>
  <li>The software development industry has gotten the idea that programmers are programmers, and that once you graduate you can code.</li>
  <li>Software apprenticeship is a three-step journey: starting from an apprentice and moving to journeyman before becoming a master.</li>
  <li>Be a craftsman - someone who works quickly, but without rushing, provides reasonable estimates and meets commitments. Know when to say No, but try hard to say Yes.</li>
  <li>If craftsmanship is your way of life, keep in mind that you cannot force other programmers to become craftsmen.</li>
</ul>

<h2 id="references">References</h2>
<ul>
  <li><a href="https://iosacademy.essentialdeveloper.com/p/ios-lead-essentials/">iOS Lead Essentials program</a> - Online program meticulously thought out for iOS developers who want to become world-class senior developers and be part of the highest-paid iOS devs in the world. Focuses on key concepts like Swift, TDD, BDD, DDD, Clean Architecture, Design Patterns, Git, Automation, CI/CD, and Modular Design.</li>
  <li><a href="https://www.goodreads.com/book/show/10284614-the-clean-coder">The Clean Coder by Robert C. Martin</a></li>
  <li><a href="https://www.goodreads.com/book/show/3735293-clean-code">Clean Code by Robert C. Martin</a></li>
  <li><a href="https://www.goodreads.com/en/book/show/44416307-dependency-injection-principles-practices-and-patterns">Dependency Injection: Principles, Practices, and Patterns by Mark Seemann and Steven van Deursen</a></li>
  <li><a href="https://www.goodreads.com/book/show/387190.Test_Driven_Development">Test Driven Development: By Example by Kent Beck</a></li>
  <li><a href="https://www.goodreads.com/book/show/44919.Working_Effectively_with_Legacy_Code">Working Effectively with Legacy Code by Michael C. Feathers</a></li>
  <li><a href="https://www.goodreads.com/book/show/85009.Design_Patterns">Design Patterns by Gamma, Johnson, Vlissides, Helm</a></li>
  <li><a href="https://www.goodreads.com/book/show/18043011-clean-architecture">Clean Architecture by Robert C. Martin</a></li>
  <li><a href="https://www.goodreads.com/book/show/6518085-pro-git">Pro Git by Scott Chacon</a></li>
</ul>]]></content><author><name></name></author><category term="Clean Code" /><category term="Clean Architecture" /><summary type="html"><![CDATA[Professional iOS Development]]></summary></entry><entry><title type="html">Clean Code - by Uncle Bob - part 4</title><link href="https://bpoplauschi.github.io/2021/02/10/Clean-Code-by-Uncle-Bob-part-4.html" rel="alternate" type="text/html" title="Clean Code - by Uncle Bob - part 4" /><published>2021-02-10T13:00:00+00:00</published><updated>2021-02-10T13:00:00+00:00</updated><id>https://bpoplauschi.github.io/2021/02/10/Clean-Code-by-Uncle-Bob-part-4</id><content type="html" xml:base="https://bpoplauschi.github.io/2021/02/10/Clean-Code-by-Uncle-Bob-part-4.html"><![CDATA[<p>One of my best sources for learning how to write clean code is the content from Robert C. Martin aka “Uncle Bob”. While studying his free “Clean Code - Uncle Bob / Lessons” on YouTube, I took notes and decided to share those notes, so others can benefit from them.</p>

<p>To be clear, all the content belongs to Robert C. Martin, I merely summarized the content and updated the code examples for Swift.</p>

<h2 id="uncle-bob-your-new-cto">Uncle Bob, your new CTO</h2>

<p>In this lesson, Robert Martin guides us through an imaginative exercise where he is the new CTO at a tech company.</p>

<p>He focuses on raising awareness, given the need to increase the level of criteria in code production. Pointing to the lack of preparation in most programmers, as one of the main reasons for the inefficiency in software development today.</p>

<p>Robert Martin proposes a series of Expectations, through which he hopes to instill in the programmers, the knowledge and desire to prosper towards a way of programming based on ethics and responsibility.</p>

<h3 id="1-we-will-not-ship-shit">1. We will not ship shit</h3>

<p>People now regularly download and use betas. :) Beta software means code that probably doesn’t work well / as expected. It definitely has bugs. Betas should be used only in limited cases.</p>

<p>Robert Martin’s expectation is that we only ship code <strong>we know it works</strong>. It should have the highest quality level you can deliver. It should be clean, tested, well organized. Everybody expects that.</p>

<p>Example: when you buy a car, you expect it to work, to have been properly tested and you are going to complain bitterly if even the smallest thing doesn’t work.</p>

<h3 id="2-we-will-always-be-ready">2. We will always be ready</h3>

<p>Agile = system is in a deployable / shippable state after every iteration / sprint.
The system is ready, even if it doesn’t have enough features to deploy (that is a business decision).
Ready to deploy = all the testing is done, all the documentation is done, the set of features is done.
If you are not deployable at the end of the sprint, you are not doing Agile.</p>

<p>Iteration length: ideally 1 week, acceptable 2 weeks.</p>

<h3 id="3-stable-productivity">3. Stable Productivity</h3>

<p>The longer the project goes, the slower you <strong>don’t</strong> get. You are able to produce features at the same rate even after a long time. Each added feature does not make the system harder and harder to maintain / change. 
The reason we slow down is because we make a mess. As the mess builds, we get slower.</p>

<p>Example from Robert Martin’s career: worked for a company where every estimate was 6+ months. The dev team’s cost of missing estimates was so high, they would not commit to anything under 6 months. Also, the system was highly coupled and you couldn’t even change a menu item’s name without affecting other areas.</p>

<h3 id="4-inexpensive-adaptability">4. Inexpensive Adaptability</h3>

<p>The software must be changeable. It should be cheap and easy to make changes to the system.</p>

<p>Put otherwise, the size of the change should be proportional to the scope of the change.</p>

<p>He expects us not to respond to a small client change with: “Oh God, that destroys our entire architecture” :)</p>

<blockquote>
  <p>“Software” is a compound word = “soft” (changeable) + “ware” (product).</p>
</blockquote>

<p>Software = changeable product. It was invented so our machines can be easily changeable.
If it’s hard to change, you have just reinvented Hardware.</p>

<p>How do you get changeable software?</p>
<ul>
  <li>you keep it clean</li>
  <li>you better have a really good suite of tests</li>
</ul>

<h3 id="5-continuous-improvement">5. Continuous Improvement</h3>

<p>The code should be getting better with time (even if most of the time, the code rots.)
The architecture of the system should be getting better with time.</p>

<h3 id="6-fearless-competence">6. Fearless Competence</h3>

<p>If your reaction to bad code is “if I change it, I will have to own it”, then that code will end up rotting.
You will change it from time to time, but with minimal changes to reduce the risk. You will not improve the system. No one will ever clean it.</p>

<p>How do you get fearless competence? With tests (you can run quickly and believe their outcome).
You could make small improvements, run the tests and make sure the state is still green, then check it in, making the system a little better than before. It will be trivial (if the tests can be trusted).</p>

<p>Conquer the fear with tests: First write unit tests for the code you have written, then for code other people has wrote.</p>

<p>Fragile test problem is when the tests are so coupled with the production code than changing anything in the production makes a bunch of tests fail. This usually happen to beginners with unit testing. Tests must be designed, just like other components.
Even outside tests, if a change in one component leads to many things breaking in others, that is just a bad design, if it’s tests or not.</p>

<p>Code coverage - there is no target number other than 100% that makes sense. Otherwise, you are ok with x% of the code just not working. Also don’t let managers see that number :) The team understands that this is just the number of lines of code being tested. If management adds this metric, developers start using less asserts and just increase coverage in a fake way.</p>

<h3 id="7-we-will-not-dump-on-qa">7. We will not dump on QA</h3>

<p>QA is not the tool we use to find bugs in our system. QA should find nothing.
The responsibility of making sure the system works belongs to developers.</p>

<p>Manual QA is a less than ideal process, also are under a lot of pressure.
QA belongs at the beginning of the process, not at the end.</p>

<h3 id="8-automation">8. Automation!</h3>

<p>If a computer can do it, a computer should do it.</p>

<p>When under pressure (time), QA will not be able to run all the tests suite, so they will just execute some. That is really problematic.</p>

<h3 id="9-we-cover-for-each-other">9. We cover for each other</h3>

<p>How do you make sure someone can cover for you when you are not available?</p>

<p>We can do this by pairing. Otherwise we end up with explicit responsibilities that only a person knows how to do.</p>

<p>Recommendation: a few times a week pair for an hour / half an hour.</p>

<p>Pairing is a better way to do code reviews.</p>

<h3 id="10-introduction-to-honest-estimates">10. Introduction to Honest Estimates</h3>

<p><a href="https://en.wikipedia.org/wiki/Program_evaluation_and_review_technique">PERT estimate system</a> - uses 3 numbers instead of one (best case, nominal - usual case, worst case)</p>

<h2 id="sources">Sources</h2>

<ul>
  <li><a href="https://www.youtube.com/watch?v=Qjywrq2gM8o">Clean Code - Uncle Bob / Lesson 3</a></li>
</ul>]]></content><author><name></name></author><category term="CleanCode" /><summary type="html"><![CDATA[One of my best sources for learning how to write clean code is the content from Robert C. Martin aka “Uncle Bob”. While studying his free “Clean Code - Uncle Bob / Lessons” on YouTube, I took notes and decided to share those notes, so others can benefit from them.]]></summary></entry><entry><title type="html">Clean Code - Naming - by Uncle Bob - part 3</title><link href="https://bpoplauschi.github.io/2021/01/30/Clean-Code-Naming-by-Uncle-Bob-part-3.html" rel="alternate" type="text/html" title="Clean Code - Naming - by Uncle Bob - part 3" /><published>2021-01-30T11:00:00+00:00</published><updated>2021-01-30T11:00:00+00:00</updated><id>https://bpoplauschi.github.io/2021/01/30/Clean-Code-Naming-by-Uncle-Bob-part-3</id><content type="html" xml:base="https://bpoplauschi.github.io/2021/01/30/Clean-Code-Naming-by-Uncle-Bob-part-3.html"><![CDATA[<p>One of my best sources for learning how to write clean code is the content from Robert C. Martin aka “Uncle Bob”. While studying his free “Clean Code - Uncle Bob / Lessons” on YouTube, I took notes and decided to share those notes, so others can benefit from them.</p>

<p>To be clear, all the content belongs to Robert C. Martin, I merely summarised the content and updated the code examples for Swift.</p>

<h2 id="code-sizing">Code sizing</h2>

<p>Here are a few interesting insights from Robert Martin about the size of the code we write.</p>

<h3 id="how-many-lines-should-there-be-in-a-source-file">How many lines should there be in a source file</h3>

<p>File size is not a function of project size, file size is a style you impose.</p>

<p>Aim for 50 or less lines of code per file (average), keeping most files under 100 lines of code.</p>

<h3 id="line-lengths">Line lengths</h3>

<p>Aim for lines up to 30-40 characters / line.</p>

<p>“It’s rude to make your readers scroll to the right”.</p>

<h2 id="names">Names</h2>

<p>Names are everywhere (files, directories, programs, classes, variables, arguments, …).</p>

<p>Because we do so much of it … we’d better do it well!</p>

<p>The rules for naming recommended by Uncle Bob are based on <a href="https://www.maultech.com/chrislott/resources/cstyle/ottinger-naming.html">Tim Ottinger’s Rules for Variable and Class Naming</a>.</p>

<h3 id="reveal-your-intent">Reveal your intent</h3>

<p><code class="language-plaintext highlighter-rouge">var d: Int // elapsed time in days</code></p>

<ul>
  <li>a name that requires a comment does not reveal it’s intent</li>
  <li>the name of a variable should tell us the significance of what that variable contains</li>
</ul>

<p><code class="language-plaintext highlighter-rouge">var elapsedTimeInDays: Int</code></p>

<h3 id="rule-for-variable-names">Rule for variable names</h3>

<p>“A variable name should be proportional to the size of the scope that contains it.”</p>

<h4 id="short-scope">Short scope</h4>

<ul>
  <li>if the scope is very small, like 1 line, a single letter name is fine</li>
</ul>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">switch</span> <span class="p">(</span><span class="n">lhs</span><span class="p">,</span> <span class="n">rhs</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">case</span> <span class="p">(</span><span class="o">.</span><span class="nf">failure</span><span class="p">(</span><span class="n">l</span><span class="p">),</span> <span class="o">.</span><span class="nf">failure</span><span class="p">(</span><span class="n">r</span><span class="p">)):</span> <span class="k">return</span> <span class="n">l</span> <span class="o">==</span> <span class="n">r</span> <span class="c1">// one line scope, using single letter names</span>
<span class="p">}</span>
</code></pre></div></div>

<ul>
  <li>this is because the scope is limited, so you don’t need the name to remind you of anything, the (name of the) function that generated the value should be enough</li>
  <li>inside an if statement, so maybe a couple of lines of code, the variable names inside should be very short</li>
</ul>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span> <span class="k">let</span> <span class="nv">data</span> <span class="o">=</span> <span class="n">cacheData</span> <span class="p">{</span>
    <span class="k">let</span> <span class="nv">cache</span> <span class="o">=</span> <span class="k">try</span> <span class="n">decoder</span><span class="o">.</span><span class="nf">decode</span><span class="p">(</span><span class="kt">Cache</span><span class="o">.</span><span class="k">self</span><span class="p">,</span> <span class="nv">from</span><span class="p">:</span> <span class="n">data</span><span class="p">)</span> <span class="c1">// scope limited to the if, using one word names</span>
    <span class="nf">completion</span><span class="p">(</span><span class="n">cache</span><span class="p">)</span>
<span class="p">}</span>
</code></pre></div></div>

<ul>
  <li>inside a while loop, the variables should be very short</li>
  <li>if you have a function (maybe 4 lines long), the variables inside should be pretty short, maybe a bit longer than the previous ones, maybe a word would be good for an argument</li>
  <li>instance variables that live inside a class have a longer scope (the scope of the class) so it should be long-ish: 2 words maybe</li>
</ul>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">struct</span> <span class="kt">FeedItem</span> <span class="p">{</span>
    <span class="k">let</span> <span class="nv">name</span><span class="p">:</span> <span class="kt">String</span>
    <span class="k">let</span> <span class="nv">imageURL</span><span class="p">:</span> <span class="kt">URL</span>
<span class="p">}</span>
</code></pre></div></div>

<ul>
  <li>the arguments to a member function probably one word</li>
</ul>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">func</span> <span class="nf">save</span><span class="p">(</span><span class="n">_</span> <span class="nv">feed</span><span class="p">:</span> <span class="p">[</span><span class="kt">FeedItem</span><span class="p">],</span> <span class="nv">completion</span><span class="p">:</span> <span class="kd">@escaping</span> <span class="p">(</span><span class="kt">SaveResult</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kt">Void</span><span class="p">)</span>
</code></pre></div></div>

<h4 id="large-scope">Large scope</h4>

<ul>
  <li>long scopes need long names</li>
  <li>global variables have a huge scope, so they should probably be very long</li>
</ul>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// I don't think using global variables is a good practice, but as an exercise ...</span>
<span class="kd">public</span> <span class="k">let</span> <span class="nv">testsDefaultTimeoutInSeconds</span><span class="p">:</span> <span class="kt">Int</span> <span class="o">=</span> <span class="mi">1</span>
</code></pre></div></div>

<h3 id="rule-for-function-names">Rule for function names</h3>

<p>“The name of a function is inversely proportional to the size of the scope that contains it.”</p>

<ul>
  <li>as the scope gets larger, we want to shrink the name because it will be called a lot, from all over the place.</li>
  <li>also, if the function has a larger scope, it’s probably dealing with a high-level abstraction</li>
  <li>we would not want to call the <code class="language-plaintext highlighter-rouge">open()</code> function if the name was <code class="language-plaintext highlighter-rouge">openFileAndThrowExceptionIfNotFound()</code></li>
  <li>as the scope decreases, the names start to get longer</li>
  <li>the instance methods of a class will probably have slightly bigger names</li>
  <li>private functions called by public functions will have even longer names</li>
  <li>private functions called by private functions will have even longer names</li>
  <li>this rule can apply recursively, as you go deeper the names will get longer</li>
  <li>as you keep extracting functions, those get smaller and more precise, that you need more words to specify</li>
</ul>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">func</span> <span class="nf">purgeAllData</span><span class="p">()</span> <span class="p">{</span> <span class="o">...</span> <span class="p">}</span>

<span class="kd">public</span> <span class="kd">final</span> <span class="kd">class</span> <span class="kt">DataManager</span><span class="p">:</span> <span class="kt">DataManagerInterface</span> <span class="p">{</span>
    <span class="kd">public</span> <span class="kd">func</span> <span class="n">loadObject</span><span class="o">&lt;</span><span class="kt">T</span><span class="p">:</span> <span class="kt">Codable</span><span class="o">&gt;</span><span class="p">(</span><span class="n">from</span> <span class="nv">storageType</span><span class="p">:</span> <span class="kt">DataStorageType</span><span class="p">,</span> <span class="n">with</span> <span class="nv">key</span><span class="p">:</span> <span class="kt">String</span><span class="p">,</span> <span class="nv">completion</span><span class="p">:</span> <span class="kd">@escaping</span> <span class="p">(</span><span class="kt">Result</span><span class="o">&lt;</span><span class="kt">T</span><span class="p">,</span> <span class="kt">Error</span><span class="o">&gt;</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kt">Void</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">switch</span> <span class="n">storageType</span> <span class="p">{</span>
        <span class="k">case</span> <span class="o">.</span><span class="nv">secure</span><span class="p">:</span>
            <span class="nf">loadObjectFromKeychain</span><span class="p">(</span><span class="nv">for</span><span class="p">:</span> <span class="n">key</span><span class="p">,</span> <span class="nv">completion</span><span class="p">:</span> <span class="n">completion</span><span class="p">)</span>
        <span class="k">case</span> <span class="kd">let</span> <span class="o">.</span><span class="nf">disk</span><span class="p">(</span><span class="n">directory</span><span class="p">):</span>
            <span class="nf">loadObjectFromDisk</span><span class="p">(</span><span class="nv">in</span><span class="p">:</span> <span class="n">directory</span><span class="p">,</span> <span class="nv">with</span><span class="p">:</span> <span class="n">key</span><span class="p">,</span> <span class="nv">completion</span><span class="p">:</span> <span class="n">completion</span><span class="p">)</span>
        <span class="k">case</span> <span class="o">.</span><span class="nv">memory</span><span class="p">:</span>
            <span class="nf">loadObjectFromMemory</span><span class="p">(</span><span class="nv">with</span><span class="p">:</span> <span class="n">key</span><span class="p">,</span> <span class="nv">completion</span><span class="p">:</span> <span class="n">completion</span><span class="p">)</span>
        <span class="k">case</span> <span class="o">.</span><span class="nv">userDefaults</span><span class="p">:</span>
            <span class="nf">loadObjectFromUserDefaults</span><span class="p">(</span><span class="nv">with</span><span class="p">:</span> <span class="n">key</span><span class="p">,</span> <span class="nv">completion</span><span class="p">:</span> <span class="n">completion</span><span class="p">)</span>
        <span class="p">}</span>
    <span class="p">}</span>
  
    <span class="kd">private</span> <span class="kd">func</span> <span class="n">loadObjectFromKeychain</span><span class="o">&lt;</span><span class="kt">T</span><span class="p">:</span> <span class="kt">Codable</span><span class="o">&gt;</span><span class="p">(</span><span class="k">for</span> <span class="nv">key</span><span class="p">:</span> <span class="kt">String</span><span class="p">,</span> <span class="nv">completion</span><span class="p">:</span> <span class="kd">@escaping</span> <span class="p">(</span><span class="kt">Result</span><span class="o">&lt;</span><span class="kt">T</span><span class="p">,</span> <span class="kt">Error</span><span class="o">&gt;</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kt">Void</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">guard</span> <span class="nf">verifyKeychainStoreIsValid</span><span class="p">()</span> <span class="k">else</span> <span class="p">{</span> <span class="k">return</span> <span class="p">}</span>
        <span class="n">keychainStorage</span><span class="o">.</span><span class="nf">retrieve</span><span class="p">(</span><span class="nv">forKey</span><span class="p">:</span> <span class="n">key</span><span class="p">)</span> <span class="p">{</span> <span class="n">result</span> <span class="k">in</span>
            <span class="o">...</span>
        <span class="p">}</span>
    <span class="p">}</span>
  
    <span class="kd">private</span> <span class="kd">func</span> <span class="nf">verifyKeychainStoreIsValid</span><span class="p">()</span> <span class="o">-&gt;</span> <span class="kt">Bool</span> <span class="p">{</span> <span class="o">...</span> <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<h3 id="rule-for-class-names">Rule for class names</h3>

<p>“The name of a class is inversely proportional to the size of the scope that contains it.”</p>

<ul>
  <li>classes at the global scope have one word names</li>
  <li>derived classes have multiple word names</li>
  <li>inner classes have multiple word names</li>
  <li>as the scope shrinks, the name grows</li>
</ul>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">protocol</span> <span class="kt">Store</span> <span class="p">{}</span>
<span class="kd">protocol</span> <span class="kt">FeedStore</span><span class="p">:</span> <span class="kt">Store</span> <span class="p">{}</span>
<span class="kd">final</span> <span class="kd">class</span> <span class="kt">CodableFeedStore</span><span class="p">:</span> <span class="kt">FeedStore</span> <span class="p">{}</span>
<span class="kd">final</span> <span class="kd">class</span> <span class="kt">InMemoryFeedStore</span><span class="p">:</span> <span class="kt">FeedStore</span> <span class="p">{}</span>
</code></pre></div></div>

<h3 id="code-example">Code Example</h3>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="nc">List</span><span class="o">&lt;</span><span class="kt">int</span><span class="o">[]&gt;</span> <span class="nf">getThem</span><span class="o">()</span> <span class="o">{</span>
    <span class="nc">List</span><span class="o">&lt;</span><span class="kt">int</span><span class="o">[]&gt;</span> <span class="n">list1</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">ArrayList</span><span class="o">&lt;</span><span class="kt">int</span> <span class="o">[]&gt;();</span>
    <span class="k">for</span> <span class="o">(</span><span class="kt">int</span><span class="o">[]</span> <span class="n">x</span> <span class="o">:</span> <span class="n">theList</span><span class="o">)</span>
        <span class="k">if</span> <span class="o">(</span><span class="n">x</span><span class="o">[</span><span class="mi">0</span><span class="o">]</span> <span class="o">==</span> <span class="mi">4</span><span class="o">)</span>
            <span class="n">list1</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">x</span><span class="o">);</span>
    <span class="k">return</span> <span class="n">list1</span><span class="o">;</span>
<span class="o">}</span>
</code></pre></div></div>

<ul>
  <li>this code isn’t complicated</li>
  <li>but it’s not explicit. It reveals no intent</li>
  <li>the names do not explicitly reveal the context of the problem being solved</li>
</ul>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="nc">List</span><span class="o">&lt;</span><span class="kt">int</span><span class="o">[]&gt;</span> <span class="nf">getFlaggedCells</span><span class="o">()</span> <span class="o">{</span>
    <span class="nc">List</span><span class="o">&lt;</span><span class="kt">int</span><span class="o">[]&gt;</span> <span class="n">flaggedCells</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">ArrayList</span><span class="o">&lt;</span><span class="kt">int</span><span class="o">[]&gt;();</span>
    <span class="k">for</span> <span class="o">(</span><span class="kt">int</span><span class="o">[]</span> <span class="n">cell</span> <span class="o">:</span> <span class="n">gameBoard</span><span class="o">)</span>
        <span class="k">if</span> <span class="o">(</span><span class="n">cell</span><span class="o">[</span><span class="no">STATUS_VALUE</span><span class="o">]</span> <span class="o">==</span> <span class="no">FLAGGED</span><span class="o">)</span>
            <span class="n">flaggedCells</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">cell</span><span class="o">);</span>
    <span class="k">return</span> <span class="n">flaggedCells</span><span class="o">;</span>
<span class="o">}</span>
</code></pre></div></div>

<ul>
  <li>only the names have changed and the meaning is far clearer</li>
  <li>now we know the list represents the game board and the function gets all the cells from a list that have the status flagged</li>
  <li>a good naming system will tell you more than the context of the function</li>
</ul>

<h3 id="disambiguate">Disambiguate</h3>

<ul>
  <li>What’s the difference between the following?</li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>XYZControllerForEfficientHandlingOfStrings
XYZControllerForEfficientStorageOfStrings
</code></pre></div></div>

<ul>
  <li>Would you pick the right one from a code completion list?</li>
  <li>And watch out for symbols that look alike</li>
</ul>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">int</span> <span class="n">a</span> <span class="o">=</span> <span class="mi">1</span><span class="o">;</span>
<span class="k">if</span> <span class="o">(</span><span class="no">O</span> <span class="o">==</span> <span class="n">l</span><span class="o">)</span>
    <span class="n">a</span> <span class="o">=</span> <span class="nc">Ol</span><span class="o">;</span>
<span class="k">else</span>
    <span class="n">l</span> <span class="o">=</span> <span class="mo">01</span><span class="o">;</span>
</code></pre></div></div>

<h3 id="avoid-convenient-mispellings">Avoid convenient mispellings</h3>

<ul>
  <li><code class="language-plaintext highlighter-rouge">klass</code> vs <code class="language-plaintext highlighter-rouge">aClass</code> or <code class="language-plaintext highlighter-rouge">theClass</code></li>
  <li>avoid situations where the code will break if a spelling error is fixed</li>
</ul>

<h3 id="number-series">Number series</h3>

<ul>
  <li>the opposite of intentional naming</li>
  <li>provide no clue into the author’s intent</li>
</ul>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">copyChars</span><span class="o">(</span><span class="kt">char</span> <span class="n">a1</span><span class="o">[],</span> <span class="kt">char</span> <span class="n">a2</span><span class="o">[])</span> <span class="o">{</span>
    <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">a1</span><span class="o">.</span><span class="na">length</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span>
        <span class="n">a2</span><span class="o">[</span><span class="n">i</span><span class="o">]</span> <span class="o">=</span> <span class="n">a1</span><span class="o">[</span><span class="n">i</span><span class="o">];</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">copyChars</span><span class="o">(</span><span class="kt">char</span> <span class="n">source</span><span class="o">[],</span> <span class="kt">char</span> <span class="n">destination</span><span class="o">[])</span> <span class="o">{</span>
    <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">source</span><span class="o">.</span><span class="na">length</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span>
        <span class="n">destination</span><span class="o">[</span><span class="n">i</span><span class="o">]</span> <span class="o">=</span> <span class="n">source</span><span class="o">[</span><span class="n">i</span><span class="o">];</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<h3 id="noise-words">Noise words</h3>

<ul>
  <li>suffixes</li>
</ul>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">var</span> <span class="nv">product</span><span class="p">:</span> <span class="kt">Product</span>
<span class="k">var</span> <span class="nv">pd</span><span class="p">:</span> <span class="kt">ProductData</span>
<span class="k">var</span> <span class="nv">pi</span><span class="p">:</span> <span class="kt">ProductInfo</span>
</code></pre></div></div>

<ul>
  <li>data is completly redundant</li>
  <li>what is the difference between <code class="language-plaintext highlighter-rouge">Product</code>, <code class="language-plaintext highlighter-rouge">ProductData</code> and <code class="language-plaintext highlighter-rouge">ProductInfo</code>? the names don’t tell the difference</li>
  <li>prefixes</li>
</ul>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">var</span> <span class="nv">aProduct</span><span class="p">:</span> <span class="kt">Product</span>
<span class="k">var</span> <span class="nv">theProduct</span><span class="p">:</span> <span class="kt">Product</span>
</code></pre></div></div>

<h3 id="distinguish-names-meaningfully">Distinguish names meaningfully</h3>

<ul>
  <li>how to know which function to call</li>
</ul>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">func</span> <span class="nf">getActiveAccount</span><span class="p">()</span> <span class="o">-&gt;</span> <span class="kt">Account</span>
<span class="kd">func</span> <span class="nf">getActiveAccounts</span><span class="p">()</span> <span class="o">-&gt;</span> <span class="p">[</span><span class="kt">Account</span><span class="p">]</span>
<span class="kd">func</span> <span class="nf">getActiveAccountInfo</span><span class="p">()</span> <span class="o">-&gt;</span> <span class="p">[</span><span class="kt">Account</span><span class="p">]</span>
</code></pre></div></div>

<h3 id="make-sure-names-are-pronounceable">Make sure names are pronounceable</h3>

<ul>
  <li>Imagine you have the variable <code class="language-plaintext highlighter-rouge">genymdhms</code> (Generation date, year, month, day, hour, minute and second) and imagine a conversation where you need talk about this variable calling it “gen why emm dee aich emm ess”.</li>
  <li>that should be renamed to <code class="language-plaintext highlighter-rouge">generationTimestamp</code></li>
</ul>

<h2 id="sources">Sources</h2>

<ul>
  <li><a href="https://www.youtube.com/watch?v=2a_ytyt9sf8">Clean Code - Uncle Bob / Lesson 2</a></li>
</ul>]]></content><author><name></name></author><category term="CleanCode" /><summary type="html"><![CDATA[One of my best sources for learning how to write clean code is the content from Robert C. Martin aka “Uncle Bob”. While studying his free “Clean Code - Uncle Bob / Lessons” on YouTube, I took notes and decided to share those notes, so others can benefit from them.]]></summary></entry><entry><title type="html">Clean Code - Comments - by Uncle Bob - part 2</title><link href="https://bpoplauschi.github.io/2021/01/20/Clean-Code-Comments-by-Uncle-Bob-part-2.html" rel="alternate" type="text/html" title="Clean Code - Comments - by Uncle Bob - part 2" /><published>2021-01-20T17:00:00+00:00</published><updated>2021-01-20T17:00:00+00:00</updated><id>https://bpoplauschi.github.io/2021/01/20/Clean-Code-Comments-by-Uncle-Bob-part-2</id><content type="html" xml:base="https://bpoplauschi.github.io/2021/01/20/Clean-Code-Comments-by-Uncle-Bob-part-2.html"><![CDATA[<p>One of my best sources for learning how to write clean code is the content from Robert C. Martin aka “Uncle Bob”. While studying his free “Clean Code - Uncle Bob / Lessons” on YouTube, I took notes and decided to share those notes, so others can benefit from them.</p>

<p>To be clear, all the content belongs to Robert C. Martin, I merely summarised the content and updated the code examples for Swift.</p>

<h2 id="comments">Comments</h2>

<p>The purpose of comments is to explain code that cannot explain itself.</p>

<h3 id="schindlers-list">Schindler’s list</h3>

<p>Nothing can be quite as helpful as a good comment.
Nothing can be quite as obscure as a bad comment.
Comments are not “pure good”.</p>

<h3 id="comments-are-a-last-resort">Comments are a last resort</h3>

<p>The proper use of comments is: <strong>to compensate for our failure to express ourselves in code</strong>.
Every use of a comment represents a failure.
So don’t comment <em>first</em>. Try everything else, then comment as a <em>last resort</em>.</p>

<h3 id="comments-lie">Comments lie</h3>

<ul>
  <li>Not always</li>
  <li>Not intentionally</li>
  <li>But they silently rot</li>
  <li>They migrate</li>
</ul>

<p>IDE’s usually display comments in a faded non-evident color, so they are easy to ignore.
They get desynchronized from the code and can lead to more confusion.
Delete comments when they are no longer necessary (code is clear enough).</p>

<h3 id="explain-yourself-in-code">Explain yourself in code</h3>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// Check to see if the employee is eligible for full benefits</span>
<span class="k">if</span> <span class="p">((</span><span class="n">employee</span><span class="o">.</span><span class="n">flags</span> <span class="o">&amp;</span> <span class="kt">HOURLY_FLAG</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">)</span> <span class="o">&amp;&amp;</span> <span class="p">(</span><span class="n">employee</span><span class="o">.</span><span class="n">age</span> <span class="o">&gt;</span> <span class="mi">65</span><span class="p">)</span> <span class="p">{</span>
    <span class="c1">// ...</span>
<span class="p">}</span>
</code></pre></div></div>

<p>VS</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span> <span class="n">employee</span><span class="o">.</span><span class="nf">isEligibleForFullBenefits</span><span class="p">()</span> <span class="p">{</span>
    <span class="c1">// ...</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Prefer using the name of variables and functions to explain the code.</p>

<hr />

<h3 id="acceptable-comments">Acceptable comments</h3>

<h4 id="copyrights">Copyrights</h4>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">//  Created by John McClane on 01/01/2020.</span>
<span class="c1">//  Copyright © 2020 Company. All rights reserved.</span>
</code></pre></div></div>

<h4 id="informative-comments">Informative comments</h4>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// Returns an instance of the Responder being tested</span>
<span class="kd">static</span> <span class="kd">func</span> <span class="nf">responderInstance</span><span class="p">()</span> <span class="o">-&gt;</span> <span class="kt">Responder</span>
</code></pre></div></div>

<ul>
  <li>this is useful, but it would be better if the function was renamed to <code class="language-plaintext highlighter-rouge">responderBeingTested</code></li>
  <li>acceptable because it’s using the Singleton design pattern</li>
  <li>a better example of an informative comment is a comment explaining what a regular expression does (Java)</li>
</ul>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// format matched hh:mm:ss EEE, MMM dd, yyyy</span>
<span class="nc">Pattern</span> <span class="n">timeMatcher</span> <span class="o">=</span> <span class="n">pattern</span><span class="o">.</span><span class="na">compile</span><span class="o">(</span><span class="s">"\\d*:\\d*:\\d* \\w*, \\w* \\d*, \\d*"</span><span class="o">);</span>
</code></pre></div></div>

<ul>
  <li>note: this comment actually lies, since the expression doesn’t match only the format in the comment</li>
</ul>

<h4 id="explanation-of-intent">Explanation of intent</h4>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kt">int</span> <span class="nf">compareTo</span><span class="o">(</span><span class="nc">Object</span> <span class="n">o</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">if</span> <span class="o">(</span><span class="n">o</span> <span class="n">instanceOf</span> <span class="nc">WikiPagePath</span><span class="o">)</span> <span class="o">{</span>
        <span class="c1">// ...</span>
    <span class="o">}</span>
    <span class="k">return</span> <span class="mi">1</span><span class="o">;</span> <span class="c1">// we are greater because we are the right type.</span>
<span class="o">}</span>
</code></pre></div></div>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// This is our best attempt to get a race condition</span>
<span class="c1">// by creating large number of threads.</span>
<span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">1000</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span>
    <span class="nc">Thread</span> <span class="n">thread</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Thread</span><span class="o">(</span><span class="n">widgetBuilderThread</span><span class="o">);</span>
    <span class="k">try</span> <span class="o">{</span>
        <span class="n">thread</span><span class="o">.</span><span class="na">start</span><span class="o">();</span>
    <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">OutOfMemoryError</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">break</span><span class="o">;</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<h4 id="warning-of-consequences">Warning of consequences</h4>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// Don't run unless you have some time to kill.</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">_testWithReallyBigFile</span><span class="o">()</span> <span class="kd">throws</span> <span class="nc">Exception</span> <span class="o">{</span>
    <span class="n">writeLinesToFile</span><span class="o">(</span><span class="mi">10000000</span><span class="o">);</span>
    <span class="n">response</span><span class="o">.</span><span class="na">setBody</span><span class="o">(</span><span class="n">testFile</span><span class="o">);</span>
    <span class="n">response</span><span class="o">.</span><span class="na">readyToSend</span><span class="o">(</span><span class="k">this</span><span class="o">);</span>
    <span class="nc">String</span> <span class="n">responseString</span> <span class="o">=</span> <span class="n">output</span><span class="o">.</span><span class="na">toString</span><span class="o">();</span>
    <span class="n">assertSubString</span><span class="o">(</span><span class="s">"Content-Length: 1000000000"</span><span class="o">,</span> <span class="n">responseString</span><span class="o">);</span>
    <span class="n">assertTrue</span><span class="o">(</span><span class="n">bytesSent</span> <span class="o">&gt;</span> <span class="mi">1000000000</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div></div>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">static</span> <span class="nc">SimpleDateFormat</span> <span class="nf">makeLogFormat</span><span class="o">()</span> <span class="o">{</span>
    <span class="c1">// SimpleDateFormat is not thread safe, so we need to create each instance independently</span>
    <span class="k">return</span> <span class="k">new</span> <span class="nf">SimpleDateFormat</span><span class="o">(</span><span class="s">"dd/MMM/yyyy:HH:mm:ss Z"</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div></div>

<h4 id="todo-comments">TODO comments</h4>

<ul>
  <li><code class="language-plaintext highlighter-rouge">TODO</code>s are a nice IDE feature, but it’s recommended not to check them in, so fix them before</li>
  <li>otherwise, they become <code class="language-plaintext highlighter-rouge">DONTDO</code>s</li>
</ul>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">private</span> <span class="nc">SimpleResponse</span> <span class="nf">makeResponseWithXML</span><span class="o">(</span><span class="nc">Document</span> <span class="n">doc</span><span class="o">)</span> <span class="kd">throws</span> <span class="nc">Exception</span> <span class="o">{</span>
    <span class="c1">// TODO MdM Should probably use a StreamedResponse</span>
    <span class="nc">ByteArrayOutputStream</span> <span class="n">output</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">ByteArrayOutputStream</span><span class="o">();</span>
    <span class="c1">// ...</span>
<span class="o">}</span>
</code></pre></div></div>

<h4 id="amplification">Amplification</h4>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">String</span> <span class="n">listItemContent</span> <span class="o">=</span> <span class="n">match</span><span class="o">.</span><span class="na">group</span><span class="o">(</span><span class="mi">3</span><span class="o">).</span><span class="na">trim</span><span class="o">();</span>
<span class="c1">// the trim is real important. It removes the starting</span>
<span class="c1">// spaces that could cause the item to be recognized</span>
<span class="c1">// as another list.</span>
</code></pre></div></div>

<h4 id="javadocs-in-publis-apis">Javadocs in publis APIs</h4>

<p>Javadocs is just an example, this applies to any documentation format that comes with public APIs (of a library / framework) and is used to generate a documentation set (like HTML).</p>

<hr />

<h3 id="bad-comments">Bad comments</h3>

<h4 id="mumbling">Mumbling</h4>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kt">void</span> <span class="nf">loadProperties</span><span class="o">(</span><span class="nc">String</span> <span class="n">propertiesLocation</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">try</span> <span class="o">{</span>
        <span class="nc">String</span> <span class="n">propertiesPath</span> <span class="o">=</span> <span class="n">propertiesLocation</span> <span class="o">+</span> <span class="s">"/"</span> <span class="o">+</span> <span class="no">PROPERTIES_FILE</span><span class="o">;</span>
        <span class="nc">FileInputStream</span> <span class="n">propertiesStream</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">FileInputStream</span><span class="o">(</span><span class="n">propertiesPath</span><span class="o">);</span>
        <span class="n">loadedProperties</span><span class="o">.</span><span class="na">load</span><span class="o">(</span><span class="n">propertiesStream</span><span class="o">);</span>
    <span class="o">}</span> <span class="k">catch</span><span class="o">(</span><span class="nc">IOException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
        <span class="c1">// No properties files means all defaults are loaded</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<ul>
  <li>what does this mean?</li>
  <li>who loads the defaults?</li>
  <li>were they previously loaded or is that yet to come?</li>
  <li>was the author trying to remind himself to do it later?</li>
</ul>

<h4 id="redundant-comments">Redundant comments</h4>

<ul>
  <li>it takes longer to read and understand the comment than it takes to read and understand the code</li>
</ul>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// Utility method that returns when this.closed is true. Throws an exception</span>
<span class="c1">// if the timeout is reached.</span>
<span class="kd">public</span> <span class="kd">synchronized</span> <span class="kt">void</span> <span class="nf">waitForClose</span><span class="o">(</span><span class="kd">final</span> <span class="kt">long</span> <span class="n">timeoutMillis</span><span class="o">)</span> <span class="kd">throws</span> <span class="nc">Exception</span> <span class="o">{</span>
    <span class="k">while</span> <span class="o">(!</span><span class="n">closed</span> <span class="o">&amp;&amp;</span> <span class="n">timeoutMillis</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">wait</span><span class="o">(</span><span class="mi">100</span><span class="o">);</span>
        <span class="n">timeoutMillis</span> <span class="o">-=</span> <span class="mi">100</span><span class="o">;</span>
    <span class="o">}</span>
    <span class="k">if</span><span class="o">(!</span><span class="n">closed</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">throw</span> <span class="k">new</span> <span class="nf">Exception</span><span class="o">(</span><span class="s">"MockResponseSender could not be closed"</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<ul>
  <li>redundant comments (from Tomcat)</li>
</ul>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cm">/** The child Containers belonging to this Container, keyed by name. */</span>
<span class="kd">protected</span> <span class="nc">HashMap</span> <span class="n">children</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">HashMap</span><span class="o">();</span>

<span class="cm">/** The processor delay for this component. */</span>
<span class="kd">protected</span> <span class="kt">int</span> <span class="n">backgroundProcessorDelay</span> <span class="o">=</span> <span class="o">-</span><span class="mi">1</span><span class="o">;</span>

<span class="cm">/** The lifecycle event support for this component. */</span>
<span class="kd">protected</span> <span class="nc">LifecycleSupport</span> <span class="n">lifecycle</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">LifecycleSupport</span><span class="o">(</span><span class="k">this</span><span class="o">);</span>

<span class="o">...</span>
</code></pre></div></div>

<h4 id="mandated-comments">Mandated comments</h4>

<ul>
  <li>it is just plain silly to have a rule that says that every function must have a javadoc,</li>
  <li>or every variable must have a comment</li>
  <li>comments like these clutter the code and propagate lies, confusion, and disorganization.</li>
</ul>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cm">/**
 * @param title The title of the CD
 * @param author The author of the CD
 * @param tracks The number of tracks on the CD
 * @param durationInMinutes The duration of the CD in minutes
 */</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">addCD</span><span class="o">(</span><span class="nc">String</span> <span class="n">title</span><span class="o">,</span>
                  <span class="nc">String</span> <span class="n">author</span><span class="o">,</span>
                  <span class="kt">int</span> <span class="n">tracks</span><span class="o">,</span>
                  <span class="kt">int</span> <span class="n">durationInMinutes</span><span class="o">)</span> <span class="o">{</span>
    <span class="c1">// ...</span>
<span class="o">}</span>
</code></pre></div></div>

<h4 id="journal-comments">Journal comments</h4>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cm">/**
 * Changes (from 11-Oct-2001)
 * --------------------------
 * 11-Oct-2001 : Re-organised the class and moved it to new package com.jrefinery.date (DG);
 * 05-Nov-2001 : Added a getDescription() method, and eliminated NotableDate class (DG);
 * 12-Nov-2001 : IBD requires setDescription() method, now that NotableDate class is gone (DG); Changed getPreviousDayOfWeek(), getFollowingDayOfWeek() and getNearestDayOfWeek() to correct bugs (DG);
 * 05-Dec-2001 : Fixed bug in SpreadsheetDate class (DG);
 */</span>
</code></pre></div></div>

<ul>
  <li>this is why we have source code control systems</li>
</ul>

<h4 id="noise-comments">Noise comments</h4>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cm">/**
 * Default constructor.
 */</span>
<span class="kd">protected</span> <span class="nf">AnnualDateRule</span><span class="o">()</span> <span class="o">{</span>
<span class="o">}</span>
</code></pre></div></div>

<ul>
  <li>these comments aren’t just redundant, they are noisy. So we learn to ignore them</li>
  <li>after a while our eyes don’t even see them.</li>
</ul>

<h4 id="scary-noise">Scary noise</h4>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cm">/** The name. */</span>
<span class="kd">private</span> <span class="nc">String</span> <span class="n">name</span><span class="o">;</span>

<span class="cm">/** The version. */</span>
<span class="kd">private</span> <span class="nc">String</span> <span class="n">version</span><span class="o">;</span>

<span class="cm">/** The licenseName. */</span>
<span class="kd">private</span> <span class="nc">String</span> <span class="n">licenseName</span><span class="o">;</span>

<span class="cm">/** The version. */</span>
<span class="kd">private</span> <span class="nc">String</span> <span class="n">info</span><span class="o">;</span>
</code></pre></div></div>

<ul>
  <li>this was taken from a popular open-source framework.</li>
  <li>clearly noisily redundant.</li>
  <li>now read it again more carefully.</li>
</ul>

<h4 id="use-explanatory-code-not-comments">Use explanatory code, not comments</h4>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// does the module from the global list &lt;mod&gt;</span>
<span class="c1">// depend on the subsystem we are part of?</span>
<span class="k">if</span> <span class="o">(</span><span class="n">smodule</span><span class="o">.</span><span class="na">getDependSubsystems</span><span class="o">().</span><span class="na">contains</span><span class="o">(</span><span class="n">subSysMod</span><span class="o">.</span><span class="na">getSubSystem</span><span class="o">()))</span> <span class="o">{</span>
    <span class="c1">// ...</span>
<span class="o">}</span>
</code></pre></div></div>

<ul>
  <li>extract variables to explain things</li>
</ul>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">ArrayList</span><span class="o">&lt;</span><span class="nc">Module</span><span class="o">&gt;</span> <span class="n">moduleDependees</span> <span class="o">=</span> <span class="n">smodule</span><span class="o">.</span><span class="na">getDependSubsystems</span><span class="o">();</span>
<span class="nc">Module</span> <span class="n">ourSubSystem</span> <span class="o">=</span> <span class="n">subSysMod</span><span class="o">.</span><span class="na">getSubSystem</span><span class="o">();</span>
<span class="k">if</span> <span class="o">(</span><span class="n">moduleDependees</span><span class="o">.</span><span class="na">contains</span><span class="o">(</span><span class="n">ourSubSystem</span><span class="o">))</span> <span class="o">{</span>
    <span class="c1">// ...</span>
<span class="o">}</span>
</code></pre></div></div>

<h4 id="position-markers">Position markers</h4>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// ------------------------------ Instance Variables</span>
</code></pre></div></div>

<ul>
  <li>these are usually pure clutter.</li>
  <li>banners are startling and obvious <em>only if</em> you don’y see them very often.</li>
</ul>

<h4 id="closing-brace-comments">Closing Brace Comments</h4>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span> <span class="o">((</span><span class="n">result</span> <span class="o">&lt;</span> <span class="mi">1</span><span class="o">)</span> <span class="o">||</span> <span class="o">(</span><span class="n">result</span> <span class="o">&gt;</span> <span class="mi">12</span><span class="o">))</span> <span class="o">{</span>
    <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">monthNames</span><span class="o">.</span><span class="na">length</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span>
        <span class="k">if</span> <span class="o">(</span><span class="n">s</span><span class="o">.</span><span class="na">equals</span><span class="o">(</span><span class="n">shortMonthNames</span><span class="o">[</span><span class="n">i</span><span class="o">]))</span> <span class="o">{</span>
            <span class="n">result</span> <span class="o">=</span> <span class="n">i</span> <span class="o">+</span> <span class="mi">1</span><span class="o">;</span>
            <span class="k">break</span><span class="o">;</span>
        <span class="o">}</span> <span class="c1">// if</span>
        <span class="k">if</span> <span class="o">(</span><span class="n">s</span><span class="o">.</span><span class="na">equals</span><span class="o">(</span><span class="n">monthNames</span><span class="o">[</span><span class="n">i</span><span class="o">]))</span> <span class="o">{</span>
            <span class="n">result</span> <span class="o">=</span> <span class="n">i</span> <span class="o">+</span> <span class="mi">1</span><span class="o">;</span>
            <span class="k">break</span><span class="o">;</span>
        <span class="o">}</span> <span class="c1">// if</span>
    <span class="o">}</span> <span class="c1">// for</span>
<span class="o">}</span> <span class="c1">// if</span>
</code></pre></div></div>

<ul>
  <li>this is a noisy bad habit.</li>
  <li>shorten your functions instead.</li>
</ul>

<h4 id="attributions-and-bylines">Attributions and bylines</h4>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cm">/* Added by Rick */</span>
</code></pre></div></div>

<ul>
  <li>Again, <em>blame</em> is what source code controls systems are for.</li>
</ul>

<h4 id="commented-out-code">Commented out code</h4>

<ul>
  <li>few practices are as odious.</li>
  <li>don’t do this!</li>
</ul>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">this</span><span class="o">.</span><span class="na">bytesPos</span> <span class="o">=</span> <span class="n">writeBytes</span><span class="o">(</span><span class="n">pngIdBytes</span><span class="o">,</span> <span class="mi">0</span><span class="o">);</span>
<span class="c1">//hdrPos = bytePos;</span>
<span class="n">writeHeader</span><span class="o">();</span>
<span class="n">writeResolution</span><span class="o">();</span>
<span class="c1">//dataPos = bytePos;</span>
<span class="o">...</span>
</code></pre></div></div>

<h4 id="html-in-comments">HTML in comments</h4>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cm">/**
* Task to run fit tests.
* This task runs fitnesse tests and publishes the results.
* &lt;p/&gt;
* &lt;pre&gt;
* Usage:
* &amp;lt;taskdef name=&amp;quot;execute-fitnesse-tests&amp;quot;
* classname=&amp;quot;fitnesse.ant.ExecuteFitnesseTestsTask&amp;quot;
* classpathref=&amp;quot;classpath&amp;quot; /&amp;gt;
* OR
* &amp;lt;taskdef classpathref=&amp;quot;classpath&amp;quot;
* resource=&amp;quot;tasks.properties&amp;quot; /&amp;gt;
* &lt;p/&gt;
* &amp;lt;execute-fitnesse-tests
* suitepage=&amp;quot;FitNesse.SuiteAcceptanceTests&amp;quot;
* fitnesseport=&amp;quot;8082&amp;quot;
* resultsdir=&amp;quot;${results.dir}&amp;quot;
* resultshtmlpage=&amp;quot;fit-results.html&amp;quot;
* classpathref=&amp;quot;classpath&amp;quot; /&amp;gt;
* &lt;/pre&gt;
*/</span>
</code></pre></div></div>

<h4 id="non-local-information">Non-local information</h4>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cm">/**
 * Port on which fitnesse would run. Defaults to &lt;b&gt;8082&lt;/b&gt;.
 */</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">setFitnessePort</span><span class="o">(</span><span class="kt">int</span> <span class="n">fitnessePort</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">this</span><span class="o">.</span><span class="na">fitnessePort</span> <span class="o">=</span> <span class="n">fitnessePort</span><span class="o">;</span>
<span class="o">}</span>
</code></pre></div></div>

<ul>
  <li>if you must write a comment, then make sure it describes the code it appears near.</li>
  <li>where is the <code class="language-plaintext highlighter-rouge">8082</code> code?</li>
</ul>

<h2 id="sources">Sources</h2>

<ul>
  <li><a href="https://www.youtube.com/watch?v=2a_ytyt9sf8">Clean Code - Uncle Bob / Lesson 2</a></li>
</ul>]]></content><author><name></name></author><category term="CleanCode" /><summary type="html"><![CDATA[One of my best sources for learning how to write clean code is the content from Robert C. Martin aka “Uncle Bob”. While studying his free “Clean Code - Uncle Bob / Lessons” on YouTube, I took notes and decided to share those notes, so others can benefit from them.]]></summary></entry></feed>