<?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 Chloe Houlihan on Medium]]></title>
        <description><![CDATA[Stories by Chloe Houlihan on Medium]]></description>
        <link>https://medium.com/@chloehoulihan?source=rss-a96544aecefb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XzqRYLlBAs2yRCsPCAdscw.jpeg</url>
            <title>Stories by Chloe Houlihan on Medium</title>
            <link>https://medium.com/@chloehoulihan?source=rss-a96544aecefb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 19:50:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chloehoulihan/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[SwiftUI MVVM: Separation of Concerns]]></title>
            <link>https://medium.com/@chloehoulihan/swiftui-mvvm-separation-of-concerns-d30cff504674?source=rss-a96544aecefb------2</link>
            <guid isPermaLink="false">https://medium.com/p/d30cff504674</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[mvvm-architecture]]></category>
            <category><![CDATA[solid-principles-in-swift]]></category>
            <category><![CDATA[mvvm]]></category>
            <dc:creator><![CDATA[Chloe Houlihan]]></dc:creator>
            <pubDate>Mon, 19 May 2025 09:47:38 GMT</pubDate>
            <atom:updated>2025-05-19T09:47:38.641Z</atom:updated>
            <content:encoded><![CDATA[<p>How to do true MVVM in SwiftUI and handle communications between views — and why.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AEfetlmpZ5LIPObA" /><figcaption>View, ViewModel and Model — ChatGPT Generated</figcaption></figure><h3>What is MVVM?</h3><p>This is a pattern for front-end features that prioritises separating UI, functionality and data.</p><h4>View (V)</h4><p>Your ditsy blonde. <em>I am a ditsy blonde, so I’m allowed to say that.</em> She should just focus on looking good. Any logic, decisions, thinking — leave that to the VM. He knows what do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*BKALiiPefMPgYYy_.gif" /></figure><h4>View Model (VM)</h4><p>This guy, amirite? I don’t want to be sexist, but it’s definitely a guy. I’m pretty sure he’s rich coz the View just does everything he says. They’re inseparable, she can’t be without him. He doesn’t even seem to notice her — it’s like he doesn’t know she’s there. Pretty unhealthy relationship, but it works really well. Each to their own, I guess.</p><h4>Model (M)</h4><p>This isn’t a person. Sorry, that’s probably really non-PC (“Models are people too!”) but, seriously, this is just data. It doesn’t <em>do</em> anything, it just… exists. The VM carries it everywhere trying to explain it to the View but she just kind of pins it on the fridge and says “very nice”. Looks good there, tbf.</p><h4>What are you talking about?</h4><p>Okay, so I like metaphors.</p><p>This is my way of getting you to remember that the View has only UI code — like makeup. import SwiftUI, know what I mean? 🤨</p><p>The VM has <em>no</em> UI code — he looks weird in makeup (no import SwiftUI here 😑). The VM handles <em>all</em> logic, however basic. The VM takes data, logic, decisions and serves them up to the View in a simple, stripped-down way (so she can understand, bless her). Also — the View “knows” about the VM, but the VM knows nothing of the View. This is the blindest date ever.</p><p>The model — that’s just fancy speak for data. Got some data from an API? That’s a model. Got a struct? That’s a model. (<em>Yes, I know views are structs, shut-up</em>). The model doesn’t think — so it knows nothing about the VM or the View.</p><h3>Why do MVVM?</h3><p>We’ve separated the UI, logic and data completely. I guess it’s decoupled now, but so what? Why are we doing all of this?</p><h4>1. Coupling/Cohesion</h4><p>Obvious one. Each bit of code is concerned with one thing and sticks to it. The code is “cleaner”, easier to maintain, less likely to get bugs or grow into an unscalable monster.</p><h4>2. Reusability/Maintainability/Testability</h4><p>Sub out any view, VM or model and everything will still work. This makes future rewrites a breeze. It also makes automating regression testing for rewrites possible.</p><p>I can test the View by shoving in a mock VM. I can test the VM by shoving in mock Models/Data Providers. I can simulate edge cases in data or network seamlessly.</p><h4>3. Single-Directional Data Flow</h4><p>Model -&gt; VM -&gt; View. Simple. No data races. No witchcraft here.</p><h4>4. State Management</h4><p>This is one of the biggest reasons beyond “it’s nice and tidy”. By keeping data and logic out of the view, we ensure that the view isn’t “refreshing” the data and resetting the state. We can also ensure the view only updates when we’re ready for the changes to show.</p><h3>How to do MVVM in SwiftUI</h3><h4>1. ObservedObject vs StateObject</h4><p>The rich VM guy owns everything. The ditsy blonde only owns makeup.</p><p>That’s why we use @ObservedObject to attribute the VM — the caller owns the VM and maintains its reference. The View just watches it (starry-eyed).</p><p>@StateObject (similarly to @State) is created and owned by the View. This is useful if we’re talking about a small, self-contained component — like a reusable button that has some logic. But for full feature views where we want MVVM, we don’t want the view managing nor owning the data/logic.</p><p>She’ll just do it wrong anyway… Forget to pay the bills or something…</p><pre>public struct DitsyBlonde: View {<br>  @ObservedObject private var viewModel: NerdyViewModel<br><br>  init(viewModel: NerdyViewModel) {<br>    self.viewModel = viewModel<br>  }<br>}</pre><p>Anyway, this helps maintain state between navigation and allows you to pass the same VM between views safely. It gives all the power to the navigation/app layer — that’s the government in our metaphor. The tax man controls the cleverclogs.</p><h4>2. ObservableObject and Publishers</h4><p>We’ve hooked the VM into the View. She’s watching him all lovingly, waiting for orders and guidance. Let’s get Nerdy McNerdface ready for his date.</p><pre>public class NerdyViewModel: ObservableObject {<br>  // Stuff we want Ditsy Blonde to see<br>  @Published public let header: String<br>  @Published public private(set) var dumbedDownData: [DumbDatum]<br><br>  // Stuff she shouldn&#39;t worry her pretty little head about<br>  private let dataProvider: DataProviding // Handle fetching data from an API<br>  private var cleverData: [Datum] // Datum has extra data we need, but the view doesn&#39;t need to show<br><br>  public init(dataProvider: DataProviding,<br>              otherDependencies: OtherDependencies) {<br>    ...<br>  }<br>}</pre><p>He’s ignoring his date, but she can still see him. He should make sure the stuff that matters looks good. We make these bits@Published so the view updates whenever it changes. E.g. He gets more money, she layers on the makeup in hopes of a diamond ring.</p><h4>3. Models</h4><pre>public struct DumbDatum: Identifiable {<br>  public let id: UUID()<br>  public let imageName: String<br>  public let title: String<br>}<br><br>struct Datum: Codable {<br>  let header: String<br>  let description: String // UX decided we don&#39;t need to show this<br>  let metadata: [String: Any]?<br>  let timestamp: TimeInterval // Need this for some clever stuff<br>  ... // Assume there&#39;s tons of metadata we don&#39;t show, but we do use.<br>}</pre><p>Ditsy Blonde doesn’t really understand McNerdface’s job, so he doesn’t talk about that stuff. All that data handling? Right over her head! He simplifies stuff when he speaks so she just gets what she needs. When he completes a complex operation in Dubai with huge compliance complications, she just needs to know that as a result they have a new living room that needs painting. She’s good at that.</p><p>In case I’ve lost you — keep the data you expose to the view as minimal as possible. If the view can’t display it exactly as it is, your VM should be processing/transforming it so the view can. Don’t just publish everything.</p><p>Only give Blondie what you want her to pin on the fridge — not all the company’s classified papers!</p><h4>4. Handlers</h4><p>Okay — Ditsy Blonde and Nerdy McNerdyface are all married, they’ve have a beautiful model garden; everything’s going nicely.</p><p>Now Ditsy gets a bill through. She needs Nerdy to pay it. She’s too dumb to ask “Would you pay the council tax bill? Don’t forget to set-up the direct debit” — she just hands him the invoice and says “Handle this”.</p><pre>// In the View<br>Button(action: viewModel.handleTapPrimaryButton) {<br>  Text(viewModel.primaryButtonTitle)<br>}</pre><p>Your VM should name its public-facing API — the bit the view uses — as generically as possible. Instead of payCouncilTax, consider some consistent format such as handle&lt;Action/Event&gt;&lt;Component?&gt;:</p><ul><li>handleTapPrimaryButton</li><li>handleTapSecondaryButton</li><li>handleOnAppear</li><li>handleScroll(to: Index)</li></ul><p>Maybe consider having an event Enum: handle(event: Event). Alternatively, on&lt;Action&gt;&lt;Component?&gt; or however you want to do it.</p><p>It’s ideal if this is consistent through-out the VM.</p><h3>Join us next episode</h3><p>Follow my articles to find out what to do when Ditsy and Nerdy McNerdface have kids! How to create child MVVMs (👀) and look after them — without creating strong reference cycles.</p><p>Please comment and let me know if you enjoy this format! I know I have a “unique” writing style but I’m always looking to improve it in a way that helps you remember the important stuff, as that’s what these are all about.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d30cff504674" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Legacy Code: Save Your Swift]]></title>
            <link>https://medium.com/@chloehoulihan/legacy-code-save-your-swift-d185204e01ce?source=rss-a96544aecefb------2</link>
            <guid isPermaLink="false">https://medium.com/p/d185204e01ce</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[decoupling]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[protocol-oriented]]></category>
            <category><![CDATA[solid-principles-in-swift]]></category>
            <dc:creator><![CDATA[Chloe Houlihan]]></dc:creator>
            <pubDate>Fri, 16 May 2025 16:21:21 GMT</pubDate>
            <atom:updated>2025-05-16T16:21:21.203Z</atom:updated>
            <content:encoded><![CDATA[<p>We’ve all landed in a team with a mess of legacy code. Luckily, Swift is Protocol Oriented Programming.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*A8_9MGDe6oJgiwn_.jpg" /><figcaption>We can’t rewrite it but we can lock it away forever — Credit: <a href="https://www.dreamstime.com/illustration/broken-door.html">https://www.dreamstime.com/illustration/broken-door.html</a></figcaption></figure><p>Ah, brand new job, brand new codebase, brand new — Oh dear god there’s singletons and coupling everywhere! Who wrote this? Where do I even start? I’ll have to write demon code just so it can work with this evil.</p><p>Not so! Protocols aren’t just for testability. They allow you to completely decouple modules of new code from legacy nightmares alongside dependency injection.</p><h3>Step 1 — Run away</h3><p>Let’s go to a nice new Swift Package and start writing our new feature. Enjoy the speedy build times of the Previews, live-coding your way to a tidy, snappy feature.</p><h3>Step 2 — It’s all a façade</h3><p>Every time you think “Oh, I’m going to need to bring that in from the app” — stop. It’s protocol time. Try to keep your naming as generic as possible. Don’t be tempted to keep any poor function/class names from the legacy code.</p><pre>// In my Swift Package<br><br>public enum NewError: Error {<br>  // Define the errors we actually want to receive<br>  // How much granuality do we want? Make the caller do the work.<br>  case knownError<br>}<br><br>public protocol DataProviding {<br>  func fetchData() async -&gt; Result&lt;Datum, NewError&gt;<br>}<br><br>public class NewFeature {<br>  private let dataProvider: DataProviding<br>}</pre><p>Okay, now we can create a mock DataProvider for now and keep coding. Other examples might be PermissionsManaging or FunctionsProviding.</p><p>These protocols act as a façade between our new feature, and complex manager classes or singletons that might manage multiple concerns.</p><h3>Step 3 — Collecting our belongings</h3><p>Time to collect our stuff from that ex-boyfriend’s house. I want to talk to him as little as possible so I’m just going to go in, grab what I need for the protocol, and get out. I don’t want to see what he’s done with the flat, I’m not cleaning the dishes while I’m there — I’m done with that legacy code!</p><pre>// In my main app code<br>// This is a bit like a Façade crossed with a Bridge<br><br>import NewFeature<br><br>class NewFeatureDataProvider: DataProviding {<br>  func fetchData() async -&gt; Result&lt;Datum, NewError&gt; {<br>    // Call any legacy code here and wrap up the result all tidy.<br>    // This is also a good oppotunity to convert any <br>    // completion blocks to async instead.<br>    do {<br>      try EwGrossSingleton.shared.getSomethingThatThrows()<br>      return .success(EwGrossSingleton.shared.savedData)<br>    } catch let error {<br>      // Grab this and make a useful result in a known format<br>      return .failure(.knownError)<br>    }<br>  }<br>}</pre><h3>Step 4 — Serve the papers</h3><p>Final step in the divorce. I don’t even have to see my Ex because of this great new lawyer I hired (`NewFeatureDataProvider`) who does everything for me.</p><pre>let dataProvider = NewFeatureDataProvider()<br>let newFeature = NewFeature(dataProvider: dataProvider)</pre><h3>Maintainability</h3><p>The great thing is if we ever get given sprint scope to handle some tech debt (yeah, right) then we can go straight into NewFeatureDataProvider and rewrite those function bodies one at a time, as and when we can. No need to run around our new features chasing knock-on effects.</p><h3>Scalability</h3><p>Let’s say you lived with your Ex for years. You need the sofa, TV, all the kitchen stuff, and he needs to keep signing the child support forms every month.</p><pre>// MARK: - In my Package<br><br>public protocol SigningManaging { }<br><br>public protocol SofaProviding { }<br><br>public protocol KitchenUtensiling { }<br><br>public protocol TVWatching { }<br><br>// Some more real-life examples would be: PermissionsProviding, <br>// NetworkManaging, NavigationHandling, NewFeatureCoordinating,<br>// UserProfileManaging, NotificationManaging, ThirdPartyLibraryManaging<br><br>// MARK: - In my App<br><br>// Optionally, also `extension NewFeature`<br>class NewFeatureBuilder {<br>  static func build() -&gt;  {<br>    let signer = SigningManager()<br>    let sofa = SofaProvider()<br>    let utensils = KitchenUtensils()<br>    let tv = TVWatcher()<br><br>    return NewFeature(signer: signer,<br>                      sofa: sofa,<br>                      utensils: utensils,<br>                      tv: tv)<br>  }<br>}</pre><p>Phew! Now all that paperwork is tucked away in my Builder pattern. My desk is clear, I don’t need to see my Ex ever again, and I’m going out for a cocktail with the gals! 🍸</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d185204e01ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Success: You’re wrong about almost everything]]></title>
            <link>https://medium.com/the-tech-collective/success-youre-wrong-about-almost-everything-4c64be5d9119?source=rss-a96544aecefb------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c64be5d9119</guid>
            <category><![CDATA[career-advice]]></category>
            <category><![CDATA[success]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[modern-workplace]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Chloe Houlihan]]></dc:creator>
            <pubDate>Thu, 04 Apr 2024 11:15:43 GMT</pubDate>
            <atom:updated>2024-04-04T15:36:41.039Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why working long hours and being in the office is not the key to success as a software engineer and may actually stunt your growth</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/0*hwgO25IKhVbtHSY5.jpg" /><figcaption>Hugh Macleod, GapingVoid</figcaption></figure><blockquote>“So these high-level sociopaths overpromote a handful of low-level losers who put forth disproportionate amounts of effort. These former losers enter the clueless ranks of middle management to act as a buffer.<br>…<br>The clueless believe that they’re on track to be CEO while the losers and sociopaths both know that’s absurd.” — Erik Dietrich, <a href="https://daedtech.com/developer-hegemony-the-crazy-idea-that-software-developers-should-run-software-development/">Developer Hegemony: The Future of Labor</a></blockquote><p>“Work hard, put in the hours, keep your head down, forget this remote-working nonsense, get in the office and make an impression!” These, the words of the 156-year-old gentleman on the stage. He takes a shaky bow and hobbles off the stage to his wheelchair made out of solid gold and upholstered with Her late Majesty’s purple face. The audience stands up and applauds, utterly beguiled by the incredible motivational advice that had been bestowed upon them.</p><p>We’ve probably all heard a similar speech before, perhaps from our parents, perhaps from <a href="https://medium.com/@TheChosenPen/the-ugliness-of-don-draper-a11413145e68">Don Draper</a>. This is how we succeed. Grind away.</p><p>Or at least, it <em>was</em>. When work consisted of mining coal and washing laundry.</p><p>Then, along came the <a href="https://www.ibm.com/blog/what-is-a-knowledge-worker-and-what-do-they-do/#:~:text=A%20knowledge%20worker%20is%20a,critical%20thinking%20and%20interpersonal%20skills">knowledge workers</a>.…</p><h3>The First Lie — Remote working is bad, mkay</h3><p>We’ve heard a lot about remote working recently. The pandemic made it standard working practice for a decent chunk of time. The Don Drapers think this is awful — and, to be fair, when the waitress at my local coffee shop worked from home, my coffee was distinctly more hypothetical than I would have liked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/0*U6BL1V6DGyF678wj.jpg" /><figcaption>Mr Mackey — South Park</figcaption></figure><p>However, these <a href="https://www.merriam-webster.com/dictionary/Luddite#:~:text=Ludd%C2%B7%E2%80%8Bite%20%CB%88l%C9%99%2D%CB%8Cd%C4%ABt,Luddite%20adjective">luddites</a> are wrong.</p><p><a href="https://www.shakebugs.com/blog/why-let-developers-work-remotely/#:~:text=The%20study%20found%20that%2068,productive%20in%20an%20office%20setting">68% of software developers are more productive at home</a>. In fact, when interrupted (common in an office setting), developers take <a href="https://blog.ninlabs.com/2013/01/programmer-interrupted/#:~:text=A%20programmer%20takes%20between%2010%2D15%20minutes%20to%20start%20editing%20code%20after%20resuming%20work%20from%20an%20interruption.">10–15 minutes</a> to start writing code again. Workers only spend <a href="https://www.vouchercloud.com/resources/office-worker-productivity">just shy of 3 hours</a> being productive in the office.</p><p>Not to mention how inefficient and unproductive commutes are, before adding on the mental degradation they impose.</p><h3>The Second Lie — Grind</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/0*tuPaXhbvYFOhQH7I" /><figcaption>“The Ladder” — iStock</figcaption></figure><p>There’s three ways to get into top positions:</p><ol><li>Start your own company</li><li>Jump across from the same position in another company</li><li><a href="https://hbr.org/2015/04/why-some-men-pretend-to-work-80-hour-weeks#:~:text=Two%20Strategies%20for%20Cutting%20Back">Cheat</a></li></ol><p>However, when asked, the nobility who actually reside in this tier of business will invariably respond “just work hard and climb up the ladder”.</p><p>Having never climbed up a real ladder in their lives, it would be easy to forgive these corporate viscounts their naivety — perhaps they simply don’t know what a ladder looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vPhtdBe0RRv0ZIdn" /><figcaption>Actual corporate ladder — Image by <a href="https://www.deviantart.com/sirinkman/gallery">SirInkman</a></figcaption></figure><p>The truth is the path to aristocracy is a classic dungeon. If you’re savvy (or lucky); if your risk appetite is healthy; if your satchel is full of useful items, there’s a shortcut. Normally by speaking to some wizard or thinking of an approach the dungeon master didn’t. And that’s where the metaphor begins to shake apart…</p><p>Some of the viscounts started their own companies, some jumped up the ladder at one or more points via various means.</p><p>Some used a cheat code.</p><p>They were handed an opportunity (<em>starter_chest=true</em>), they joined a company when there were only 10 employees (<em>difficulty_mode=easy</em>), they got their dad’s mate to invest (<em>difficulty_mode=peaceful</em>), they stole a job from someone on mat leave (<em>w*nker_level=9000</em>)…</p><blockquote>“Productivity per hour decline sharply when a person works more than 50 hours a week. After 55 hours, productivity drops so much that putting in any more hours would be pointless. And, those who work up to 70 hours a week are only getting the same amount of work done as those who put in the 55 hours.” — <a href="https://docs.iza.org/dp8129.pdf">Stanford</a></blockquote><p>A small amount of highly efficient time working is far more productive than long working hours. The dozen countries that rank higher than the USA for productivity (and no, the UK is not one) have less annual working hours.</p><blockquote>“All 12 countries that ranked ahead of the U.S. [for productivity] have employees who work fewer hours annually than U.S. employees. For example, Germany has the fewest annual working hours at 1,340.9 yet still produces $47.09 per person per hour.</blockquote><blockquote>On the flip side, some of the countries with the most hours worked produced the least amount of money per person, per hour.” — <a href="https://www.businessnewsdaily.com/9302-hours-worked-productivity.html">Business News Daily</a> reporting on Expert Market research, 2022</blockquote><p>Additionally, happy workers are <a href="https://www.ox.ac.uk/news/2019-10-24-happy-workers-are-13-more-productive">13% more productive</a> per hour. This means work-life balance, healthy eating, exercise, green-space time, hobbies and spending time with friends and family. Not working an extra hour or two a day, for some reason.</p><h3>The Truth: You’re the Problem</h3><p>The truth is (and please tell them this to their faces) these kings of commerce are the problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*sw_V1UVhMX9cyKTs" /><figcaption>Accurate reconstruction of “successful” people discussing the performance of company employees — Source OP unknown</figcaption></figure><p><a href="https://hbr.org/2015/08/the-research-is-clear-long-hours-backfire-for-people-and-for-companies">Research shows that</a>, although workers’ perceivable outputs don’t change when they reduce their hours, <a href="https://hbr.org/2015/04/why-some-men-pretend-to-work-80-hour-weeks#:~:text=Others%20were%20more%20transparent%20about%20their%20difficulties%2C%20and%20asked%20the%20firm%20for%20help%20in%20pulling%20back.%20Their%20efforts%20resulted%20in%20harsh%20penalties%20and%20marginalization.%C2%A0">managers penalise them anyway</a> if those workers express a desire to pull back.</p><blockquote>“By using local clients, telecommuting, and controlling information about his whereabouts, [Lloyd] found ways to work and travel less, without being found out. He told me: “I skied five days last week. I took calls in the morning and in the evening but I was able to be there for my son when he needed me to be, and I was able to ski five days in a row.” […] Despite his deviance from the ideal worker expectation, however, senior colleagues viewed him as a star; indeed, one Partner described him to me as a “rising star,” who worked “much harder than” he himself did.” — <a href="https://hbr.org/2015/08/the-research-is-clear-long-hours-backfire-for-people-and-for-companies">Harvard Business Review</a></blockquote><p>Not only do these successful dukes lie to the commoners about how long and hard they’ve worked, they lie to themselves. They’ve convinced themselves that this is true to the point that they are certain that others doing well must have followed this deeply faulted advice to a tee. In fact, if someone doing well tells Sir Worksalot they work <em>less</em> hours than most, they must therefore not be doing well at all, and should be marked down and admonished.</p><h3>More Lies</h3><p>Hopefully, by now you’re thinking “Great! I’ll just tell my company there’s clear evidence for working less hours with less distractions — we’ll <a href="https://hbr.org/2017/07/stop-the-meeting-madness">cancel all the meetings</a>, turn off our techy chat tools, and do 4 hours a day from home! I’ll be clocking off at noon!”</p><p>Well, here’s the bad news. If you try to lay down your boundaries with your company, even to result in better performance for them and more promotions for you, they most likely won’t like it. In fact, they will probably promote the inefficient job-snatchers in your place and shove you in the corner. Like they did <a href="https://hbr.org/2015/04/why-some-men-pretend-to-work-80-hour-weeks#:~:text=But%20not%20all,have%20long%20been.">here</a>. And if you’re a woman? Forget it.</p><p>The answer? Don’t worry your little face, my darling, for I have a solution. Lie.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c64be5d9119" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-tech-collective/success-youre-wrong-about-almost-everything-4c64be5d9119">Success: You’re wrong about almost everything</a> was originally published in <a href="https://medium.com/the-tech-collective">The Tech Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI Padding Vs Spacing]]></title>
            <link>https://medium.com/the-tech-collective/swiftui-padding-vs-spacing-b7351c91faed?source=rss-a96544aecefb------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7351c91faed</guid>
            <category><![CDATA[padding]]></category>
            <category><![CDATA[coding-conventions]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Chloe Houlihan]]></dc:creator>
            <pubDate>Fri, 14 Jul 2023 12:46:36 GMT</pubDate>
            <atom:updated>2023-10-27T13:38:12.523Z</atom:updated>
            <content:encoded><![CDATA[<h4>Which to use, when and why</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*nhs5cuBKuyxkKYND.jpg" /><figcaption>We’ve all been there (Credit: <br><a href="https://www.apolloniaponti.com/i-need-space/">Apollonia Ponti</a>)</figcaption></figure><p>Having a mix of padding and spacing can get confusing, especially when they combine to create effects not immediately obvious in code.</p><p>Here, I propose a convention to decide when to use which, consistently, and with a rationale that other engineers can use to review your code.</p><p>It’s one of my SwiftUI “Rules of Thumb”. For more, consider reading my other article: <a href="https://medium.com/@chloehoulihan/chloes-opinionated-and-biased-law-of-swiftui-905e07563a8d">Chloe’s Opinionated and Biased Law of SwiftUI</a> (do it… do it now).</p><h3>When do I use which?</h3><p>I’ve made this as simple as possible.</p><p><strong>If it’s a list or a feed of repeating components, especially using a </strong><strong>ForEach, use spacing. Everything else is padding, even if the padding happens to be the same for every component. If in doubt, use padding.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*FgVi50WAocCXXzfGVhZRWA.png" /><figcaption>All over the shop</figcaption></figure><p>Combining padding and spacing, especially when the spacing being the same is coincidental and not inherent in the nature of the context (i.e. a feed or list), causes confusion and makes it much harder to change later. It also means engineers reading it need to combine VStack/HStack spacing with any vertical/horizontal padding, respectively, in their heads- meaning what they read is not the direct truth. And when I read it, I scream “Whyyyy” and immediately decline your PR and revoke your git access.</p><h4>Incorrect Usage</h4><pre>VStack(spacing: 8) {<br>  Text(&quot;Title&quot;)<br>  Text(&quot;Description description&quot;)<br>}</pre><p>This is not a list or feed. If we add another Text in the future, it’s unlikely the spacing will still be 8 consistently. This means future engineers would need to remove the spacing and add padding to the existing components as well as the new one.</p><p>Yes, the vertical padding is the same for all components, but that is a coincidence and could be said about any view with only 2 components.</p><pre>VStack(spacing: 8) {<br>  Text(&quot;Title&quot;)<br>  Text(&quot;Description description&quot;)<br>  Button().padding(.top, 4)<br>}</pre><p>This numpty has been asked to add a new Button to this view. Like a numpty, they’ve kept their ill-conceived spacing: 8 and corrected the issue of the slightly wider padding between the text and the button by adding the difference to a padding modifier.</p><blockquote><strong>Numpty ˈnʌmptɪ: British, noun</strong><br><em>1. A person lacking intelligence, an idiot, a fool, the person who designed Obj-C<br>2. An engineer who incorrectly uses spacing in SwiftUI</em></blockquote><p>As an engineer, I now look at this and think that there is 4 padding between the button and the text, when there is actually 12.</p><p>You can see how this problem could grow out of control in more complex views- so leave that spacing alone! (No offence, numpties)</p><h4>Correct Usage</h4><pre>VStack(spacing: 8) {<br>  ForEach(models) { model in<br>    ListItem(model)<br>  }<br>}</pre><pre>List(models) { model in<br>  ListItem(model).padding(.vertical, 8)<br>}</pre><pre>VStack(spacing: .zero) {<br>  Text().padding(.bottom, 8)<br>  Text()<br>}</pre><p>Oof, what a lovely bit of coding. This guy ^ amirite?</p><h3>TLDR</h3><p>If it’s a list or a feed of repeating components, especially using a ForEach, use spacing.</p><p>Everything else is padding, even if the padding happens to be the same for every component.</p><p>If in doubt, use padding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7351c91faed" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-tech-collective/swiftui-padding-vs-spacing-b7351c91faed">SwiftUI Padding Vs Spacing</a> was originally published in <a href="https://medium.com/the-tech-collective">The Tech Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chloe’s Opinionated and Biased Law of SwiftUI]]></title>
            <link>https://medium.com/the-tech-collective/chloes-opinionated-and-biased-law-of-swiftui-905e07563a8d?source=rss-a96544aecefb------2</link>
            <guid isPermaLink="false">https://medium.com/p/905e07563a8d</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[coding-conventions]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Chloe Houlihan]]></dc:creator>
            <pubDate>Fri, 14 Jul 2023 12:34:45 GMT</pubDate>
            <atom:updated>2023-10-26T13:10:59.157Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to establish law and convention in the Wild West of SwiftUI</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*6B0q3OzS0nFUskd8.jpg" /><figcaption>Chloe enforcing the law, circa 1885 - Image by <a href="https://dribbble.com/IlyaSedykh">Ilya Sedykh</a></figcaption></figure><p>Having used SwiftUI since 2019 and as my primary language in a production app since 2020, I’ve learned a thing or two and I’ve also developed strong opinions about what I think is right, and, of course, everyone else is wrong!!</p><p>This is all of these things merged into My Word of Law. It’s up to you to pick which bits are well-reasoned and a good idea, and which bits are just me being a grumpy pedant.</p><p>In all seriousness though, this is just one engineer’s thoughts. They have been well received and adopted by all my teams so far, and so I thought they were worth sharing, especially for teams new to SwiftUI who are just looking for a jumping-off point for convention.</p><h3>Basic Rules of Thumb</h3><p>These tips are aimed at avoiding weird SwiftUI things occurring, making your code more readable, maintainable, debuggable and reducing <a href="https://en.wikipedia.org/wiki/Code_smell">smells</a>.</p><h4>Sizes/Dimensions</h4><p>You can now use Double instead of CGFloat . Putting all your Doubles in their own Struct (called Sizesor Dimensions or similar) has multiple benefits:</p><pre>public struct MyView: View {<br>  private let sizes: Sizes<br><br>  public init(sizes: Sizes = .init()) {<br>    self.sizes = sizes<br>  }<br><br>  public var body: some View {<br>    VStack(spacing: .zero) {<br>      MySubView()<br>        .padding(.horizonal, sizes.smallPadding)<br>        .padding(.top, sizes.padding)<br>      MyButton(width: sizes.buttonWidth)<br>        .padding(.horizonal, sizes.smallPadding)<br>        .padding(.vertical, sizes.padding)<br>      MyImage()<br>        .resizeable()<br>        .fixedSize()<br>        .frame(width: sizes.imageSize)<br>    }<br>  }<br>}<br><br>extension MyView {<br>  public struct Sizes {<br>    // MARK: Common sizes<br>    let padding: Double<br>    let smallPadding: Double<br><br>    // MARK: Button sizes<br>    let buttonWidth: Double<br><br>    // MARK: Image sizes<br>    let imageSize: Double<br><br>    public init(padding: Double = 16,<br>                smallPadding: Double = 8,<br>                buttonWidth: Double = 24,<br>                imageSize: Double = 50) {<br>      self.padding = padding<br>      self.smallPadding = smallPadding<br>      self.buttonWidth = buttonWidth<br>      self.imageSize = imageSize<br>    }<br>  }<br>}</pre><p>Pros:</p><ul><li>Dimensions are injectable making the view more reusable and customisable</li><li>Reduces repetition of values, meaning fewer mistakes if a value changes</li><li>All Doubles are in one place which reduces visual smells across the View. This is because the syntax highlighting will be of constants, not of raw values (no raw values in the View).</li><li>Values are easily adjustable in one place making maintenance quicker and easier, especially for engineers unfamiliar with this particular view</li><li>Sizes can be reused and shared/injected across multiple views if applicable</li><li>You’d be a big dumb-dumb not to</li></ul><p>Cons:</p><ul><li>More code (but less repeated code)</li><li>Dimension and component names need to be very clear to avoid engineers getting confused about which values control which view dimensions (in a way, this is a good thing as it forces engineers to make their code clear and readable, maybe even adding docs)</li></ul><h4>Padding- “Don’t Do”s</h4><pre>Text().padding(EdgeInsets(<br>  top: 0, <br>  leading: 8, <br>  bottom: 0, <br>  trailing: 8<br>))</pre><pre>Text()<br>  .padding(.top, 8)<br>  .padding(.bottom, 8)</pre><pre>Text().padding()</pre><h4>Padding- “Do Do”s 💩</h4><pre>Text().padding(.horizontal, 8)</pre><pre>Text().padding(.vertical, 8)</pre><ul><li>Use .all, .horizontal and .vertical</li></ul><pre>Text().padding(.all, 8)</pre><ul><li>You should ALWAYS specify dimensions: Which edges to pad, and by how much</li><li>Otherwise, don’t use padding. Just… just don’t…</li></ul><h4>Spacing- “Don’t Do”s</h4><pre>VStack {}<br>HStack {}<br>VStack(spacing: 0)</pre><ul><li>Spacing should be explicit, otherwise, <a href="https://stackoverflow.com/questions/58018633/swiftui-how-to-remove-margin-between-views-in-vstack">SwiftUI can set it to something weird</a> (it will default)</li></ul><h4>Spacing- “Do Do”s</h4><pre>VStack(spacing: .zero) {}<br>HStack(spacing: .zero) {}</pre><ul><li>Using the constant .zero instead of the variable 0 reduces smells by allowing our eyes to scan past it without seeing a stray Double highlighted in syntax (this is because we’re going to keep our dimensions tucked away in their own Struct), instead highlighting it as a constant</li><li>If I see little blue numbers dotted around my Views, I can smell ’em all like yesterday’s fish</li></ul><h4>Padding Vs Spacing</h4><p>For more, read: <a href="https://medium.com/@chloehoulihan/swiftui-padding-vs-spacing-b7351c91faed">SwiftUI Padding Vs Spacing</a></p><p><strong>Don’t do:</strong></p><pre>VStack(spacing: 8) {<br>  Text()<br>  Text()<br>  Button().padding(.top, 4)<br>}</pre><pre>VStack(spacing: 8) {<br>  Text(&quot;Title&quot;)<br>  Text(&quot;Description&quot;)<br>}</pre><pre>VStack(spacing: 8) {<br>  MyThing(models[0])<br>  MyThing(model[1])<br>  MyThing(model[2])<br>}</pre><p><strong>Do instead:</strong></p><p><em>(Note: These doubles should be in their own struct, and copy in the logic layer)</em></p><pre>VStack(spacing: .zero) {<br>  Text()<br>  Text().padding(.top, 8)<br>  Button().padding(.top, 12)<br>}</pre><pre>VStack(spacing: .zero) {<br>  Text(&quot;Title&quot;).padding(.bottom, 8)<br>  Text(&quot;Description&quot;)<br>}</pre><pre>VStack(spacing: 8) {<br>  ForEach(models) { model in<br>    MyThing(model)<br>  }<br>}</pre><h4>Frame- Don’t Do</h4><pre>Image()<br>  .resizable<br>  .frame(width: 10, height: 10)</pre><ul><li>If the aspect ratio of the asset changes, this will stretch the image</li></ul><h4>Frame- Do Do</h4><p><em>(Note: These doubles should be in their own struct, and copy in the logic layer)</em></p><pre>Image()<br>  .resizable()<br>  .fixedSize() // Or .scaleToFit()<br>  .frame(width: 10) // Or height: 10</pre><ul><li>Use either width or height (think about which one you want to stay the same if the image became taller/wider)</li><li>Use .scaleToFit (for SF icons) or .fixedSize (for assets) to keep the aspect ratio</li></ul><h4>Animations- Don’t Do</h4><p><em>(Note: Doubles should be in their own struct, and copy/logic in the logic layer)</em></p><pre>VStack(spacing: .zero) {<br>  if x {<br>    MySubView()<br>  }<br>  Button {<br>    withAnimation {<br>      x = 5<br>    }<br>  }, label: {<br>    Text(&quot;My button&quot;)<br>  }<br>}</pre><ul><li>Don’t use withAnimation { } because it’s ugly as sin.</li></ul><h4>Animations- Do Do</h4><pre>VStack(spacing: .zero) {<br>  if x == 5 {<br>    MySubView().transition(.slide) // Often not needed<br>  }<br>  Button(action: buttonTapped) {<br>    Text(&quot;My button&quot;)<br>  }<br>}.animation(.default, value: x)<br><br><br>// In the ViewModel (VM), where `x` is a VM field:<br>func buttonTapped() {<br>  x = 5<br>}</pre><ul><li>Use .animation on the container view- All the cool kids are doing it</li><li>Use .transition on the specific components to dictate how you want each to animate</li><li>The view/container the modifier is attached to, and everything inside it, will automatically animate any changes caused when the value updates (e.g. here MySubView will slide out)</li><li>In MVVM, @Published x, buttonTapped and x == 5are in your view model (logic layer)</li></ul><h3>Containers: Stacks, Groups and ViewBuilders</h3><h4>Don’t use containers needlessly</h4><pre>public var body: some View {<br>  VStack(spacing: .zero) {<br>    topSection<br>    middleSection<br>    bottomSection<br>  }<br>}<br><br>private var topSection: some View {<br>  VStack(spacing: .zero) {...}<br>}<br><br>private var middleSection: some View {<br>  VStack(spacing: .zero) {...}<br>}<br><br>private var bottomSection: some View {<br>  VStack(spacing: .zero) {...}<br>}</pre><ul><li>Don’t have 3 identical VStacks (same spacing, alignment, padding, etc) inside another identical VStack just for the sake of separating out the body for readability</li></ul><h4>Do use @ViewBuilder</h4><pre>public var body: some View {<br>  VStack(spacing: .zero) {<br>    topSection<br>    middleSection<br>    bottomSection<br>  }<br>}<br><br>@ViewBuilder private var topSection: some View {<br>  ...<br>}<br><br>@ViewBuilder private var middleSection: some View {<br>  ...<br>}<br><br>@ViewBuilder private var bottomSection: some View {<br>  ...<br>}</pre><ul><li>Use @ViewBuilder to take the components and add them to the upper container- in this case adding the components of the different sections to the body VStack</li><li>Don’t use Group instead of @ViewBuilder: This will reduce the repeated containers but doesn’t decrease the nesting like @ViewBuilder does. We’re not sparrows, stop nesting.</li></ul><h4>Don’t repeat modifiers</h4><pre>if viewModel.something {<br>  thing1.someModifer()<br>} else {<br>  thing2.someModifer()<br>}</pre><ul><li>Don’t apply the same modifier to multiple components, common when components are conditional (in an if/else, or switch)</li></ul><p>E.g.</p><ul><li>.animation(.default, viewModel.something)</li><li>.padding(.all, sizes.padding)</li></ul><h4>Do use Group</h4><pre>Group {<br>  if viewModel.something {<br>    thing1<br>  } else {<br>    thing2<br>  }<br>}.someModifer()</pre><ul><li>Subviews are sheep- they’ll follow anything the group is doing. If the teacher asks them “If the group jumped off a cliff, would you do it?” their answer is “hell, yeah”.</li><li>Use Group to apply modifiers to multiple components and reduce repetition</li></ul><h3>The Triangle of Death</h3><p>If you nest too many views inside each other, resulting in enough indentation to create a “triangle-like” effect, you may get a confusing error at the body level. This is essentially the compiler saying “This is a total mess, I can’t even help you anymore. Something’s wrong, I guess, but ̶G̶o̶d̶ Jobs knows what!”.</p><pre>public var body: some View {<br>  ZStack {<br>    Color.white<br>    VStack(spacing: .zero {<br>      Text(&quot;Title&quot;)<br>        .font(.title)<br>        .foregroundColor(.green)<br>        .padding(.vertical, 8)<br>      Text(&quot;Subtitle&quot;)<br>        .font(.subtitle)<br>        .foregroundColor(.blue)<br>        .padding(.bottom, 8)<br>        VStack(spacing: .zero) {<br>          ForEach(items) { item in<br>            ScrollView {<br>              HStack(spacing: 4) {<br>                ForEach(images) { image in<br>                  Image(image)<br>                    .resizable()<br>                    .fixedSize()<br>                    .frame(width: 50)<br>                  VStack(spacing: .zero) {<br>                    Text(&quot;Image name&quot;)<br>                      .font(.title2)<br>                      .foregroundColor(.blue)<br>                      .padding(.bottom, 2)<br>                    Text(&quot;Image description&quot;)<br>                      .font(.subtitle2)<br>                      .foregroundColor(.green)<br>                  }<br>                }<br>              }<br>            }<br>          }<br>        }<br>      }<br>      Text(&quot;^ Scroll through these image reels&quot;)<br>        .font(.caption)<br>        .foregroundColor(.red)<br>        .padding(.top, 16)<br>    }.padding(.horizontal, 16)<br>  }<br>}</pre><p>Not pretty, is it? Let’s try using private variables to break this ToD (Triangle of Death) down.</p><pre>public var body: some View {<br>  ZStack {<br>    Color.white<br>    content<br>  }<br>}<br><br>private var content: some View {<br>  VStack(spacing: .zero {<br>    header<br>    itemsList<br>    instruction<br>  }.padding(.horizontal, 16)<br>}<br><br>@ViewBuilder private var header: some View {<br>  Text(&quot;Title&quot;)<br>    .font(.title)<br>    .foregroundColor(.green)<br>    .padding(.vertical, 8)<br>  Text(&quot;Subtitle&quot;)<br>    .font(.subtitle)<br>    .foregroundColor(.blue)<br>    .padding(.bottom, 8)<br>}<br><br>private var itemsList: some View {<br>  VStack(spacing: .zero) {<br>    ForEach(items) { item in<br>      imageReel(item)<br>    }<br>  }<br>}<br><br>private func imageReel(_ item: Item) -&gt; some View {<br>  ScrollView {<br>    HStack(spacing: 4) {<br>      ForEach(images) { image in<br>        imageProfile(image)<br>      }<br>    }<br>  }<br>}<br><br>@ViewBuilder private func imageProfile(_ image: String) -&gt; some View {<br>  Image(image)<br>    .resizable()<br>    .fixedSize()<br>    .frame(width: 50)<br>  VStack(spacing: .zero) {<br>    Text(&quot;Image name&quot;)<br>      .font(.title2)<br>      .foregroundColor(.blue)<br>      .padding(.bottom, 2)<br>    Text(&quot;Image description&quot;)<br>      .font(.subtitle2)<br>      .foregroundColor(.green)<br>  }<br>}<br><br>private var instruction: some View {<br>  Text(&quot;^ Scroll through these image reels&quot;)<br>    .font(.caption)<br>    .foregroundColor(.red)<br>    .padding(.top, 16)<br>}</pre><h4>Pros</h4><ul><li>Reduced horizontal space</li><li>Reduced nesting (take that, sparrows)</li><li>Easier to read</li><li>Quicker to find components in code</li><li>Easier to rearrange the view</li><li>Top-level body and subviews are much quicker and easier to read/visualise (seeing a list of components in order instead of their full code)</li><li>No body-level compiler error: Debugging easier, inline errors/warnings enabled</li><li>Chloe is happy</li></ul><h4>Cons</h4><ul><li>More vertical space</li><li>More code</li></ul><h3>Conclusion</h3><p>I can already hear my CompSci first-years <em>(I used to mark Java lab work to make my rum money)</em> saying “But it runs fine without this stuff”. To which my response was normally “Shut up and do it, n00b!”.</p><p>Of course, with maturity comes patience (or complacency, you decide). And yes, most of this won’t change how the app compiles, performs or runs. But let me explain why we should do it anyway.</p><p>Conventions will make your PR reviewers happy. And if your whole team conforms to this, you’ll all be better able to sniff out those smells in SwiftUI views, drawing your nose straight into those potential bugs (e.g. unintentional combined padding and spacing) like a nerd to overpriced D&amp;D merch. Essentially, they make the code more readable, therefore, more maintainable and easier to debug.</p><p>Also, it’s pretty.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=905e07563a8d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-tech-collective/chloes-opinionated-and-biased-law-of-swiftui-905e07563a8d">Chloe’s Opinionated and Biased Law of SwiftUI</a> was originally published in <a href="https://medium.com/the-tech-collective">The Tech Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>