<?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 Krishnapalsinh Gohil on Medium]]></title>
        <description><![CDATA[Stories by Krishnapalsinh Gohil on Medium]]></description>
        <link>https://medium.com/@krishnapalsinhgohil?source=rss-4ede969fa3b6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nWMcAJdzMJsQtpYbYI3OWQ@2x.jpeg</url>
            <title>Stories by Krishnapalsinh Gohil on Medium</title>
            <link>https://medium.com/@krishnapalsinhgohil?source=rss-4ede969fa3b6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 14:20:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@krishnapalsinhgohil/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[Dive deep into the Single Responsibility Principle]]></title>
            <link>https://medium.com/@krishnapalsinhgohil/dive-deep-into-the-single-responsibility-principle-6f6c95182f02?source=rss-4ede969fa3b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f6c95182f02</guid>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[solid]]></category>
            <dc:creator><![CDATA[Krishnapalsinh Gohil]]></dc:creator>
            <pubDate>Sat, 22 Jun 2024 09:30:19 GMT</pubDate>
            <atom:updated>2024-06-29T03:46:07.421Z</atom:updated>
            <content:encoded><![CDATA[<h4>Also have a look how components are attached via Composition layer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lnHzF6AlOUgA4xcTQ6Mvug.png" /></figure><h3><strong>What are SOLID principles?</strong></h3><p>Every profession has a set of standards and strict rules to adhere to, with important consequences for non-compliance.</p><p>For example, consider how an architect must adhere to building codes to ensure the safety and stability of a structure.</p><p>Why are these standards made?</p><ul><li>Many people have gone through the same process, and their experiences contribute to a collective understanding of best practices.</li><li>Having a standard reduces the chance of error. It provides a clear, tested method that professionals can follow, ensuring consistency and reliability</li><li>A standard incorporates knowledge of all potential problem areas. It is defined in such a way that it addresses and mitigates these issues</li></ul><p><strong>Similarly, in software development,</strong></p><p>SOLID principles were created to provide a standard for writing clean, maintainable, and robust code.</p><ul><li>These principles result from many developers’ experiences and collective knowledge about what works best in software design.</li></ul><p>By following the SOLID principles, developers can minimize errors, fix potential problems, and create software that is easier to understand, extend, and maintain.</p><blockquote><em>While following these principles is optional, many developers might choose to skip them. Let’s first understand the first principle, and then you can decide if it’s useful</em></blockquote><h3><strong>What is the Single Responsibility Principle (SRP)?</strong></h3><blockquote><strong>It states that a class should have only one job or responsibility</strong></blockquote><ul><li>Now, every developer may interpret “responsibility” differently</li><li>When designing a component, one developer may consider the creation of the entire component as its single responsibility</li><li>Another developer might advocate for breaking down responsibilities further, such as handling the View and network calls as separate concerns</li></ul><p>To clarify, we often express the SRP as the concept that a class should have only one reason to change.</p><p>Simply, If a class requires modifications for more than one reason, it violates the SRP</p><h4><strong>Let’s see how ProfileVC violates the principle</strong></h4><pre>class ProfileVC: UIViewController {<br>  override func viewDidLoad() {<br>    fetchImageFromAPI()<br>  } <br><br>  func fetchImageFromAPI() {<br>    APIService.callAPI(with: url) { response in <br>      handleResponse (response: response)<br>    }<br>  }<br><br>  func handleResponse (response: Result&lt;Data, Error&gt;) {<br>    switch response {<br>    case success(let data):<br>      processImage (data: data)<br>    case failure (let error):<br>      print(&quot;Failed to fetch data: \(error)&quot;)<br>   }<br><br>  processImage(data: Data) {<br>    // process image<br>    displayDataOnUI(data: data)<br>  } <br><br>  func displayDataOnUI(data: Data) {<br>    print(&quot;Updating UI with data&quot;)<br>  }<br><br>}</pre><p>ProfileVC has the following responsibilities <br>- Fetching data from the service [Violation]<br>- Handling response [Violation]<br>- Processing image [Violation]<br>- Displaying image [Valid]</p><h3>Let’s apply the Single Responsibility Principle (SRP) to ProfileVC</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FoHuad18AzhU1sYS1Tm%2Fvideo&amp;display_name=GIPHY&amp;url=https%3A%2F%2Fgiphy.com%2Fclips%2Fanidom-christmas-crime-s20e10-season-20-ep-10-oHuad18AzhU1sYS1Tm&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2FoHuad18AzhU1sYS1Tm%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="480" height="270" frameborder="0" scrolling="no"><a href="https://medium.com/media/f26e016e70532a1f8692be67aba9c381/href">https://medium.com/media/f26e016e70532a1f8692be67aba9c381/href</a></iframe><blockquote><strong>Separation of concerns<br>On a very high level, let’s create separate components each having only one responsibility</strong></blockquote><ul><li>ImageLoader</li></ul><pre>// ImageLoader has only one responsibility<br>// Load the image from the network and pass it forward<br><br>class ImageLoader {<br><br>  func fetchImageFromAPI(completion: @escaping ResultCompletion) {<br>    APIService.callAPI(with: url) { response in <br>      completion(response)<br>    }<br>  }<br><br>}</pre><ul><li>ImageDecoder</li></ul><pre>// ImageDecoder  <br>// In reality, it would be parsing the base64 image from<br>// the response or similar operation and passing it to the next instance<br>// Just demonstration that decoding logic should be done in different component<br><br>class ImageDecoder {<br>  let result: ResultCompletion<br>  <br>  init(...) {<br>    self.result = result<br>  }<br>  <br>  func decodeImage(completion: ...) -&gt; Void)  {<br>     switch result {<br>      case .success(let data):<br>        // Handle decoding<br>        completion(success(data))<br>      case .failure(let error):<br>        completion (.failure(error))<br>     }<br>  }<br><br>}</pre><ul><li>ImageProcessor</li></ul><pre>// ImageProcessor  <br><br>class ImageProcessor {<br>  let imageData: Data<br>  <br>  init(...) {<br>    self.imageData = imageData<br>  }<br>  <br>  func processData(completion: ...) -&gt; Void)  {<br>    // Process image and pass further to the chain <br>  }<br><br>}</pre><ul><li>ProfileVC</li></ul><pre>// ProfileVC  <br><br>class ProfileVC: UIViewController {<br><br>  var load: (() -&gt; Void)?<br><br>  func viewDidLoad() { <br>    load()<br>  } <br><br>  func displayImage(_ data: Data) -&gt; Void)  {<br>    profileImage.image = UIImageFromData(data)<br>  }<br><br>}</pre><p>ProfileVC now only has a display method that will present the changes to the user</p><h4>Now comes the Composition, the real deal</h4><p>All the components are combined here</p><pre>// ProfileComposer  <br>// This is a simplest form of composition for easy understanding<br>// Preferred way is to use a design pattern. <br><br>final class ProfileComposer {<br>  func makeProfileVC() {<br>    let profileVC = ProfileVC()<br><br>    profileVC.load = {<br>      imageLoader.loadImage() {<br>         imageDecoder.decodeImage() {<br>            imageProcessor.processImage() { data in<br>                profileVC.displayImage(data)<br>            }<br>         }<br>      }<br>    }<br><br>    // Handle navigation of ProfileVC<br><br>  }<br>}<br></pre><blockquote>Do let me know if you want to see how a design pattern can be used to simplify this composition level</blockquote><h3><strong>What are the benefits?</strong></h3><h4><strong>Maintainability, Reusability &amp; Clarity</strong></h4><p>Dividing functionality into separate components like ImageLoader, ImageProcessor, and ImageResponseHandler enhances maintainability, gives reusability, and makes clear responsibilities, improving code clarity.</p><h4><strong>Abstraction</strong></h4><p>ProfileVC remains decoupled from specific data sources, allowing it to focus solely on UI presentation.</p><h4><strong>Improved Testability</strong></h4><p>As components are isolated it enables in-depth testing of individual functionalities independent of external dependencies or using mocks.</p><h4><strong>Reduced Coupling</strong></h4><p>Following SRP minimizes dependencies between components, lowering the risk of unintended interactions and enhancing the overall flexibility and robustness of the system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f6c95182f02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Do you use Codable protocol often? Here is a neat trick!]]></title>
            <link>https://medium.com/@krishnapalsinhgohil/do-you-use-codable-protocol-often-here-is-a-neat-trick-d426cccf91e0?source=rss-4ede969fa3b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d426cccf91e0</guid>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Krishnapalsinh Gohil]]></dc:creator>
            <pubDate>Sat, 08 Jul 2023 13:19:34 GMT</pubDate>
            <atom:updated>2023-07-08T13:19:34.220Z</atom:updated>
            <content:encoded><![CDATA[<h3>Do you use Codable protocol often? Here is a clean trick!</h3><h4>Say goodbye to unnecessary optionals and complex decoding logic</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*9kGM2ok_tp3OjkQz9UPUaw.png" /></figure><p>Have you ever encountered the challenge of handling JSON responses? Often, we find ourselves making trade-offs by making properties nullable or introducing unwanted changes in the model just to facilitate decoding.</p><p>We are left with properties we don&#39;t actually need, and every modification introduces the risk of impacting other modules (unless we have comprehensive tests in place).</p><p>Let’s consider an example to illustrate this problem. Imagine that we need to display a list of books, with each book showing the title, author, and publication year. To achieve this, we have two JSON endpoints: Authors and Books.</p><p>Authors JSON</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/331dfc735df7eecb452013b594e50dec/href">https://medium.com/media/331dfc735df7eecb452013b594e50dec/href</a></iframe><p>Books JSON</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec447556da8c199dba77e87d4b82cfdf/href">https://medium.com/media/ec447556da8c199dba77e87d4b82cfdf/href</a></iframe><p>Given the structure and requirements, we are prompted to design the following structure:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/857fe036adfa260a093f5a59e0a73517/href">https://medium.com/media/857fe036adfa260a093f5a59e0a73517/href</a></iframe><p>As you can see, we make the author property optional and mutable just for the decoder. Later, we replace the author from nil to the actual author name mapped from the author response. However, this leads to optional handling in the presentation layer, which is not related to the UI.</p><h4>What is the proposed solution for this problem?</h4><p>Let’s introduce a BookItemMapper. The responsibility of this mapper is to handle the data in an encapsulated way, providing an array of [Book] or an error if it fails to do so.</p><p>Let’s see it in action.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9199bba5c85441df7e352f2d465d2506/href">https://medium.com/media/9199bba5c85441df7e352f2d465d2506/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d30dc434615f639a67af8af0f611a06/href">https://medium.com/media/3d30dc434615f639a67af8af0f611a06/href</a></iframe><p>The BookItemMapper takes care of all the decoding and correctly maps the author in each Book object. It returns a simple model that can be safely used in our presentation layer.</p><p>Noticed how the Rootand Item model conforming to Decodable are private? They are only used for decoding and meeting the exact requirements of the Decoder.</p><p>Also, we get the control of handling the result however we need, in our case simply mapping it to array of Book</p><p>With the introduction of the BookItemMapper, we can now simplify our BookItemLoader</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfccfd5c9539de364f78f97d34deeaa0/href">https://medium.com/media/bfccfd5c9539de364f78f97d34deeaa0/href</a></iframe><p>Resulting in no unnecessary nullable, no mutating, just pure model. You can now use the BookItemLoader in your presentation module and implement the UI without worrying about the complexities of the handling the data.</p><p>The BookItemLoader now relies on the BookItemMapper to handle the data mapping. It provides a completion handler that returns either an array of books or an error, based on the result.</p><p>By leveraging the power of the Codable protocol and introducing a dedicated mapper, we gain more control over the decoding process while keeping our models pure and focused. This approach not only improves the readability and understandability of our codebase but also reduces the risk of introducing bugs when making modifications. Overall, it’s a clean and efficient solution that enhances the overall development</p><p>Additionally, consider using the <a href="https://medium.com/@krishnapalsinhgohil/remove-dispatchqueue-main-async-from-everywhere-and-simplify-1fc1c58e8fdf">DispatchQueueDecorator</a> to further improve your code and simplify the UI level without worrying about threading logic.</p><p>Start implementing this already! If you have any further questions or need additional assistance, feel free to ask.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d426cccf91e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Remove DispatchQueue.main.async from everywhere and simplify]]></title>
            <link>https://medium.com/@krishnapalsinhgohil/remove-dispatchqueue-main-async-from-everywhere-and-simplify-1fc1c58e8fdf?source=rss-4ede969fa3b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fc1c58e8fdf</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Krishnapalsinh Gohil]]></dc:creator>
            <pubDate>Sat, 01 Jul 2023 13:45:40 GMT</pubDate>
            <atom:updated>2023-07-09T07:26:43.666Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stop repeating DispatchQueue.main.async</h3><h4>An efficient way to perform main queue operations for your iOS apps.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*w2l5TsCRC6PUeAYcs39U9Q.png" /></figure><p>How often do you find yourself adding this block in your code just so that the UI layer get convenience to update it’s components?</p><p>Let’s consider the scenario of a RemoteItemLoader and an ItemListController</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/900b4bf72da910616646585f437343e9/href">https://medium.com/media/900b4bf72da910616646585f437343e9/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc0bf1ed7af6ae3155bcd519fb832e33/href">https://medium.com/media/cc0bf1ed7af6ae3155bcd519fb832e33/href</a></iframe><p>Notice, how the RemoteItemLoader is given the responsibility to complete on main queue. It&#39;s not ideal for the API or the ItemListController to handle dispatching to the main queue. It’s not their responsibility, we need a better solution, and that&#39;s where the MainQueueDecorator comes in.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5537c06a3ab812de5a50fac1a59358ff/href">https://medium.com/media/5537c06a3ab812de5a50fac1a59358ff/href</a></iframe><p>The MainQueueDecorator acts as an interface between the RemoteItemLoader and the ItemListController, providing a neat way to handle main queue operations.</p><p>First, we define the ItemService protocol, which allows us to decouple our code from the concrete implementation of the RemoteItemLoader. This also gives us the flexibility to intercept the service and modify its behavior, such as in our case dispatching to the main queue.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c75904e3d4a1e2bc73cbc7a6f310473/href">https://medium.com/media/0c75904e3d4a1e2bc73cbc7a6f310473/href</a></iframe><p>Next, we make the RemoteItemLoader conform to the ItemService protocol.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/efe82aaf079d17f526b2dd58fb92f114/href">https://medium.com/media/efe82aaf079d17f526b2dd58fb92f114/href</a></iframe><p>We then replace the concrete class with the ItemService protocol in the ItemListController. This decouples the controller from the implementation details and allows us to work with the abstraction.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44fc151a8309e37c325883f5a79d5558/href">https://medium.com/media/44fc151a8309e37c325883f5a79d5558/href</a></iframe><p>To handle main queue operations, we implement the MainQueueDecorator and make it conform to the ItemService protocol. This decorator intercepts the service calls and ensures that the code execution is dispatched to the main queue.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cbc740feb53a89406a426f7d97181e38/href">https://medium.com/media/cbc740feb53a89406a426f7d97181e38/href</a></iframe><p>Let’s see what we can do with ItemListController</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b60948e63f07c2b0e5d34cd40d8076d5/href">https://medium.com/media/b60948e63f07c2b0e5d34cd40d8076d5/href</a></iframe><p>With this setup, we can now guarantee that the code completes on the main queue, providing a clean and reliable way to handle UI updates. By decoupling the threading logic from the RemoteItemLoader and ItemListController, we improve the maintainability and testability of our codebase.</p><p>In summary, using a MainQueueDecorator to handle main queue operations is a great approach for managing UI updates in iOS apps. It promotes cleaner code, separation of concerns, and better code organisation.</p><p>Start implementing this pattern already! If you have any further questions or need additional assistance, feel free to ask.</p><p>If you found this article insightful, I highly recommend checking out my other articles. They can provide even more valuable information and insights. Thank you.</p><p><a href="https://medium.com/@krishnapalsinhgohil/do-you-use-codable-protocol-often-here-is-a-neat-trick-d426cccf91e0">Do you use Codable protocol often? Here is a neat trick!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fc1c58e8fdf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>