<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chris Nevin on Medium]]></title>
        <description><![CDATA[Stories by Chris Nevin on Medium]]></description>
        <link>https://medium.com/@cjnevin?source=rss-79ea0cfb22d7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2UEHvtO-v4OuxrhaGPDvRg.jpeg</url>
            <title>Stories by Chris Nevin on Medium</title>
            <link>https://medium.com/@cjnevin?source=rss-79ea0cfb22d7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 10:45:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cjnevin/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[AI Generated Architecture Decision Records (ADRs)]]></title>
            <link>https://medium.com/@cjnevin/ai-generated-architecture-decision-records-adrs-89e757d7f43e?source=rss-79ea0cfb22d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/89e757d7f43e</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[ai-generated-content]]></category>
            <dc:creator><![CDATA[Chris Nevin]]></dc:creator>
            <pubDate>Tue, 04 Nov 2025 05:59:22 GMT</pubDate>
            <atom:updated>2025-11-04T05:59:22.500Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eEMZyiItAaGxjyTUH5CuAQ.png" /><figcaption>AI generated image for this article</figcaption></figure><p>Architecture Decision Records (ADRs) can be time consuming to write well with lots of context and thoughtful unbiased consequences. In order to reduce complexity and bias I have decided to write this guide on how to prompt AI to assist us to write a decent ADR.</p><p>Let’s start with a role for the AI to take on, a task for the AI to achieve, and a template for the output.</p><blockquote>As an expert Software Engineer. You have been tasked to write an <br>Architecture Decision Record using the following headings:</blockquote><blockquote># ADR-&lt;4 Digit Number&gt;: &lt;Name&gt;</blockquote><blockquote>## Context</blockquote><blockquote>## Decision</blockquote><blockquote>## Deciders</blockquote><blockquote>## Status<br>Valid statuses are Proposed, Accepted, Deprecated, or Superseded by <br>ADR-&lt;4 Digit Number&gt;</blockquote><blockquote>## Consequences</blockquote><blockquote>Prompt the user for ADR number, name, deciders, and status. Then ask them <br>for the Ticket and Pull Request descriptions so you can derive the <br>Context, Decisions, and Consequences.</blockquote><p>Based on the above, we can expect the AI to prompt us 3 times for information, I have broken this up into steps below.</p><h4>Step 1</h4><p>We can expect the AI to come back asking for the ADR Number, ADR Name, Deciders, and Status. For this example, I’ll reply with this:</p><blockquote>0005, Centralized Dependencies, @cjnevin, Accepted</blockquote><h4>Step 2</h4><p>Next, we can expect the AI to ask us about the <em>Ticket Description</em> (to keep this article small, it has been summarized)</p><blockquote>As a developer I want to centralize the dependencies using a modular architecture with the Core defining the dependencies so that they can be reused between Feature modules and injected and configured by different White Labeled apps.</blockquote><h4>Step 3</h4><p>Finally, the AI should request a <em>Pull Request Description</em> (to keep this article small, it has been summarized)</p><blockquote>This pull request restructures the way dependency injection works, rather than creating a Service for each dependency in each Feature which often wrap the same underlying dependencies we want to write some low-level dependencies that we can extend with some common logic in the Core and extend further to provide the data we need in each of the Features.</blockquote><h4>Output</h4><p>Based on the input above, we could expect the AI to respond with something like what is shown below…</p><h3>ADR-0005: Centralized Dependencies</h3><h3>Context</h3><p>As a developer, the current approach to dependency management often leads to duplication. The goal is to centralize dependencies using a modular architecture where the Core module defines these dependencies. This will enable their reuse across various Feature modules and allow for flexible injection and configuration by different White Labeled applications. This addresses the inefficiency of creating separate services for the same underlying dependencies within each feature.</p><h3>Decision</h3><p>The decision is to restructure the dependency injection mechanism. Instead of creating a distinct service for each dependency within every Feature module—which often results in multiple services wrapping the same underlying components—we will establish low-level dependencies within the Core module. These core dependencies can then be extended with common logic and further specialized to provide the specific data and functionality required by individual Feature modules. This approach promotes a more cohesive and extensible dependency graph.</p><h3>Deciders</h3><p>@cjnevin</p><h3>Status</h3><p>Accepted</p><h3>Consequences</h3><h4>Positive:</h4><ul><li><strong>Increased Reusability:</strong> Dependencies defined in the Core module can be easily reused across multiple Feature modules, reducing code duplication.</li><li><strong>Improved Maintainability:</strong> Centralizing dependency definitions simplifies updates and bug fixes, as changes only need to be made in one place.</li><li><strong>Enhanced Modularity: </strong>Promotes a clearer separation of concerns, with the Core module responsible for foundational dependencies and Feature modules focusing on specific functionalities.</li><li><strong>Easier White Labeling:</strong> White Labeled applications can more easily configure and inject specific implementations of dependencies, as the core structure is standardized.</li><li><strong>Reduced Boilerplate:</strong> Eliminates the need to create redundant wrapper services in each feature, leading to cleaner and more concise code.</li><li><strong>Better Consistency:</strong> Ensures a consistent approach to dependency management across the entire application.</li></ul><h4>Negative/Considerations:</h4><ul><li><strong>Initial Refactoring Effort: </strong>Significant work may be required to refactor existing dependency structures to align with the new centralized model.</li><li><strong>Increased Complexity in Core: </strong>The Core module might become more complex as it houses a greater number of foundational dependencies. Careful design and organization within Core will be crucial.</li><li><strong>Learning Curve: </strong>Developers unfamiliar with this centralized pattern may require time to adapt to the new dependency injection approach.</li><li><strong>Potential for Breaking Changes: </strong>The transition period may introduce breaking changes to existing features that rely on the previous dependency injection patterns.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89e757d7f43e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extending Core Dependencies]]></title>
            <link>https://medium.com/@cjnevin/extending-core-dependencies-e905c47245e0?source=rss-79ea0cfb22d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e905c47245e0</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Chris Nevin]]></dc:creator>
            <pubDate>Thu, 09 May 2024 00:42:24 GMT</pubDate>
            <atom:updated>2025-05-21T22:30:57.630Z</atom:updated>
            <content:encoded><![CDATA[<p>As codebases grow we can end up with <em>Ravioli code:</em></p><blockquote>Ravioli code describes code that comprises well-structured <a href="https://en.wikipedia.org/wiki/Class_(computer_programming)">classes</a> that are easy to understand in isolation, but difficult to understand as a whole.</blockquote><p>We can also end up with <em>Lasagne code:</em></p><blockquote><a href="https://en.wikipedia.org/wiki/Lasagna">Lasagna</a> code refers to code whose layers are so complicated and intertwined that making a change in one layer would necessitate changes in all other layers.</blockquote><p>Below I have provided a simple example of a login request which fetches values using aURLRequest and stores the <em>username</em> and <em>password</em> and the Date that we attempted login.</p><pre>// Interfaces<br><br>protocol DateProviderInterface: AnyObject {<br>  func now() -&gt; Date<br>}<br><br>protocol StorageInterface: AnyObject {<br>  func read(for key: String) throws -&gt; Any<br>  func write(_ value: Any, for key: String)<br>}<br><br>protocol NetworkManagerInterface: AnyObject {<br>  func send(_ request: URLRequest) async throws -&gt; Data<br>}<br><br>protocol LoginInterface: AnyObject {<br>  func login(username: String, password: String) async throws -&gt; User<br>}<br><br>// Implementation<br><br>final class LoginManager: LoginInterface {<br>  let dateProvider: DateProviderInterface<br>  let networkManager: NetworkManagerInterface<br>  let storage: StorageInterface<br>  func login(username: String, password: String) async throws -&gt; User {<br>    let data = try networkManager.send(URLRequest.login(username: username, password: password)<br>    let user = try JSONDecoder().decode(User.self, from: data)<br>    storage.write(username, for: &quot;username&quot;)<br>    storage.write(password, for: &quot;password&quot;)<br>    storage.write(dateProvider.now(), for: &quot;lastLoginDate&quot;)<br>    return user<br>  }<br>}<br><br>// Mocks<br><br>final class DateProviderMock: DateProviderInterface {<br>  var returnedDate = Date(timeIntervalSinceReferenceDate: 0)<br>  func now() -&gt; Date {<br>    returnedDate<br>  }<br>}<br><br>final class StorageMock: StorageInterface {<br>  var keyValues: [String: Any] = [:]<br>  var recordedStorageActions: [String] = []<br>  func read(for key: String) throws -&gt; Any {<br>    recordedStorageActions.append(&quot;Read key \(key)&quot;)<br>    return try keyValues[key].tryUnwrap()<br>  }<br>  func write(_ value: Any, for key: String) {<br>    recordedStorageActions.append(&quot;Write \(value) for key \(key)&quot;)<br>    keyValues[key] = value<br>  }<br>}<br><br>final class NetworkManagerMock: NetworkManagerInterface {<br>  private let result: Result&lt;Data, Error&gt;<br>  var recordedRequests: [URLRequest] = []<br>  init(result: Result&lt;Data, Error&gt; = .success(Data())) {<br>    self.result = result<br>  }<br>  func send(_ request: URLRequest) async throws -&gt; Data {<br>    recordedRequests.append(request)<br>    return try result.get()<br>  } <br>}<br><br>// Test<br><br>@Test<br>func loginSucceeds() {<br>  // GIVEN<br>  let expectedUser = User(id: &quot;123&quot;)<br>  let encodedUser = try JSONEncoder().encode(expectedUser)<br>  let networkManager = NetworkManagerMock(result: .success(encodedUser))<br>  let storage = StorageMock()<br>  let sut = LoginManager(<br>    networkManager: networkManager,<br>    storage: storage<br>  )<br><br>  // WHEN<br>  let user = try await sut.login(username: &quot;Username&quot;, password: &quot;Password&quot;)<br><br>  // THEN<br>  #expect(user == expectedUser)<br>  #expect(networkManager.recordedRequests == [<br>    .login(username: &quot;username&quot;, password: &quot;password&quot;)<br>  ])<br>  #expect(storage.recordedStorageActions == [<br>    &quot;Wrote Username for key username&quot;,<br>    &quot;Wrote Password for key password&quot;,<br>    &quot;Wrote 01-01-2000 for key lastLoginDate&quot;<br>  ])<br>  #expect(storage.read(for: &quot;username&quot;) == &quot;Username&quot;)<br>  #expect(storage.read(for: &quot;password&quot;) == &quot;Password&quot;)<br>  #expect(storage.read(for: &quot;lastLoginDate&quot;) == Date(timeIntervalSinceReferenceDate: 0))<br>}</pre><p>As you can see above, we have to create the DateProviderMock, NetworkManagerMock and StorageMock. And, in other places we will also need to create a LoginManagerMock such as in a <em>ViewModel</em>. Protocols also need to be marked with AnyObject to avoid potential memory leaks.</p><p>This is fine in smaller codebases as there aren’t many mocks but in very large codebases this can quickly spiral out of control and cause a huge maintenance overhead because almost every object is defined with a protocol, an implementation, and a mock/spy.</p><blockquote>The Golden Hammer anti-pattern can arise when developers become overly reliant on a single tool, technique, or pattern, applying it to situations where it may not be the best fit. This can result in inefficient, hard-to-maintain code, and can limit the developer’s growth as they fail to explore other techniques or tools.</blockquote><p>As our codebase grows we end up with another problem: <em>Cognitive Load</em>. Tests can become too complicated to write/understand when there are dozens of dependencies to think about, the codebase I am working on that follows this principle has over 500<em> ‘dependencies’</em> and in most cases they just wrap a <em>‘core dependency’</em> such as a DateProvider or aNetworkManager or a StorageManager as seen above with the LoginManager.</p><p>Which leads me to two other principles of software development, <em>KISS (keep it simple stupid) </em>and <em>YAGNI (you aren’t gonna need it)</em>. Given most of these dependencies will never change have we over-engineered it by making them all replaceable? Shouldn’t we just make the ‘core’ dependencies replaceable then feed mock values through them?</p><p>Lets rethink the above example using the simplest types we can think of then extend them with additional behaviour:</p><pre>// Concrete Types<br><br>enum StoredValue {<br>  case date(Date)<br>  case string(String)<br>}<br><br>struct Storage {<br>  let read: (String) throws -&gt; StoredValue<br>  let write: (StoredValue, String) -&gt; Void<br>}<br><br>struct AppEnvironment {<br>  let date: () -&gt; Date<br>  let fetch: (URLRequest) async throws -&gt; Data<br>  let storage: Storage<br>}<br><br>// Extension<br><br>extension AppEnvironment {<br>  func login(username: String, password: String) async throws -&gt; User {<br>    let data = try fetch(URLRequest.login(username: username, password: password)<br>    let user = try JSONDecoder().decode(User.self, from: data)<br>    storage.write(.string(username), “username”)<br>    storage.write(.string(password), “password”)<br>    storage.write(.date(date()), for: &quot;lastLoginDate&quot;)<br>    return user<br>  }<br>}<br><br>// Test<br><br>@Test<br>func loginSucceeds() async throws {<br>  // GIVEN<br>  let expectedUser = User(id: &quot;123&quot;)<br>  let encodedUser = try JSONEncoder().encode(expectedUser)<br>  var fetchResult: Result&lt;Data, Error&gt; = .success(encodedUser)<br>  var storedValues: [String: StoredValue] = [:]<br>  var recordedRequests: [URLRequest] = []<br>  var recordedStorageActions: [String] = []<br>  let sut = AppEnvironment(<br>    date: { Date(timeIntervalSinceReferenceDate: 0) }<br>    fetch: { request in<br>      recordedRequests.append(request)<br>      return try fetchResult.get()<br>    },<br>    storage: Storage(<br>      read: { key in <br>        recordedStorageActions.append(&quot;Read key \(key)&quot;)<br>        return try storedValues[key].tryUnwrap()<br>      },<br>      write: { value, key in <br>        storedValues[key] = value<br>        recordedStorageActions.append(&quot;Wrote \(value) for key \(key)&quot;)<br>      }<br>    )<br>  )<br><br>  // WHEN<br>  let user = try await sut.login(username: &quot;Username&quot;, password: &quot;Password&quot;)<br><br>  // THEN<br>  #expect(user == expectedUser)<br>  #expect(recordedRequests == [<br>    .login(username: &quot;username&quot;, password: &quot;password&quot;)<br>  ])<br>  #expect(recordedStorageActions == [<br>    &quot;Wrote Username for key username&quot;,<br>    &quot;Wrote Password for key password&quot;,<br>    &quot;Wrote 01-01-2000 for key lastLoginDate&quot;<br>  ])<br>  #expect(sut.storage.read(&quot;username&quot;) == .string(&quot;Username&quot;))<br>  #expect(sut.storage.read(&quot;password&quot;) == .string(&quot;Password&quot;))<br>  #expect(sut.storage.read(&quot;lastLoginDate&quot;) == .date(Date(timeIntervalSinceReferenceDate: 0)))<br>}</pre><p>This in effect does the same thing but without having to define protocols and mock objects, we can utilise dictionaries and arrays to store values. We can even return fatalError for dependencies we don&#39;t expect to be called by our test. Since every dependency is a function we can write wrappers for those functions to provide additional value, such as <em>analytics</em> or <em>logging</em> or like in the above example: <em>recordings</em>.</p><p>We can also leverage other frameworks to confirm our recordings to reduce the amount of code we need to write, such as the <em>SnapshotTesting</em> library from the guys at <a href="http://pointfree.co/">PointFree.co</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e905c47245e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Clipping Infinite Carousel]]></title>
            <link>https://medium.com/@cjnevin/building-a-clipping-infinite-carousel-bd31a50dbf72?source=rss-79ea0cfb22d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd31a50dbf72</guid>
            <category><![CDATA[infinite]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[infinite-scroll]]></category>
            <category><![CDATA[circular]]></category>
            <category><![CDATA[carousel]]></category>
            <dc:creator><![CDATA[Chris Nevin]]></dc:creator>
            <pubDate>Sat, 13 May 2023 06:55:57 GMT</pubDate>
            <atom:updated>2023-05-13T17:58:08.889Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*laWxUSpwEEs954T4K6KFjA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@flowinteractive?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ivan Slade</a> on <a href="https://unsplash.com/photos/mxbhFkoI6AU?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>I wanted to build something similar to the <em>Netflix</em> carousels which lets you scroll infinitely to the right but not to the left and when you stop scrolling right it recalculates your offset so you don’t need to scroll several pages of items to get back to the zero index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*sbMQ6g0e88JLPWpYp8EOOg.gif" /><figcaption>Here’s what the final product looks like</figcaption></figure><p>I attempted to get this working in Compositional Layout however there were two problems: 1) UIScrollViewDelegate methods are not called when you set the layout to a UICollectionViewCompositionalLayout; and 2) the contentOffset property is always zero.</p><p>I also attempted to get this working in SwiftUI but unfortunately due to not being able to set contentOffset or detect when a user has stopped scrolling accurately it made SwiftUI unviable.</p><p>So, I ended up using a plain old UICollectionViewFlowLayout:</p><pre>lazy var flowLayout = UICollectionViewFlowLayout()<br>flowLayout.scrollDirection = .horizontal<br>flowLayout.itemSize = itemSize<br>flowLayout.minimumInteritemSpacing = 0<br>flowLayout.minimumLineSpacing = 0</pre><p>Returning number of items like so:</p><pre>var additionalItemCount: Int = 0<br>let items: [Item] = [...]<br>var total: Int { additionalItemCount + items.count }<br><br>func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -&gt; Int {<br>  total<br>}</pre><p>After we reach a particular index we want to show more items:</p><pre>func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {<br>  if indexPath.row == total - threshold {<br>    DispatchQueue.main.async {<br>      self.additionalItemCount += self.items.count<br>      self.collectionView.reloadData()<br>    }<br>  }<br>}</pre><p>We need to respond to two methods of the UIScrollViewDelegate:</p><pre>// called when user swipes and there is an animation<br>func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {<br>  removeAdditionalItems()<br>}<br><br>// called when user drags and there is no deceleration<br>func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {<br>  if !decelerate {<br>    removeAdditionalItems()<br>  }<br>}</pre><p>When scrolling stops we can remove the additional items:</p><pre>func removeAdditionalItems() {<br>  guard additionalItemCount &gt; 0 else { return }<br>  // First lets check to see if the trigger to load more items is visible<br>  let triggerEnd = total - items.count<br>  let triggerStart = triggerEnd - loadThreshold<br>  let triggerRange = triggerStart..&lt;triggerEnd<br>  let visibleIndices = collectionView.indexPathsForVisibleItems.map(\.row)<br>  let addItemsTriggerVisible = visibleIndices.contains(where: triggerRange.contains)<br>  if addItemsTriggerVisible {<br>    // If total is high enough, we can still do some cleanup<br>    // Otherwise we need to keep both pages of items<br>    guard total &gt; items.count * 2 else { return }<br>    resetAdditionalItems(to: items.count)<br>  } else {<br>    resetAdditionalItems(to: 0)<br>  }<br>}<br><br>func resetAdditionalItems(to count: Int) {<br>  var contentOffset = collectionView.contentOffset<br>  let itemsWidth = CGFloat(items.count) * itemSize.width<br>  contentOffset.x = contentOffset.x.truncatingRemainder(dividingBy: itemsWidth)<br>  DispatchQueue.main.async {<br>    self.additionalItemCount = count<br>    self.collectionView.contentOffset = contentOffset<br>    self.collectionView.reloadData()<br>  }<br>}</pre><p>Now, when we scroll through 5 pages of items it will reset to 1 or 2 pages depending on where we are in relation to the trigger index.</p><p><a href="https://gist.github.com/cjnevin/c96f3f6b32087fbee7a1fbe8cbed5f85">Number of items gist here</a></p><h4>DiffableDataSource</h4><p>I have also managed to get this working using UICollectionViewDiffableDataSource which is more useful when we are receiving content that changes over time.</p><p><a href="https://gist.github.com/cjnevin/a4400c3ae581bfdd47a9a4355dfb57d3">Diffable gist here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd31a50dbf72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency Graph Hell (iOS)]]></title>
            <link>https://levelup.gitconnected.com/problem-dependency-graph-hell-1405d17dcb92?source=rss-79ea0cfb22d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/1405d17dcb92</guid>
            <category><![CDATA[dependencies]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[dependency-management]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[service-locator]]></category>
            <dc:creator><![CDATA[Chris Nevin]]></dc:creator>
            <pubDate>Mon, 07 Nov 2022 09:28:04 GMT</pubDate>
            <atom:updated>2022-11-07T14:39:33.792Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sm6TnZODWLAOx_Dt4dDdcg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@charlesdeluvio?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">charlesdeluvio</a> on <a href="https://unsplash.com/s/photos/arrows?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>A common pattern I see emerging in large codebases that have dozens or hundreds of dependencies is that a parent object has knowledge about all of the dependencies below it in the dependency graph. Consider the following:</p><blockquote>Parent: A, B, C, D, E<br> — Child1: A, B, C, E<br> — — Grandchild1: E<br> — — Grandchild2: B, C</blockquote><p>Adding a new dependency to a <em>Child</em> or <em>Grandchild</em> object requires performing <a href="https://refactoring.guru/smells/shotgun-surgery">shotgun-surgery</a> on all objects that know about that object… One change could affect 20 or 30 files.</p><p>In the above example, there is a lot of boilerplate involved in passing these objects between each other. This also leads to a lot of boilerplate in our tests with mocks and spies. These objects effectively act as <a href="https://refactoring.guru/smells/middle-man">middle-men</a>, not doing anything with the object except passing it down the line.</p><p>Ideally, changes should be isolated to reduce merge conflicts and objects should be small to reduce cognitive load, thus, reducing boilerplate code is a must as your project grows.</p><p>In order to achieve good modularisation you shouldn’t need to import every single module just to create a parent object that uses two of them, so reducing these unused imports is a must in writing independent modules.</p><h4>Solution: Service Locator Pattern</h4><p>This is where the <strong><em>Service Locator</em></strong> pattern comes in, all objects have access to a <a href="https://refactoring.guru/design-patterns/singleton">singleton</a> dependency container<em> </em>and can request only the dependencies they need in order to function.</p><p>Testing these objects just involves providing the dependency, you can even enforce that tests cannot use <em>“real”</em> dependencies.</p><p>Using the Service Locator pattern our dependency graph looks more like:</p><blockquote>Parent<br> — Child1: A<br> — — Grandchild1: E<br> — — Grandchild2: B, C</blockquote><p>Particularly in large codebases this can be a Godsend, we can hide a lot of boilerplate code and focus on testing smaller pieces of code injecting the dependencies we need.</p><p>This is effectively what the @Environment and @EnvironmentObject property wrappers are in SwiftUI, you override the defaults for your previews and tests.</p><h4>Package: DependencyContainer</h4><p>I have created a <a href="https://github.com/cjnevin/DependencyContainer"><em>DependencyContainer</em></a> package which uses a property wrapper @Dependency that helps us keep our dependency graph lean like in the above example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24d99b8a20eb7b3f8eedc6dbf43a499f/href">https://medium.com/media/24d99b8a20eb7b3f8eedc6dbf43a499f/href</a></iframe><p>In our unit tests we could provide mocked versions of these dependencies, an example may be something like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ede1810c9897ab1a2f9aca915086df65/href">https://medium.com/media/ede1810c9897ab1a2f9aca915086df65/href</a></iframe><p>While, in our implementation we could provide the real dependencies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a47ce4cad44feb9cc8c467d16cb13ad9/href">https://medium.com/media/a47ce4cad44feb9cc8c467d16cb13ad9/href</a></iframe><h4>If you’re interested, I have created an <a href="https://github.com/cjnevin/IdealCleanArchitecture">example project</a> that goes over this, and many other concepts.</h4><h4>You can also include <a href="https://github.com/cjnevin/DependencyContainer">this package</a> in your own project.</h4><p><em>Thanks for reading and enjoy!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1405d17dcb92" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/problem-dependency-graph-hell-1405d17dcb92">Dependency Graph Hell (iOS)</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modular VIPER Architecture (iOS)]]></title>
            <link>https://medium.com/@cjnevin/modular-viper-architecture-9a7cdb7475f8?source=rss-79ea0cfb22d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a7cdb7475f8</guid>
            <category><![CDATA[viper-architecture]]></category>
            <category><![CDATA[swift-package-manager]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <dc:creator><![CDATA[Chris Nevin]]></dc:creator>
            <pubDate>Sun, 06 Nov 2022 00:25:54 GMT</pubDate>
            <atom:updated>2022-11-16T10:44:38.924Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OLG2ZUN_Vr3Ob3_jqd426A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@shutter_hunter?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Austin Lowman</a> on <a href="https://unsplash.com/s/photos/viper?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Enforcing boundaries with Swift Package Manager</p><h4>First, what does the acronym VIPER stand for?</h4><ul><li><strong>[V]iew</strong> — sends actions to <em>Presenter</em>, receives state from <em>Presenter</em>, receives navigation from <em>Router.</em></li><li><strong>[I]nteractor</strong> — talks with <em>Services</em> to access/modify entities, communicates changes back to <em>Presenter.</em></li><li><strong>[P]resenter</strong> — receives actions from <em>View</em> then delegates to <em>Router</em> or <em>Interactor</em>, sends new state to <em>View</em>.</li><li><strong>[E]ntity</strong> — simple data types used for communication with external dependencies.</li><li><strong>[R]outer</strong> — responsible for navigation between <em>Views.</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*C--c_IhxDzppx9AhOJnGIw.png" /></figure><h4>Concrete vs Abstract</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*j98xIMT-r31VXglUmKzH3A.png" /><figcaption>Uncle Bob’s Clean Architecture Diagram</figcaption></figure><p>If we look at Uncle Bob’s Clean Architecture concentric circles we can see that <strong>UI, DB, Devices, and External Interfaces </strong>live in the outer <em>blue</em> circle, these objects adhere to protocols defined by the <em>green</em> circle, communicating back and forth using <strong>entities</strong> defined in the <em>yellow</em> circle.</p><p>In relation to app development, <strong>UI</strong> could be a <em>UIViewController</em>, <strong>DB</strong> could be <em>CoreData</em>, <strong>External Interfaces</strong> could be <em>Bluetooth</em> or <em>CoreLocation</em>, <strong>Web</strong> could be our <em>NSURLSession</em>, and <strong>Devices</strong> could be <em>iPad, iPhone,</em> or <em>Watch</em>.</p><p>Therefore, we could divide this circle into two modules, the <em>blue</em> outer layer being the <strong>Config</strong> module that provides the concrete type for the platform, and the inner <em>green</em>, <em>red</em>, and <em>yellow</em> layers being the <strong>Core</strong> module that defines all of the business rules, interactions, and defines the abstract types that each <strong>Config</strong> module must inject.</p><h3>Enforcing Boundaries</h3><p>With <em>Swift Package Manager</em> we can enforce these boundaries in a single <em>Package.swift</em> like so:</p><ul><li><strong>Core</strong> — inner layers, contains abstract Services, concrete Interactor, concrete Presenter, concrete Entity, abstract Router.</li><li><strong>CoreTests</strong> — unit tests all concrete types using mocks/spies for all abstract types.</li><li><strong>Config</strong> — outer layer, contains our concrete implementations of the <strong>Core</strong> abstract types (i.e. ViewController, UserService, LoginService, LoginRouter, etc)</li><li><strong>ConfigTests</strong> — snapshot tests our views layout correctly, integration tests that our services implement their protocols correctly. Abstract dependencies are usually stubbed or mocked in this layer.</li></ul><h4>Example: Login Scenario</h4><p>Legend: ⭕️ — outer ring (Config), 🔘 — inner ring (Core)</p><p>Now that we’ve separated everything lets consider a user tapping the submit button on a ⭕️LoginViewController️.</p><p>The ⭕LoginViewController would create a 🔘LoginEntity containing the username and password and pass this to the 🔘LoginPresenter.</p><p>The 🔘LoginPresenter could perform <em>RegEx</em> validation on the email and call the 🔘AlertRouter presenting an alert if it fails validation, if it succeeds it would call the 🔘LoginInteractor with the 🔘LoginEntity which would in turn call the ⭕LoginService.</p><p>The ⭕LoginService would map the 🔘LoginEntity to a ⭕LoginRequest and create send it via a <em>URLSession</em> receiving a <em>JSON</em> ⭕LoginResponse, this response would then be mapped back to a 🔘UserEntity and returned to the 🔘LoginInteractor.</p><p>The 🔘LoginInteractor could then call the ⭕UserStorage service (doing it’s own mapping to our database types) then inform the 🔘LoginPresenter that we have logged in with a particular 🔘UserEntity.</p><p>The 🔘LoginPresenter could map this 🔘UserEntity to a 🔘UserViewModel and call the 🔘UserRouter to create a ⭕UserViewController displaying this 🔘UserViewModel.</p><p>Since our views and services are abstract, we could switch to a different view for <em>A-B testing</em> or change the storage used by our UserService from <em>Realm</em> to <em>CoreData</em> without having to touch any code in the <em>Core</em>.</p><p>This is the <strong>power</strong> of <em>Clean Architecture</em> when it is configured properly and concerns are kept separate.</p><h4>If you’re interested, I have created an <a href="https://github.com/cjnevin/IdealCleanArchitecture"><strong>example project</strong></a> that goes over this, and many other concepts.</h4><p><em>Thanks for reading!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a7cdb7475f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing Assert — My Wrapper Framework Around XCTest]]></title>
            <link>https://medium.com/better-programming/assert-my-wrapper-framework-around-xctest-7d6bea2d05f9?source=rss-79ea0cfb22d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d6bea2d05f9</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Chris Nevin]]></dc:creator>
            <pubDate>Tue, 01 Nov 2022 03:42:40 GMT</pubDate>
            <atom:updated>2022-11-02T05:04:36.612Z</atom:updated>
            <content:encoded><![CDATA[<h4>Write robust tests in iOS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KHg2Gm26JrD6Q7CwSPQs1A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@glenncarstenspeters?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Glenn Carstens-Peters</a> on <a href="https://unsplash.com/s/photos/test?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>XCTest feels like part of the Swift migration that has just never been cleaned up, it’s even unclear which order we should pass variables into things like XCTAssertEqual so often times it is flipped depending on who writes the tests:</p><pre>XCTAssertEqual(actual, expected)<br>XCTAssertEqual(expected, actual)</pre><p>So with that in mind, let’s split the assertion by creating a wrapper around the thing we want to assert. We’ll then write a simple function that returns our Assert object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a58b53cdeac91a5674b7675e4507411/href">https://medium.com/media/2a58b53cdeac91a5674b7675e4507411/href</a></iframe><p>Now we have the wrapper we can add some extensions, I’m going to lean heavily on XCAssert functions here but you could just as easily rely on throws.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/303b8c5fa83def9b73b4673cf7fd0929/href">https://medium.com/media/303b8c5fa83def9b73b4673cf7fd0929/href</a></iframe><p>Simple enough, at this point we can replace our XCTAssertEqual above with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a6504e20994551a06c33bd99cc76eb3/href">https://medium.com/media/0a6504e20994551a06c33bd99cc76eb3/href</a></iframe><p>That’s pretty nice, theres still a little more we could clean up, let’s introduce an operator.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f110525621913571a595be66b6b146a6/href">https://medium.com/media/f110525621913571a595be66b6b146a6/href</a></iframe><p>At this point you could stop, but what about when we want to deal with more complex types? Let’s add some support for closures and @dynamicMemberLookup.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51cfdb30a7bf9b2e3926e1fe82d7e6bd/href">https://medium.com/media/51cfdb30a7bf9b2e3926e1fe82d7e6bd/href</a></iframe><p>What does this allow us to do?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa79a109471dd76afc62249b248e65fd/href">https://medium.com/media/fa79a109471dd76afc62249b248e65fd/href</a></iframe><p>With our closure, we can assert values on an object more easily without having to do an assert on every field, we are given back an Assert&lt;User&gt; and can operate on all fields of the user using @dynamicMemberLookup.</p><p>If an assertion fails we will still see exactly which line it failed on thanks to file: StaticString = #fileand line: UInt = #line.</p><p>If you’re interested in this approach I’ve created a Swift Package which contains additional operators !=, &lt;=, &lt;, &gt;, &gt;=, !==, === and others. It also provides the textual representation if you prefer (i.e. greaterThanOrEqual(to: ...). The naming follows the XCTAssert naming.</p><p>Swift Package/more information: <a href="https://github.com/cjnevin/Assert">https://github.com/cjnevin/Assert</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d6bea2d05f9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/assert-my-wrapper-framework-around-xctest-7d6bea2d05f9">Introducing Assert — My Wrapper Framework Around XCTest</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[UIView/NSView Styling With @propertyWrapper]]></title>
            <link>https://medium.com/better-programming/view-styling-with-propertywrapper-92d8476e96a7?source=rss-79ea0cfb22d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/92d8476e96a7</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Chris Nevin]]></dc:creator>
            <pubDate>Fri, 21 Oct 2022 12:36:53 GMT</pubDate>
            <atom:updated>2022-11-06T17:25:47.924Z</atom:updated>
            <content:encoded><![CDATA[<h4>Separating styles from layout to make code more readable.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wXiJ6A2_i1755ZfD" /><figcaption>Photo by <a href="https://unsplash.com/@cristina_gottardi?utm_source=medium&amp;utm_medium=referral">Cristina Gottardi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It feels like a natural approach to move UIView style code away from the layout logic while also making the styles reusable.</p><p>Consider a standard UIViewController with some embedded layout code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0746cd228f1b3c7b93899b04dd05556/href">https://medium.com/media/d0746cd228f1b3c7b93899b04dd05556/href</a></iframe><p>We haven’t even gotten to the layout code and our view controller is already a mess.</p><p>People often break these out into smaller functions or write helper functions that extend UIView like .configure { } but even these leave us with the inevitable cruft.</p><p>I’ve also seen people solve this by creating subclasses of each view type which should only really be done if we are modifying behavior not just for moving some styling logic.</p><p>Some of the better projects I’ve worked on have stylesheets defined. So, each view initializer may take a Style&lt;UITextField&gt; or have an apply(Style&lt;UITextField&gt;) which are better approaches for sure — but it dawned on me, why not remove the need to have an initializer or a custom function and just use a @propertyWrapper?</p><blockquote>Each feature could have its own @propertyWrapper styles and shared styles could be put in a common package.</blockquote><p>The above code could be moved to a <em>Stylesheet</em> file with three @propertyWrappers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e575a45e755b9aa6a388284f1aee3054/href">https://medium.com/media/e575a45e755b9aa6a388284f1aee3054/href</a></iframe><p>We could re-use this SubmitStyle in another screen now that it’s extracted away from our LoginViewController.</p><p>Let’s look at our revised LoginViewController:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbaedfb4c32cff5f0d871a00f4fbd9b6/href">https://medium.com/media/dbaedfb4c32cff5f0d871a00f4fbd9b6/href</a></iframe><p>Well, that’s certainly a drastic improvement!</p><p>Our property wrappers even handle the initialization of our views and remove the need to specify the type.</p><p>What about when the state changes and we want to change style? That’s where I’d introduce a property in a subclass of the view or a view extension.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afbd7bc0149a8f0ee9e67c7f974f9fb7/href">https://medium.com/media/afbd7bc0149a8f0ee9e67c7f974f9fb7/href</a></iframe><p>This is similar to how other UI components work such as UIButton, you define each of the styles for the different states up front, then you set the state (i.e. isEnabled = false).</p><h4>Lazy</h4><p>There is one piece missing to the puzzle, lazy initialization of our views, so they are only created when our ViewController is ready to layout, such as after viewDidLoad.</p><p>In order to re-add this piece of functionality we’ll need to use a @Lazy property wrapper. As described in <a href="https://github.com/apple/swift-evolution/blob/main/proposals/0258-property-wrappers.md">swift proposal 0258</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36e59b46f924da0467f82ed61dc7a592/href">https://medium.com/media/36e59b46f924da0467f82ed61dc7a592/href</a></iframe><p>In order to keep the syntax concise we’ll need to wrap it’s initializer in a configure function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b3f0f9f7b6cf913fe7b233a76ca86cc/href">https://medium.com/media/1b3f0f9f7b6cf913fe7b233a76ca86cc/href</a></iframe><p>Let’s take a look at the above EmailStyle revised with lazy initialization.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/440976019f1e783e0fbbe873f398f9ec/href">https://medium.com/media/440976019f1e783e0fbbe873f398f9ec/href</a></iframe><p>Great! Now this FormTextField won’t be initialized until we first try to access it, which is typically inviewDidLoad.</p><p>I’ve created a project that includes this and other concepts <a href="https://github.com/cjnevin/IdealCleanArchitecture">here</a>.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92d8476e96a7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/view-styling-with-propertywrapper-92d8476e96a7">UIView/NSView Styling With @propertyWrapper</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Expressible Dynamic Phantom Types]]></title>
            <link>https://levelup.gitconnected.com/expressible-dynamic-phantom-types-513091b63f04?source=rss-79ea0cfb22d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/513091b63f04</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[expressiblebyliteral]]></category>
            <category><![CDATA[dynamic-member-lookup]]></category>
            <category><![CDATA[phantom-types]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Chris Nevin]]></dc:creator>
            <pubDate>Wed, 19 Oct 2022 14:27:18 GMT</pubDate>
            <atom:updated>2022-10-22T12:06:16.243Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JobvFlkFw_c_1fketmXhMw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@tandemxvisuals?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Tandem X Visuals</a> on <a href="https://unsplash.com/s/photos/ghost?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>A <strong>phantom type</strong> is a custom type that has one or more <em>unused</em> type parameters.</p><p>The simplest example would be this:</p><pre><strong>struct</strong> Phantom&lt;Context, WrappedValue&gt; {<br>  <strong>let</strong> wrappedValue: WrappedValue<br>}</pre><p>Why is this useful? It helps us ensure that developers can’t accidentally put an unexpected value in a field, for example putting a firstName in a lastName field could be restricted like so…</p><pre><strong>enum</strong> PhantomTypes {<br>  <strong>enum</strong> FirstName {}<br>  <strong>enum</strong> LastName {}<br>}</pre><pre><strong>typealias</strong> FirstName = Phantom&lt;PhantomTypes.FirstName, String&gt;<br><strong>typealias</strong> LastName = Phantom&lt;PhantomTypes.LastName, String&gt;</pre><pre><strong>struct</strong> Client {<br>  <strong>let</strong> firstName: FirstName<br>  <strong>let</strong> lastName: LastName<br>}</pre><h3>Type-Safety</h3><p>So now a developer can’t actually do firstName = lastName without the compiler throwing a type-mismatch error.</p><p>What if we had two entities with firstName properties? What’s to stop me setting a client’s firstName to a producer’s firstName? We can introduce nesting of the Phantom type on the first unused property.</p><pre><strong>enum</strong> PhantomTypes {<br>  <strong>enum</strong> FirstName {}<br>  <strong>enum</strong> LastName {}<br>}</pre><pre><strong>protocol</strong> FirstNameHaving {}<br><strong>extension</strong> FirstNameHaving {<br>  <strong>typealias</strong> FirstName = Phantom&lt;Phantom&lt;Self, FirstName&gt;, String&gt;<br>}</pre><pre><strong>struct</strong> Client: FirstNameHaving {<br>  <strong>let</strong> firstName: FirstName<br>}</pre><pre><strong>struct</strong> Producer: FirstNameHaving {<br>  <strong>let</strong> firstName: FirstName<br>}</pre><pre>client.firstName = producer.firstName <strong>// type-mismatch</strong></pre><p>This is great! We can ensure our values will be set correctly at compile-time without having to write any tests of our value mappers.</p><p>However, these are still a bit bulky to use. If you try to create a Producer above you’d have to write:</p><pre>Producer(firstName: FirstName(&quot;firstName&quot;))</pre><p>If only there was a way that we could hide away that we are using a custom type and just provide the guts to the firstName property...</p><h3>ExpressibleBy…Literal</h3><p>Thankfully, there is! Here’s an example of ExpressibleByStringLiteral.</p><pre><strong>extension</strong> Phantom: ExpressibleByStringLiteral <strong>where</strong> WrappedValue: ExpressibleByStringLiteral {<br>  <strong>init</strong>(stringLiteral value: StringLiteralType) {<br>    <strong>self</strong> = <strong>Self</strong>(WrappedValue(stringLiteral: value <strong>as</strong>! WrappedValue.StringLiteralType))<br>  }<br>}</pre><p>Now we could write the above initializer like:</p><pre>Producer(firstName: &quot;firstName&quot;)</pre><blockquote>Note: It’s still a FirstName and you can still pass in a FirstName object.</blockquote><p>There’s still one downside, if we wanted to check if the firstName was not empty (for example) we’d have to write something like:</p><pre>producer.firstName.wrappedValue.isEmpty</pre><p>It would be great if we could get rid of that wrappedValue so our use of phantom-types are transparent…</p><h3>@dynamicMemberLookup</h3><p>Syntactic sugar completes the final piece of the puzzle, here’s how we could add it to our Phantom struct:</p><pre><strong>@dynamicMemberLookup<br>struct</strong> Phantom&lt;Context, WrappedValue&gt; {<br>  <strong>var</strong> wrappedValue: WrappedValue<br>  <strong>init</strong>(_ wrappedValue: WrappedValue) {<br>    <strong>self</strong>.wrappedValue = wrappedValue<br>  }</pre><pre><strong>  subscript</strong>&lt;T&gt;(dynamicMember member: KeyPath&lt;WrappedValue, T&gt;) -&gt; T {<br>    <strong>get</strong> { <strong>return</strong> wrappedValue[keyPath: member] }<br>  }<br>}</pre><p>This allows us to access the properties of the WrappedValue directly from the Phantom type, for example:</p><pre>producer.firstName.isEmpty</pre><h3>@propertyWrapper</h3><p>We can take this one step further by introducing @propertyWrappers which take a WrappedType.</p><pre><strong>struct</strong> Producer: FirstNameHaving {<br>  <strong>@Truncated</strong>(maxLength: 10) <br>  <strong>var</strong> firstName: FirstName<br>}</pre><pre>producer.firstName = &quot;Christopher&quot;<br>print(producer.firstName) // &quot;Christophe&quot;</pre><p>Thanks for reading!</p><p>I’ve created a Swift Package which contains the above plus many more protocol conformances, check it out… <a href="https://github.com/cjnevin/PhantomTypes">https://github.com/cjnevin/PhantomTypes</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=513091b63f04" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/expressible-dynamic-phantom-types-513091b63f04">Expressible Dynamic Phantom Types</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AutoLayoutBuilder —My Swift Package to Reduce Boilerplate Code]]></title>
            <link>https://medium.com/better-programming/autolayoutbuilder-294badac5015?source=rss-79ea0cfb22d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/294badac5015</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Chris Nevin]]></dc:creator>
            <pubDate>Thu, 06 Oct 2022 13:37:24 GMT</pubDate>
            <atom:updated>2022-10-24T11:54:50.047Z</atom:updated>
            <content:encoded><![CDATA[<h4>Leverage @resultBuilder to create a DSL for UIView constraints</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yTYKV0g80XLro3Wm_H178A.jpeg" /></figure><p>We are going to solve a few problems with this DSL:</p><ol><li>Setting <a href="https://developer.apple.com/documentation/uikit/uiview/1622572-translatesautoresizingmaskintoco">translatesAutoresizingMaskToConstrants</a> to false</li><li>Repeating the same anchor twice</li><li>Repeating the same constant multiple times</li><li>Code structure: Layout code can be all over the place, this DSL aims to solve that through the use of nesting</li></ol><p>Typically, when using auto-layout we have many blocks of code like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34bf68012a5c3c8c9dda94fd63232896/href">https://medium.com/media/34bf68012a5c3c8c9dda94fd63232896/href</a></iframe><p>This is already starting to become hard to read and we’ve only added one view, what happens when we have 10 views?</p><p>No wonder developers hate it when they need to hunt down an auto-layout bug, there’s so much reading involved!</p><p>Most developers are lazy. With that in mind, let’s remove all of the cruft and make this more succinct:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73e89ba5b7390e83672157b6745154e9/href">https://medium.com/media/73e89ba5b7390e83672157b6745154e9/href</a></iframe><p>Let’s see how we can achieve this…</p><p>First, we’ll need is a way to refer to singular and arrays of NSLayoutConstraints in the same block, we can do this with a protocol.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f2e93466eeceed490f8df98141ef20a/href">https://medium.com/media/9f2e93466eeceed490f8df98141ef20a/href</a></iframe><p>Second, the addSubview is utilising a @resultBuilder which allows us to collect all of the NSLayoutConstraints we want to apply.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82d573924b5d9e2e6bbc7d3fe3663406/href">https://medium.com/media/82d573924b5d9e2e6bbc7d3fe3663406/href</a></iframe><p>At this point we actually have all we need to do something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e761a6e29612b36b86ba7927b057e5f/href">https://medium.com/media/0e761a6e29612b36b86ba7927b057e5f/href</a></iframe><p>That’s already a massive improvement over what we had at the beginning, but let’s continue…</p><p>In order to make our constraints more readable we’re going to need to store some information about them, for the sake of this example I’m just going to reference the four edge constraints we are going to use.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b9d4f3e3d5ed418147cf633ed6c90e5/href">https://medium.com/media/5b9d4f3e3d5ed418147cf633ed6c90e5/href</a></iframe><p>That provides some anchors that we can now reference/combine in our ConstraintBuilder, lets implement the ConstraintBuilding protocol first…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/903b32e833c8a2ffa8aade585cedc012/href">https://medium.com/media/903b32e833c8a2ffa8aade585cedc012/href</a></iframe><p>There you can see our anchors being used in those 4 functions, by putting this in a protocol we can extend other types with build this allows us to chain the constraints (i.e. .leading().trailing()).</p><p>Now let’s implement this protocol in our ConstraintBuilder struct. For the sake of this article, I’m just going to simplify this and just create the equalToSuperview() function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95a10b127bd4f4de834033e4f1df3ae5/href">https://medium.com/media/95a10b127bd4f4de834033e4f1df3ae5/href</a></iframe><p>In the above example you can see we can combine with another constraint inside our build function, this is what allows us to chain our constraints. We can now layout our redView like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56210add8a87fbbfe98af874e88e8256/href">https://medium.com/media/56210add8a87fbbfe98af874e88e8256/href</a></iframe><p>Since all of these values are 20 we could combine this into a single function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d81099fe7d46489a0eae955be3907ed4/href">https://medium.com/media/d81099fe7d46489a0eae955be3907ed4/href</a></iframe><p>Now we can do what we set out to do:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52fb0bd1150fa9cbd4b22783642e3e00/href">https://medium.com/media/52fb0bd1150fa9cbd4b22783642e3e00/href</a></iframe><p>We can actually nest these calls as well:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ba3a02c624073e2023d3527a9fd0746/href">https://medium.com/media/1ba3a02c624073e2023d3527a9fd0746/href</a></iframe><p>Thanks for reading!</p><p>If you’re interested in including it in your own project, there is information about the Swift Package below, it allows you to write even more succinct code with relative constraints like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b30a88e5f833028f5c094cd2779040c3/href">https://medium.com/media/b30a88e5f833028f5c094cd2779040c3/href</a></iframe><h3>Swift Package</h3><p>The Swift Package contains vastly more functionality than described above, things like:</p><ul><li>Configuration blocks within @AutoLayoutBuilder blocks</li><li>Constraint chaining before calling an equalTo function</li><li>Various equalTo functions that allow us to link to UILayoutGuide or other views.</li><li>[NSLayoutConstraint] storage via the store(in:) function</li><li>Operators (==, &lt;=, &gt;=) to clean up layout code</li><li>Setting multipliers for NSLayoutDimensions</li><li>Setting UILayoutPriority during constraint creation</li><li>Targeted management of constraints within [NSLayoutConstraint] arrays identified using NSLayoutConstraint.Attribute (setting constant, priority)</li><li>…and much more!</li></ul><p>Package: <a href="https://github.com/cjnevin/AutoLayoutBuilder">https://github.com/cjnevin/AutoLayoutBuilder</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=294badac5015" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/autolayoutbuilder-294badac5015">AutoLayoutBuilder —My Swift Package to Reduce Boilerplate Code</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing Valuable Tests]]></title>
            <link>https://levelup.gitconnected.com/writing-valuable-tests-591f5e4d2895?source=rss-79ea0cfb22d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/591f5e4d2895</guid>
            <category><![CDATA[mocking]]></category>
            <category><![CDATA[snapshot-testing]]></category>
            <category><![CDATA[bdd]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Chris Nevin]]></dc:creator>
            <pubDate>Thu, 30 Jan 2020 10:50:23 GMT</pubDate>
            <atom:updated>2020-01-31T13:34:19.061Z</atom:updated>
            <content:encoded><![CDATA[<h4>The best tests do not tie your code to your tests.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WiR1hoY2Ncy3NfQcmSh1RA.jpeg" /></figure><p>Below I compare my opinion on two common testing mindsets. One focuses on writing tests first, the other focuses on writing tests last.</p><h3><strong>Test driven development</strong></h3><p>TDD requires that you write a test for each function and first make it <em>fail</em>, then implement the logic to make it <em>pass</em>.</p><p>These tests <em>usually</em> don’t cover multiple objects at once as the cognitive load for writing a test that does so <em>may</em> be too great.</p><p>As a result, these tests <em>can</em> be too granular resulting in code that is tied directly to your tests.</p><p>This makes any future refactoring attempt extremely dangerous incurring a high maintenance cost, consider the following:</p><ul><li>What happens if a new object is added to the object graph?</li><li>What if an object adds or removes a variable?</li><li>What if we need to move some logic around as it no longer makes sense where it is?</li></ul><p>These are all major changes to the system and may break tens if not hundreds of unit tests (and initializers) resulting in:</p><ul><li>Large pull requests (your poor colleagues!)</li><li>Loss of confidence. How can we guarantee the behavior is identical if the code and the tests have changed? <em>Spoiler:</em> we can’t, we probably need to do a regression now (your poor colleagues!)</li><li>Loss of time. This causes a significant expense for your employer/client in maintaining tests. We should be focusing on new features and bugfixes not rewriting assertions.</li></ul><h3>Behavior driven development</h3><p>After considering some of the pitfalls of TDD, I would argue that thinking with a BDD mindset is much more efficient and effective as it focuses on:</p><ol><li>Where to start in the process</li><li>What to test and what not to test</li><li>How much to test in one go</li><li>What to call the tests</li><li>How to understand why a test fails</li></ol><p>The following approaches cover all of the above and defend against changes to underlying objects/logic.</p><h4>Testing UI</h4><p>If the behavior you’re testing has a visual effect you should be testing the view layer with snapshot tests (where you take a screen capture for each change to the screen).</p><p>This means you can refactor all of your business logic, model objects, and side-effects and still be guaranteed that your view behaves correctly in all the scenarios that can affect its presentation.</p><p>Imagine you have a toggle on the screen and when toggled on it expands to reveal additional options; you can snapshot the off and on states and check that the image is correct.</p><p>If the UI changes or the business logic changes your test will fail and you can view the difference between the recorded image and the failed image. This will help you narrow down which part of the code has changed at a glance.</p><p>In my opinion, these are the most valuable tests as you can validate the layout of the screen and behavior at the same time, as a bonus — since they are unit tests they also run faster than automation tests.</p><h4>Testing Side-Effects</h4><p>There is usually no value in testing that an underlying framework behaves correctly, these tests <em>should</em> already be covered by the framework’s test suite.</p><p>Therefore, following the dependency inversion principle, we should be writing an interface for each dependency to allow us to inject a mock/spy in place of a framework in order to test the business logic of our side-effects.</p><p>We can then mock the result of things like API calls or storage of a particular object returning each success/failure value possible. We can also write spies to record when each of the functions is executed and assert they are executed in the correct sequence and with the correct data.</p><h3>Conclusion</h3><p>I hope this brief comparison has opened your eyes to some of the issues that writing granular tests may cause and has at least helped you to question what sort of tests are valuable.</p><p><strong>iOS developers:</strong> There is a <a href="https://github.com/pointfreeco/swift-snapshot-testing">great framework</a> from PointFree for snapshot testing and they go in depth on how to use it in <a href="https://www.pointfree.co/episodes/ep86-swiftui-snapshot-testing">this episode</a>. You can even extend the library to test whatever you like.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=591f5e4d2895" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/writing-valuable-tests-591f5e4d2895">Writing Valuable Tests</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>