<?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 Ahmet Tarik DÖNER on Medium]]></title>
        <description><![CDATA[Stories by Ahmet Tarik DÖNER on Medium]]></description>
        <link>https://medium.com/@ahmettarikdoner?source=rss-6ca908bc68e4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RRfMumoz6pPZ516OWt2Shw.png</url>
            <title>Stories by Ahmet Tarik DÖNER on Medium</title>
            <link>https://medium.com/@ahmettarikdoner?source=rss-6ca908bc68e4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 02:47:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ahmettarikdoner/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[Command Design Pattern]]></title>
            <link>https://blog.stackademic.com/command-design-pattern-8c4c93421171?source=rss-6ca908bc68e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c4c93421171</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[command-pattern]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Ahmet Tarik DÖNER]]></dc:creator>
            <pubDate>Tue, 05 Nov 2024 15:04:02 GMT</pubDate>
            <atom:updated>2024-11-07T01:45:04.960Z</atom:updated>
            <content:encoded><![CDATA[<h4>The <strong>Command Design Pattern</strong> encapsulates a request as an object, allowing you to parameterize other objects with different requests, queue them, and log or undo operations easily. This pattern turns commands into standalone objects, making it easier to handle complex sequences of operations and enabling more flexible, decoupled code.</h4><p>Complexity: ⭐️★★<br>Popularity: ⭐️⭐️⭐️</p><h4>The Problem Command Solves</h4><p>Imagine your team are building a photo editing application like Adobe Lightroom or PhotoShop. And your task is to create a Word like toolbar with bunch of buttons for various operations. You can either create a top hierarchical Button class or use generic button as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0lxjM_D2ZByCfS79oDVGDA.png" /><figcaption>All buttons are derived from the defined Button object.</figcaption></figure><p>You have multiple buttons performing different actions, each button might need to have its own unique click handler. The simplest but inflexible solution would be to create a separate subclass for each action the button could perform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dVnygCAYaZH9gQs0SBRNSQ.png" /><figcaption>Subclasses of Button</figcaption></figure><p>We&#39;re directing to the wrong way. A lots lots of subclasses… What about when i want to change the base Button class? This might break the code in subclasses. And also GUI code has become awkwardly dependent on the volatile code on the business logic-side. Some operations, such as copy-pasting would need to be invoked multiple places. It is okey to subclassing Button again for now, but later decided to implement Menus, Shortcuts etc., need to duplicate this code in multiple places. This is getting out of control.</p><h4>The Command Solution</h4><p>Software architecture thrives on clean <em>separation of concern</em>, with each layer serving a distinct purpose. Most modern applications implement this through a clear division between presentation and processing — specifically, separating the user interface layer from the business logic core. The UI layer excels at its specialized role: managing visual elements, handling user interactions, and orchestrating the flow of information across the screen. Yet when computational tasks arise, whether it’s data analysis, business rule validation, or complex algorithmic processing, this presentation layer steps aside, delegating these operations to the dedicated business logic layer.</p><p>A GUI objects calls a method of business logic object and pass it some arguments. This process usually describes as one object sending another a <em>request</em>.</p><p>The command pattern suggests that GUI objects shouldn’t send these request directly. Instead, you should extract all of these request details, such as the object being called, the name of the method and the list of arguments into a separate <strong><em>command </em></strong>class with a single method triggers this request</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DmWx37aq1PiUvc1pmretOg.png" /><figcaption>Accessing the business logic via a command.</figcaption></figure><p>Next step make commands implement same interface. Usually, it has just a single execution method that takes no parameters. This interface lets you use various commands with the same request sender. Since the command execution method doesn’t have any parameters, how we pass the request details to the receiver? The answer is either the command should be pre-configured with this data, or capable of getting it on its own.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oFN_MDOQKu9nEf5Amj_s1Q.png" /><figcaption>GUI objects delegates the work to commands.</figcaption></figure><p>Back to our app, we no longer all those subclasses to implement various click behaviors. Just put a single field to stores a reference to a command object and make the button execute that command on a click</p><h4>The Command Structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O6rCT1z6bRp4tkwjizCCWg.png" /><figcaption>The Structure of Command.</figcaption></figure><h4>Domain of Applicability</h4><ul><li><strong>To parameterize objects with operations</strong>: Command pattern lets you convert method calls into standalone objects, making it possible to pass commands as arguments, store them, or even switch them at runtime.</li><li><strong>To queue, schedule, or remotely execute operations</strong>: Since commands can be serialized (converted to strings), they can easily be stored in files or databases, queued, or executed later.</li><li><strong>To implement undoable actions</strong>: The Command pattern enables reversing actions by storing necessary details, making it ideal for undo/redo functionality.</li></ul><h4>How does the Command Implements:</h4><ol><li><strong>Define a command interface</strong> with a single execute() method.</li><li><strong>Create concrete command classes</strong> that implement this interface. Each command class should store request-specific details, including any necessary arguments and a reference to the target receiver object, initialized through the command’s constructor.</li><li><strong>Identify sender classes</strong> and add fields for storing command objects. These senders should interact with commands only through the command interface, without creating command objects directly.</li><li><strong>Update senders</strong> to execute commands rather than directly calling methods on the receiver.</li><li><strong>Initialize the command chain</strong> in the following order:</li></ol><ul><li>Create receiver objects.</li><li>Create command objects, associating them with the appropriate receivers.</li><li>Create sender objects and assign specific commands to them.</li></ul><h4>Conceptual Example</h4><pre><br>//  MARK: - Command Interface<br>/// The Command interface declares a method for executing a command.<br>protocol Command {<br>    func execute()<br>}<br><br>//  MARK: - Concrete Commands<br>/// Some commands can implement simple operations on their own.<br>final class SimpleCommand: Command {<br>    <br>    private var payLoad: String<br>    <br>    init(_ payLoad: String) {<br>        self.payLoad = payLoad<br>    }<br>    <br>    func execute() {<br>        print(&quot;SimpleCommand: See, I can do simple things like printing (&quot; + payLoad + &quot;)&quot;)<br>    }<br>}<br><br>/// However, some commands can delegate more complex operations to other objects<br>/// called &#39;receivers&#39;.<br>final class ComplexCommand: Command {<br>    <br>    private var receiver: Receiver<br>    <br>    /// Complex commands can accept one or several receiver objects along with any<br>    /// context data via the constructor.<br>    private var a: String<br>    private var b: String<br>    <br>    init(receiver: Receiver, _ a: String, _ b: String) {<br>        self.receiver = receiver<br>        self.a = a<br>        self.b = b<br>    }<br>    <br>    /// Commands can delegate to any methods of a receiver.<br>    func execute() {<br>        print(&quot;ComplexCommand: Complex stuff should be done by a receiver object.\n&quot;)<br>        receiver.doSomething(a)<br>        receiver.doSomethingElse(b)<br>    }<br>}<br><br>//  MARK: - Receiver<br>final class Receiver {<br>    func doSomething(_ a: String) {<br>        print(&quot;Receiver: Working on (&quot; + a + &quot;)\n&quot;)<br>    }<br>    <br>    func doSomethingElse(_ b: String) {<br>        print(&quot;Receiver: Also Working on (&quot; + b + &quot;)\n&quot;)<br>    }<br>}<br><br><br>//  MARK: - Sender / Invoker<br>/// The Invoker class is associated with one or several commands. It sends a request to the command.<br>final class Invoker {<br>    private var onStart: Command?<br>    private var onFinish: Command?<br>    <br>    /// Initialize commands<br>    func setOnStart(_ command: Command) {<br>        onStart = command<br>    }<br>    <br>    func setOnFinish(_ command: Command) {<br>        onFinish = command<br>    }<br>    <br>    /// The Invoker does not depend on concrete command or receiver  classes. The<br>    /// Invoker passes a request to a reciever indirectly, by executing  a command.<br>    func doSomethingImportant() {<br>        print(&quot;Invoker: Does anybody want something done before I begin?&quot;)<br>        onStart?.execute()<br>        print(&quot;Invoker: ...doing something really important...&quot;)<br>        print(&quot;Invoker: Does anybody want something done after I finish?&quot;)<br>        onFinish?.execute()<br>    }<br>}<br><br>class TestCommandConceptual {<br>    func test() {<br>        /// The Client code can parametirize an invoker with any commands.<br>        let invoker = Invoker()<br>        invoker.setOnStart(SimpleCommand(&quot;Say 🙋&quot;))<br>        let receiver = Receiver()<br>        invoker.setOnFinish(ComplexCommand(receiver: receiver, &quot;Send email📧&quot;, &quot;Save reports&quot;))<br>        invoker.doSomethingImportant()<br>    }<br>}<br><br>let test = TestCommandConceptual()<br>test.test()</pre><h4>Real World Example</h4><pre>import Foundation<br><br>class DelayedOperation: Operation {<br>    <br>    private var delay: TimeInterval<br>    private var _executing: Bool = false<br>    private var _finished: Bool = false<br>    <br>    init(_ delay: TimeInterval) {<br>        self.delay = delay<br>    }<br>    <br>    override var isExecuting: Bool {<br>        get { _executing }<br>        set {<br>            willChangeValue(forKey: &quot;isExecuting&quot;)<br>            _executing = newValue<br>            didChangeValue(forKey: &quot;isExecuting&quot;)<br>        }<br>    }<br>    <br>    override var isFinished: Bool {<br>        get { _finished }<br>        set {<br>            willChangeValue(forKey: &quot;isFinished&quot;)<br>            _finished = newValue<br>            didChangeValue(forKey: &quot;isFinished&quot;)<br>        }<br>    }<br>    <br>    override func start() {<br>        guard delay &gt; 0 else {<br>            _start()<br>            return<br>        }<br>        let deadline = DispatchTime.now() + delay<br>        DispatchQueue(label: &quot;&quot;).asyncAfter(deadline: deadline) {<br>            self._start()<br>        }<br>    }<br>    <br>    func _start() {<br>        guard !self.isCancelled else {<br>            print(&quot;\(self): operation is cancelled.&quot;)<br>            self.isFinished = true<br>            return<br>        }<br>        self.isExecuting = true<br>        self.main()<br>        self.isExecuting = false<br>        self.isFinished = true<br>    }<br>}<br><br>final class WindowOperation: DelayedOperation {<br>    override var description: String { &quot;WindowOperation&quot; }<br>    <br>    override func main() {<br>        print(&quot;\(self): Windows are closed via HomeKit.&quot;)<br>    }<br>}<br><br>final class TaxiOperation: DelayedOperation {<br>    override var description: String { &quot;TaxiOperation&quot; }<br>    <br>    override func main() {<br>        print(&quot;\(self): Taxi is ordered via Uber.&quot;)<br>    }<br>}<br><br>final class DoorOperation: DelayedOperation {<br>    override var description: String { &quot;DoorOperation&quot; }<br>    <br>    override func main() {<br>        print(&quot;\(self): Door are closed via HomeKit.&quot;)<br>    }<br>}<br><br><br>final class SiriShortCuts {<br>    static let shared = SiriShortCuts()<br>    private lazy var queue = OperationQueue()<br>    <br>    private init() { }<br>    <br>    enum Action: String {<br>        case leaveHome<br>        case leaveWork<br>    }<br>    <br>    func perform(_ action: Action, delay: TimeInterval = 0) {<br>        print(&quot;Siri: performing \(action)-action\n&quot;)<br>        switch action {<br>        case .leaveHome:<br>            add(operation: WindowOperation(delay))<br>            add(operation: DoorOperation(delay))<br>        case .leaveWork:<br>            add(operation: TaxiOperation(delay))<br>        }<br>    }<br>    <br>    private func add(operation: Operation) {<br>        queue.addOperation(operation)<br>    }<br>    <br>    private func cancelOperation(with operationType: Operation.Type) {<br>        queue.operations.filter { operation in<br>            return type(of: operation) == operationType<br>        }.forEach { $0.cancel() }<br>    }<br>    <br>    func cancel(_ action: Action) {<br>        print(&quot;Siri: cancelling \(action)-action&quot;)<br>        switch action {<br>        case .leaveHome:<br>            cancelOperation(with: WindowOperation.self)<br>            cancelOperation(with: DoorOperation.self)<br>        case .leaveWork:<br>            cancelOperation(with: TaxiOperation.self)<br>        }<br>    }<br>}<br><br>import XCTest<br><br>class TestCommandRealWorld: XCTestCase {<br>    func testCommandRealWorld() {<br>        <br>    }<br>}<br><br>extension TestCommandRealWorld {<br>    struct ExecutionTime {<br>        static let max: TimeInterval = 5<br>        static let waiting: TimeInterval = 4<br>    }<br>    <br>    func prepareTestEnvironment(_ execution: () -&gt; Void) {<br>        /// This method tells Xcode to wait for async operations. Otherwise the main test is done immediately.<br>        let expectation = self.expectation(description: &quot;Expectation for async operations&quot;)<br>        let deadline = DispatchTime.now() + ExecutionTime.waiting<br>        DispatchQueue.main.asyncAfter(deadline: deadline) { &quot;expectations.fullFill()&quot; }<br>    }<br>}</pre><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c4c93421171" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/command-design-pattern-8c4c93421171">Command Design Pattern</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Strategy Design Pattern]]></title>
            <link>https://blog.stackademic.com/strategy-design-pattern-1a03a10bf8cd?source=rss-6ca908bc68e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a03a10bf8cd</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[strategy-pattern]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Ahmet Tarik DÖNER]]></dc:creator>
            <pubDate>Tue, 05 Nov 2024 11:37:48 GMT</pubDate>
            <atom:updated>2024-11-07T01:45:18.462Z</atom:updated>
            <content:encoded><![CDATA[<h4>The <strong>Strategy</strong> pattern enables you to define a family of algorithms, place each in its own class, and make them interchangeable. This provides flexibility in choosing the best algorithm at runtime without altering the context in which it is used.</h4><p>Complexity: ⭐️★★<br>Popularity: ⭐️⭐️⭐️</p><h4>The Problem Strategy Solves</h4><p>Imagine you’re developing a video streaming app. One of the main features is to <strong>suggest personalized recommendations</strong> based on different criteria. Initially, the app’s recommendation engine only offered suggestions based on <strong>watch history</strong>. Later, to improve personalization, you add options for <strong>genre-based recommendations</strong>, <strong>top trending videos</strong>, and <strong>recommendations based on friends’ watchlists</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dEgeF54i_e-bVSVdh0KK5A.png" /><figcaption>The RecommendationEngines would become unmanageable and fail-prone.</figcaption></figure><p>Each time a new recommendation algorithm is added, the RecommendationEngine class grows more complex. Changing or tweaking one algorithm becomes risky, as it could disrupt the entire recommendation system.</p><h4>The Strategy Solution</h4><p>The Strategy pattern can help here by isolating each recommendation algorithm into its own class called <em>strategy</em>, creating a <strong>recommendation strategy</strong>. The main RecommendationEngine class, known as the <strong>context</strong>, holds a reference to one of these strategies and delegates the recommendation work to it. The context doesn’t choose which recommendation algorithm to use; instead, the client (or app) selects and passes the appropriate strategy to the RecommendationEngine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZUQ1OOGY6kN-1Ac0PlF21g.png" /><figcaption>Stream recommendation strategies</figcaption></figure><p>For example, you might have separate classes like WatchHistoryStrategy, GenreBasedStrategy, TrendingStrategy, and FriendsWatchlistStrategy. Each strategy class implements a getRecommendations() method, which returns a list of recommended videos based on the selected algorithm. Although the recommendations may vary depending on the strategy, the RecommendationEngine only needs to display the final list, keeping it independent of specific recommendation algorithms.</p><h4>The Strategy Structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NeQmhEVEmHqodSYlO9idTA.png" /><figcaption>The Structure of Strategy.</figcaption></figure><h4>Domain of Applicability</h4><ul><li>You need different variants of an algorithm that can be switched at runtime</li><li>You have similar classes that differ only in their behavior</li><li>You want to isolate algorithm logic from implementation details</li><li>You notice large conditional statements switching between different algorithm variants</li></ul><h4>How does the Strategy Implements:</h4><ol><li>In the context class, identify an algorithm that’s prone to frequent changes.<br><em>It may also be a massive conditional that selects and executes a variant of the same algorithm at runtime.</em></li><li>Declare a strategy interface common to all variants of algorithm.</li><li>Extract each algorithm into its own class, implementing the strategy interface.</li><li>In the context class, add a field to store a reference to a strategy object, and provide a setter for assigning different strategies. The context should interact with the strategy solely through the strategy interface.</li><li>Clients of the context associate it with an appropriate strategy, enabling the context to execute the desired algorithm seamlessly.</li></ol><h4>Conceptual Example</h4><pre><br>//  MARK: - STRATEGY INTERFACE<br>/// The Strategy interface declares operations common to all supported versions of some algorithm.<br>///<br>/// The Context uses this interface to call the algorithm defined by Concrete Strategies.<br>protocol Strategy {<br>    func doAlgorithm&lt;T: Comparable&gt;(_ data: [T]) -&gt; [T]<br>}<br><br>//  MARK: - CONCRETE STRATEGIES<br>/// Concrete Strategies implement the algorithm while following the base Strategy interface.<br>/// The interface makes them interchangeable in the Context.<br>final class ConcreteStrategyA: Strategy {<br>    func doAlgorithm&lt;T: Comparable&gt;(_ data: [T]) -&gt; [T] {<br>        return data.sorted()<br>    }<br>}<br><br>final class ConcreteStrategyB: Strategy {<br>    func doAlgorithm&lt;T: Comparable&gt;(_ data: [T]) -&gt; [T] {<br>        return data.sorted(by: &gt;)<br>    }<br>}<br><br>//  MARK: - CONTEXT<br>/// The Context defines the interface of interest to clients.<br>class Context {<br>    /// The Context maintains a reference to one of Strategy objects.<br>    /// The Context doens&#39;t know the concrete class of a strategy. It should work with all strategies via Strategy interface.<br>    private var strategy: Strategy<br>    <br>    /// Usually, the Context, accepts a strategy through the constructor, but<br>    /// also provides a setter to change it at runtime.<br>    init(strategy: Strategy) {<br>        self.strategy = strategy<br>    }<br>    <br>    /// Usually, Context allows replacing a Strategy object at runtime.<br>    func update(strategy: Strategy) {<br>        self.strategy = strategy<br>    }<br>    <br>    /// The Context delegates some work to the Strategy object instead of<br>    /// implementing multiple versions of the algorithm on its own.<br>    func doSomeBusinessLogic() {<br>        print(&quot;Context: Sorting data using the strategy (not sure how it will do it.)\n&quot;)<br>        let result = strategy.doAlgorithm([&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;])<br>        print(result.joined(separator: &quot;, &quot;))<br>    }<br>}<br><br>let context = Context(strategy: ConcreteStrategyA())<br>print(&quot;Client: Strategy is set to normal sorting.\n&quot;)<br>context.doSomeBusinessLogic()<br>print(&quot;\nClient: Strategy is set to reverse sorting.\n&quot;)<br>context.update(strategy: ConcreteStrategyB())<br>context.doSomeBusinessLogic()<br></pre><h4>Real World Example</h4><pre>import UIKit<br><br>//  MARK: - STRATEGY INTERFACE<br>protocol DataSourceStrategy {<br>    func loadModels&lt;T: DomainModel&gt;() -&gt; [T]<br>}<br><br>//  MARK: - CONCRETE STRATEGIES<br>final class ConcreteMemoryStorageStrategy&lt;Model&gt;: DataSourceStrategy {<br>    private lazy var items = [Model]()<br>    <br>    func add(_ items: [Model]) {<br>        self.items.append(contentsOf: items)<br>    }<br>    <br>    func loadModels&lt;T: DomainModel&gt;() -&gt; [T] {<br>        guard T.self == User.self else { return [] }<br>        <br>        return items as! [T]<br>    }<br>}<br><br>final class ConcreteCoreDataStorageStrategy: DataSourceStrategy {<br>    func loadModels&lt;T: DomainModel&gt;() -&gt; [T] {<br>        guard T.self == User.self else { return [] }<br>        let firstUser = User(id: 3, username: &quot;username3&quot;)<br>        let secondUser = User(id: 4, username: &quot;username4&quot;)<br>        <br>        return [firstUser, secondUser] as! [T]<br>    }<br>}<br><br>final class ConcreteRealmStorageStrategy: DataSourceStrategy {<br>    func loadModels&lt;T&gt;() -&gt; [T] where T : DomainModel {<br>        guard T.self == User.self else { return [] }<br>        let firstUser = User(id: 5, username: &quot;username5&quot;)<br>        let secondUser = User(id: 6, username: &quot;username6&quot;)<br>        <br>        return [firstUser, secondUser] as! [T]<br>    }<br>}<br><br><br>//  MARK: - DOMAIN MODEL<br>protocol DomainModel {<br>    var id: Int { get }<br>}<br>/// User specific domain-model<br>struct User: DomainModel {<br>    var id: Int<br>    var username: String<br>}<br><br>//  MARK: - LISTVIEWCONTEXT<br>final class ListViewController {<br>    <br>    private var dataSourceStrategy: DataSourceStrategy?<br>    <br>    func update(strategy: DataSourceStrategy) {<br>        self.dataSourceStrategy = strategy<br>    }<br>    <br>    func displayModels() {<br>        guard let dataSourceStrategy else { return }<br>        let models = dataSourceStrategy.loadModels() as [User]<br>        print(&quot;\nListViewController: Displaying models...&quot;)<br>        models.forEach { print($0) }<br>    }<br>}<br><br><br>//  MARK: - TESTING<br>final class TestStrategyRealWorld {<br>    func test() {<br>        let controllerContext = ListViewController()<br>        let memoryStorage = ConcreteMemoryStorageStrategy&lt;User&gt;()<br>        memoryStorage.add(usersFromNetwork())<br>        clienCode(use: controllerContext, with: memoryStorage)<br>        clienCode(use: controllerContext, with: ConcreteCoreDataStorageStrategy())<br>        clienCode(use: controllerContext, with: ConcreteRealmStorageStrategy())<br>    }<br>    <br>    func clienCode(use controller: ListViewController, with dataSourceStrategy: DataSourceStrategy) {<br>        controller.update(strategy: dataSourceStrategy)<br>        controller.displayModels()<br>    }<br>    <br>    private func usersFromNetwork() -&gt; [User] {<br>        let firstUser = User(id: 1, username: &quot;username1&quot;)<br>        let secondUser = User(id: 2, username: &quot;username2&quot;)<br>        <br>        return [firstUser, secondUser]<br>    }<br>}<br><br>let test = TestStrategyRealWorld()<br>test.test()</pre><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a03a10bf8cd" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/strategy-design-pattern-1a03a10bf8cd">Strategy Design Pattern</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adapter Design Pattern]]></title>
            <link>https://blog.stackademic.com/adapter-design-pattern-062ce375d234?source=rss-6ca908bc68e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/062ce375d234</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[adapter-pattern]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Ahmet Tarik DÖNER]]></dc:creator>
            <pubDate>Tue, 05 Nov 2024 10:11:54 GMT</pubDate>
            <atom:updated>2024-11-07T01:45:30.711Z</atom:updated>
            <content:encoded><![CDATA[<h4>The <strong>Adapter</strong> pattern enables objects with incompatible interfaces to work together. It acts as a bridge, transforming one interface into another so that otherwise incompatible components can collaborate seamlessly.</h4><p>Complexity: ⭐️★★<br>Popularity: ⭐️⭐️⭐️</p><h4>The Problem Adaptor Solves</h4><p>Imagine, you’ve built a music streaming app that processes playlists in MP3 format. Your app works flawlessly until you want to integrate a sophisticated audio processing library that only works with FLAC format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CqQlS7dTo8BSUX6yqWPmMg.png" /><figcaption>You can&#39;t use the library &#39;as it is&#39;, because it expects the type as FLAC format.</figcaption></figure><p>If the library were open source, you could modify it to work with FLAC. However, doing so might break existing code that relies on the library’s original design, and creating additional problems. Also it is violates the Single Responsibility Principle.</p><p>Here&#39;s the another common analogy: Imagine you’re traveling internationally with your laptop charger. You have a perfectly good charger, but the wall socket has a completely different shape. What do you need? A power adapter! This everyday scenario perfectly illustrates the Adapter Design Pattern in software development.</p><h4>The Adaptor Solution</h4><p>To solve this, you can create an <strong>adapter</strong> — a special object that converts the interface of one object so another object can understand it. This adapter wraps one object and hides the complexity of conversion from the rest of the application. The wrapped object remains unaware of the adapter’s presence.</p><p>Here’s how it works in practice:</p><ol><li>The adapter uses an interface compatible with one of the existing objects.</li><li>Through this interface, the existing object can safely call the adapter’s methods.</li><li>When the adapter receives a call, it translates the request and passes it to the second object in a format that the object expects.</li></ol><p>In our music streaming app, we could create an MP3-to-FLAC adapter. The application would then communicate with the analytics library through this adapter. When the adapter receives data in MP3 format, it converts it to FLAC and then passes it to the analytics library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*scL4wuzM2B82aG98caRviA.png" /><figcaption>Adapter act as a bridge in between incompatible layers.</figcaption></figure><h4>The Adaptor Structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7_nrEM936VpiaMZ6Wnslag.png" /><figcaption>The Structure of Adapter</figcaption></figure><p>This structure depends on the <em>object composition principle</em>, and the object called <strong>object adapter</strong>. Also we have <strong>class adapters </strong>that uses <em>inheritance</em>. The adapter inherits both interface at the same time. But it supports only when the programming language supports multiple inheritance such as C++.</p><h4>Domain of Applicability</h4><ul><li>You need to use an existing class whose interface doesn’t match your needs</li><li>You want to create a reusable class that cooperates with classes having incompatible interfaces</li><li>You need to integrate third-party libraries without modifying their code</li><li>You have multiple components with similar functionality but different interfaces</li></ul><h4>How does the Adapter Implements:</h4><ol><li>Identify at least two classes with incompatible interfaces.</li><li>Define the client interface to specify how clients should interact with the service.</li><li>Create an adapter class that follows the client interface.</li><li>Add a field to the adapter class to store a reference to the service object. Typically, this reference is initialized via the constructor, but in some cases, it’s convenient to pass it directly when calling the adapter’s methods.</li><li>Implement all methods of the client interface in the adapter class. Each method should delegate most of the real work to the service object, handling only interface or data formatting as needed.</li><li>Ensure the client interacts with the adapter through the client interface, allowing you to modify or extend adapters without affecting existing client code.</li></ol><h4>Conceptual Example</h4><pre><br>/// Target defines the domain-specific interface used by the client code.<br>class Target {<br>    func request() -&gt; String {<br>        &quot;Target: The default target&#39;s behavior.&quot;<br>    }<br>}<br><br>/// Adaptee contains some useful behavior, but its interface is incompatible with the existing client code.<br>/// Te Adaptee needs some adaptation before the client code can use it.<br>class Adaptee {<br>    func specificRequest() -&gt; String {<br>        &quot;.eetpadA eht fo roivaheb laicepS&quot;<br>    }<br>}<br><br>/// The Adapter makes the Adaptee&#39;s interface compatible with the Target&#39;s interface.<br>class Adapter: Target {<br>    <br>    private var adaptee: Adaptee<br>    <br>    init(_ adaptee: Adaptee) {<br>        self.adaptee = adaptee<br>    }<br>    <br>    override func request() -&gt; String {<br>        &quot;ADAPTER: (TRANSLATED) &quot; + adaptee.specificRequest().reversed()<br>    }<br>}<br><br>class Client {<br>    static func someClientCode(target: Target) {<br>        print(target.request())<br>    }<br>}<br><br>class TestAdapterConceptual {<br>    func testAdapterConceptual() {<br>        print(&quot;Client: I can work just fine with the Target objects:&quot;)<br>        Client.someClientCode(target: Target())<br>        <br>        let adaptee = Adaptee()<br>        print(&quot;Client: The Adaptee class has a weird interface. See, i dont understand it.&quot;)<br>        print(&quot;Adaptee: &quot; + adaptee.specificRequest())<br>        print(&quot;Client: But i can work with it via the Adapter:&quot;)<br>        Client.someClientCode(target: Adapter(adaptee))<br>    }<br>}<br>let test = TestAdapterConceptual()<br>test.testAdapterConceptual()</pre><h4>Real World Example</h4><pre>import UIKit<br><br>protocol AuthService {<br>    func presentAuthFlow(from viewController: UIViewController)<br>}<br><br>class FacebookAuthSDK {<br>    func presentAuthFlow(from viewController: UIViewController) {<br>        print(&quot;Facebook WebView has been shown.&quot;)<br>    }<br>}<br>extension FacebookAuthSDK: AuthService {<br>    /// This extension tells compiler that both SDKs have the same interface.<br>}<br><br>class XAuthSDK {<br>    func startAuthorization(with viewController: UIViewController) {<br>        print(&quot;X WebView has been shown. Users will be happy.&quot;)<br>    }<br>}<br>extension XAuthSDK: AuthService {<br>    /// This is an Adapter<br>    ///<br>    /// Yeah, we are able to not create another class and just an existing one.<br>    func presentAuthFlow(from viewController: UIViewController) {<br>        print(&quot;The Adapter is called! Redirecting to the original method...&quot;)<br>        self.startAuthorization(with: viewController)<br>    }<br>}<br><br>class TestAdapterRealWorld {<br>    func testAdapterRealWorld() {<br>        print(&quot;Starting an authorization via Facebook&quot;)<br>        startAuthorization(with: FacebookAuthSDK())<br>        print(&quot;Starting an authorization via X&quot;)<br>        startAuthorization(with: XAuthSDK())<br>    }<br>    <br>    func startAuthorization(with service: AuthService) {<br>        let topViewController = UIViewController()<br>        service.presentAuthFlow(from: topViewController)<br>    }<br>}<br>let test = TestAdapterRealWorld()<br>test.testAdapterRealWorld()</pre><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=062ce375d234" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/adapter-design-pattern-062ce375d234">Adapter Design Pattern</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Builder Design Pattern]]></title>
            <link>https://blog.stackademic.com/builder-design-pattern-664897458f18?source=rss-6ca908bc68e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/664897458f18</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[builder-pattern]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Ahmet Tarik DÖNER]]></dc:creator>
            <pubDate>Mon, 04 Nov 2024 20:44:47 GMT</pubDate>
            <atom:updated>2024-11-07T01:44:52.284Z</atom:updated>
            <content:encoded><![CDATA[<h4>The <strong>Builder</strong> pattern is a creational design pattern that lets you construct complex objects step by step. It enables you to produce different types and representations of an object using the same construction code.</h4><p>Complexity: ⭐️⭐️★<br>Popularity: ⭐️⭐️⭐️</p><h4>The Problem Builder Solves</h4><p>Imagine you’re creating a complex object that requires laborious, step-by-step initialization of many fields and nested objects. Let’s use a smartphone configuration system as an example.</p><p>A basic smartphone might need: a processor, memory, storage, screen, battery, camera… But if a customer wants additional features like: dual cameras, extended battery, extra storage, 5G capability, wireless charging, biometric security(seems like wants an iPhone right? 📱)</p><p>The simple solution is to extend base SmartPhone class and create a set of subclasses to cover all combinations. This approach has a significant drawback which is creating a subclass for each possible combination of features would lead to an enormous number of classes. Alright, what if we create a single constructor with all possible parameters? Yeah, this approach eliminates subclasses but it would be unwieldy and confusing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UTAKY8nOEJWQxP4GzgWVdw.png" /><figcaption>The initializer with lots of parameters has its downsides: not all the parameters are needed at all time.</figcaption></figure><p>Most of these parameters would be unused in any given instance, making the code messy and error-prone.</p><h4>The Builder Solution</h4><p>The Builder pattern suggests extracting the object construction code out of its own class and moving it to separate objects called builders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*leeEeDogs_Hv6sHtOZ6qpg.png" /><figcaption>Builder pattern lets you construct complex object step-by-step. The Builder doesn&#39;t allow the other object to access to the product while it&#39;s being built.</figcaption></figure><p>To create an object, you invoke a series of steps on a builder object, calling only the steps you need. Some steps may require different implementations, so you can create multiple builder classes that implement the same set of construction steps in various ways.</p><p>However, this works only if the client code interacts with the builders through a shared interface.</p><p><strong>The Director</strong></p><p>You can take this approach further by introducing a <strong>Director</strong> class. The Director defines the order in which to execute the building steps, while the builder implements each step. The Director isn’t always necessary, but it can be helpful for reusing certain construction routines and concealing the construction details from the client code. With a Director, the client only needs to associate a builder with the Director, trigger the construction process, and obtain the result from the builder.</p><h4>The Builder Structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JuVxAq-V60WYSPRZf4c1gA.png" /><figcaption>Structure of Builder</figcaption></figure><h4>Domain of Applicability</h4><ul><li><strong>To avoid telescoping constructors</strong>: If you have a constructor with numerous optional parameters, the Builder pattern allows you to build objects step-by-step, only using the steps necessary for your configuration.</li><li><strong>To create different representations of an object</strong>: This pattern is useful when building various representations of an object involves similar steps that differ only in specific details.</li></ul><p>How does the Builder Implements:</p><ol><li><strong>Define common construction steps</strong> for building all available representations of the product.</li><li><strong>Declare these steps in a base builder interface</strong>.</li><li><strong>Create concrete builder classes</strong> for each product representation, implementing the steps required for each. Be sure to add a method for retrieving the final product. This retrieval method is usually not part of the base builder interface, as different builders may return different types.</li><li><strong>Consider creating a Director class</strong> if there is a need to organize and control the construction sequence.</li><li>The client creates both the builder and the Director. Before starting construction, the client assigns the builder to the Director, often via parameters in the Director’s constructor.</li><li><strong>Retrieve the constructed object</strong>: If all products follow a common interface, the Director can return the result directly; otherwise, the client should get the final product from the builder.</li></ol><h4>Conceptual Example</h4><pre>import Cocoa<br><br>/// Builder interface specifies methods for creating the different parts of the Product object.<br>protocol Builder {<br>    func producePartA()<br>    func producePartB()<br>    func producePartC()<br>}<br><br>/// ConcreteBuilder classes follow the Builder interface and provide specific implementation<br>/// of the building steps. Your program may have several variations of Builders, implemented differently.<br>class ConcreteBuilder1: Builder {<br>    /// A fresh builder instance should contain a blank product object,  which is used in further assembly.<br>    private var product = Product1()<br>    <br>    func producePartA() {<br>        product.add(part: &quot;PartA1&quot;)<br>    }<br>    /// All production steps work with the same product instance.<br>    func producePartB() {<br>        product.add(part: &quot;PartB1&quot;)<br>    }<br>    <br>    func producePartC() {<br>        product.add(part: &quot;PartC1&quot;)<br>    }<br>    <br>    func reset() {<br>        product = Product1()<br>    }<br>    <br>    /// Concrete Builders are supposed to provide their own methods for retrieving results. That&#39;s because various types of builders may create<br>    /// entirely different product that don&#39;t follow the same interface. Therefore, such methods cannot be declared in the base Builder interface.<br>    ///<br>    /// Usually, after returning the end result to client, a builder instance is expected to be ready to start producing another product.That&#39;s why it&#39;s a usual practice<br>    /// to call the reset method at the end of the &#39;getProduct&#39; method body. However, this behavior is not mandatory.<br>    /// You can make your builders wait for an explicit reset call from the client code before disposing the previous result.<br>    func retrieveProduct() -&gt; Product1 {<br>        let result = self.product<br>        reset()<br>        <br>        return result<br>    }<br>}<br><br>/// Director is only responsible for executing the building steps in a particular sequence. It is helpful<br>/// when producing products according to specific order or configuration. Strictly speaking, the Director class is optional<br>/// , since the client can control builders directly.<br>class Director {<br>    private var builder: Builder?<br>    <br>    /// Director works with any builder instance that the client code passes to it.<br>    /// This way the client code may alter the final type of newly assembled product.<br>    func update(builder: Builder) {<br>        self.builder = builder<br>    }<br>    <br>    func buildMinimalViableProduct() {<br>        builder?.producePartA()<br>    }<br>    <br>    func buildFullFeaturedProduct() {<br>        builder?.producePartA()<br>        builder?.producePartB()<br>        builder?.producePartC()<br>    }<br>}<br><br>/// Make sense to use Builder pattern only when your products are quite complex and require extensive configurations.<br>/// Unlike in other creational patterns, different concrete builders can produce unrelated products. In other words, results of<br>/// various builders may not always follows the same interface.<br>class Product1 {<br>    private var parts = [String]()<br>    <br>    func add(part: String) {<br>        self.parts.append(part)<br>    }<br>    <br>    func listsPart() -&gt; String {<br>        &quot;Product parts: &quot; + parts.joined(separator: &quot;, &quot;) + &quot;\n&quot;<br>    }<br>}<br><br><br>class Client {<br>    static func someClientCode(director: Director) {<br>        let builder = ConcreteBuilder1()<br>        director.update(builder: builder)<br>        print(&quot;Standart basic product:&quot;)<br>        director.buildMinimalViableProduct()<br>        print(builder.retrieveProduct().listsPart())<br>        /// Remember, builder pattern can be used without a director class<br>        print(&quot;Custom Product: &quot;)<br>        builder.producePartA()<br>        builder.producePartC()<br>        print(builder.retrieveProduct().listsPart())<br>    }<br>}<br><br>class TestBuilderConceptual {<br>    func test() {<br>        let director = Director()<br>        Client.someClientCode(director: director)<br>    }<br>}<br>let test = TestBuilderConceptual()<br>test.test()</pre><h4>Real World Example</h4><pre>import Foundation<br><br>class BaseQueryBuilder&lt;Model: DomainModel&gt; {<br>    typealias Predicate = (Model) -&gt; Bool<br>    <br>    func limit(_ limit: Int) -&gt; BaseQueryBuilder&lt;Model&gt; {<br>        return self<br>    }<br>    <br>    func filter(_ predicate: @escaping Predicate) -&gt; BaseQueryBuilder&lt;Model&gt; {<br>        return self<br>    }<br>    <br>    func fetch() -&gt; [Model] {<br>        preconditionFailure(&quot;Should be overridden in subclasses.&quot;)<br>    }<br>}<br><br>class RealmQueryBuilder&lt;Model: DomainModel&gt;: BaseQueryBuilder&lt;Model&gt; {<br>    fileprivate var operations = [Query]()<br>    enum Query {<br>        case filter(Predicate)<br>        case limit(Int)<br>    }<br>    <br>    @discardableResult<br>    override func limit(_ limit: Int) -&gt; BaseQueryBuilder&lt;Model&gt; {<br>        operations.append(Query.limit(limit))<br>        return self<br>    }<br>    <br>    @discardableResult<br>    override func filter(_ predicate: @escaping Predicate) -&gt; BaseQueryBuilder&lt;Model&gt; {<br>        operations.append(Query.filter(predicate))<br>        return self<br>    }<br>    <br>    override func fetch() -&gt; [Model] {<br>        print(&quot;RealmQueryBuilder: Initializing RealmDataProvider with \(operations.count) operations&quot;)<br>        return RealmProvider().fetch(operations)<br>    }<br>}<br><br>class CoreDataQueryBuilder&lt;Model: DomainModel&gt;: BaseQueryBuilder&lt;Model&gt; {<br>    enum Query {<br>        case filter(Predicate)<br>        case limit(Int)<br>        case includesPropertyValues(Bool)<br>        /// ...<br>    }<br>    <br>    fileprivate var operations = [Query]()<br>    <br>    override func limit(_ limit: Int) -&gt; CoreDataQueryBuilder&lt;Model&gt; {<br>        operations.append(Query.limit(limit))<br>        return self<br>    }<br>    <br>    override func filter(_ predicate: @escaping Predicate) -&gt; CoreDataQueryBuilder&lt;Model&gt; {<br>        operations.append(Query.filter(predicate))<br>        return self<br>    }<br>    <br>    func includesPropertyValues(_ toggle: Bool) -&gt; CoreDataQueryBuilder&lt;Model&gt; {<br>        operations.append(Query.includesPropertyValues(toggle))<br>        return self<br>    }<br>    <br>    override func fetch() -&gt; [Model] {<br>        print(&quot;CoreDataQueryBuilder: Initializing CoreDataProvider with \(operations.count) operations.&quot;)<br>        return CoreDataProvider().fetch(operations)<br>    }<br>}<br><br>class CoreDataProvider {<br><br>    func fetch&lt;Model: DomainModel&gt;(_ operations: [CoreDataQueryBuilder&lt;Model&gt;.Query]) -&gt; [Model] {<br><br>        /// Create a NSFetchRequest<br><br>        print(&quot;CoreDataProvider: Retrieving data from CoreData...&quot;)<br><br>        for item in operations {<br>            switch item {<br>            case .filter(_):<br>                print(&quot;CoreDataProvider: executing the &#39;filter&#39; operation.&quot;)<br>                /// Set a &#39;predicate&#39; for a NSFetchRequest.<br>                break<br>            case .limit(_):<br>                print(&quot;CoreDataProvider: executing the &#39;limit&#39; operation.&quot;)<br>                /// Set a &#39;fetchLimit&#39; for a NSFetchRequest.<br>                break<br>            case .includesPropertyValues(_):<br>                print(&quot;CoreDataProvider: executing the &#39;includesPropertyValues&#39; operation.&quot;)<br>                /// Set an &#39;includesPropertyValues&#39; for a NSFetchRequest.<br>                break<br>            }<br>        }<br><br>        /// Execute a NSFetchRequest and return results.<br>        return []<br>    }<br>}<br><br>class RealmProvider {<br>    func fetch&lt;Model: DomainModel&gt;(_ operations: [RealmQueryBuilder&lt;Model&gt;.Query]) -&gt; [Model] {<br>        print(&quot;RealmProvider: Retrieving data from Realm...&quot;)<br>        for item in operations {<br>            switch item {<br>            case .filter(_):<br>                print(&quot;RealmProvider: executing the &#39;filter&#39; operation.&quot;)<br>                /// Use Realm instance to filter results.<br>                break<br>            case .limit(_):<br>                print(&quot;RealmProvider: executing the &#39;limit&#39; operation.&quot;)<br>                /// Use Realm instance to limit results.<br>                break<br>            }<br>        }<br>        /// Return results from Realm<br>        return []<br>    }<br>}<br><br>protocol DomainModel {<br>    /// The protocol groups domain models to the common interface.<br>}<br><br>private struct User: DomainModel {<br>    let id: Int<br>    let age: Int<br>    let email: String<br>}<br><br>import XCTest<br><br>class BuilderRealWorld: XCTestCase {<br><br>    func testBuilderRealWorld() {<br>        print(&quot;Client: Start fetching data from Realm&quot;)<br>        clientCode(builder: RealmQueryBuilder&lt;User&gt;())<br><br>        print()<br><br>        print(&quot;Client: Start fetching data from CoreData&quot;)<br>        clientCode(builder: CoreDataQueryBuilder&lt;User&gt;())<br>    }<br><br>    fileprivate func clientCode(builder: BaseQueryBuilder&lt;User&gt;) {<br><br>        let results = builder.filter({ $0.age &lt; 20 })<br>            .limit(1)<br>            .fetch()<br><br>        print(&quot;Client: I have fetched: &quot; + String(results.count) + &quot; records.&quot;)<br>    }<br>}<br>let test = BuilderRealWorld()<br>test.testBuilderRealWorld()</pre><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=664897458f18" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/builder-design-pattern-664897458f18">Builder Design Pattern</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Abstract Factory Design Pattern]]></title>
            <link>https://blog.stackademic.com/abstract-factory-design-pattern-d72489046d1f?source=rss-6ca908bc68e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/d72489046d1f</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[abstract-factory-pattern]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Ahmet Tarik DÖNER]]></dc:creator>
            <pubDate>Mon, 04 Nov 2024 18:39:20 GMT</pubDate>
            <atom:updated>2024-11-07T01:45:45.871Z</atom:updated>
            <content:encoded><![CDATA[<h4>The <strong>Abstract Factory</strong> pattern is a creational design pattern that allows you to produce families of related objects without specifying their concrete classes. This pattern is particularly useful when your code needs to work with various families of related products, and you want to avoid depending on the specific implementations of those products.</h4><p>Complexity: ⭐️⭐️★<br>Popularity: ⭐️⭐️⭐️</p><h4>The Problem Abstract Factory Solves</h4><p>Imagine you’re building a furniture app simulator. Your codebase consists of classes that represent:</p><ol><li>A family of related furniture products, such as <strong>Table</strong>, <strong>Bookshelf</strong>, and <strong>Armchair</strong>.</li><li>Multiple style options for each product, like <strong>Industrial</strong>, <strong>Scandinavian</strong>, and <strong>Minimalist</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AxoxYxxecPhnm7-8akTsMQ.png" /><figcaption>Product families and their variants</figcaption></figure><p>You need a way to create individual furniture items that match the style of other items in the same family, ensuring a cohesive look for each style. At the same time, you want the flexibility to add new styles or furniture types without modifying existing code.</p><h4>The Abstract Factory Solution</h4><p>The first thing Abstract Factory suggests defining interfaces for each type of furniture item, such as Table, Bookshelf, and Armchair. This way, all variations of a Table, for example, implement a shared Table interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bXxHir2wH5ADKCGnrWjJtA.png" /><figcaption>All variants of the same object must be moved to the single class hierarchy.</figcaption></figure><p>Next, you define an <strong>Abstract Factory</strong> interface with methods for creating each type of furniture (e.g., createTable(), createBookshelf()). These methods return abstract product types, which are defined by the furniture interfaces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q2WzDNJ-zpKeizmPguRPnw.png" /><figcaption>Each concrete factory corresponds a specific product variant.</figcaption></figure><p>For each style, you create a separate factory class based on the Abstract Factory interface. For example, the IndustrialFurnitureFactory class would create only IndustrialTable, IndustrialBookshelf, and IndustrialArmchair objects. Similarly, the ScandinavianFurnitureFactory would create ScandinavianTable, ScandinavianBookshelf, and ScandinavianArmchair.</p><p>This approach allows client code to work with furniture items through abstract interfaces, without needing to know the specific class. If the client requests a Table, it doesn’t matter whether the factory is IndustrialFurnitureFactory or ScandinavianFurnitureFactory; the client only knows that the Table returned will have specific methods, like hasDrawer().</p><p>To select a particular style, the app initializes a specific factory object at startup based on user choice or app configuration. This factory object is then passed to the client code, allowing it to create all products in the selected style family.</p><h4>The Abstract Factory Structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x7ITigAbX-krJ6WUUdMw5A.png" /><figcaption>Structure of Abstract Factory</figcaption></figure><h4>Domain of Applicability</h4><ul><li><strong>When your code needs to work with different families of related products but shouldn’t depend on the concrete classes of those products</strong>: The Abstract Factory allows the client code to create objects from a specific family without knowing their exact classes.</li><li><strong>When a class has too many Factory Methods, which could blur its primary purpose</strong>: Each class should ideally handle a single responsibility. If a class is responsible for creating multiple product types, it may be worth extracting these methods into a dedicated factory class or implementing the Abstract Factory pattern.</li></ul><h4>How does the Abstract Factory Implements:</h4><ol><li><strong>Map out a matrix</strong> of product types and their style variations.</li><li><strong>Define abstract product interfaces</strong> for each product type, and ensure all concrete product classes implement these interfaces.</li><li><strong>Declare an Abstract Factory interface</strong> with methods to create each product type as an abstract product.</li><li><strong>Implement concrete factory classes</strong> for each style, ensuring they create only products of that particular style.</li><li><strong>Initialize a concrete factory</strong> at application startup based on configuration or user settings, and pass this factory to relevant parts of the app.</li><li><strong>Replace direct constructor calls</strong> throughout the code with calls to the factory’s creation methods, promoting flexibility and uniformity.</li></ol><h4>Conceptual Example</h4><pre>import Foundation<br><br>//  MARK: - AbstractFactory Interface:<br>/// Abstract Factory protocol declares a set of methods that return different abstract products.<br>/// These products are called a family and are related by a high-level theme or concept.<br>/// Products of one family are usually able to collaborate among themselves.<br>/// A family of products may have several variants, but the products of one variant are incompatible with<br>/// products  of another.<br>protocol AbstractFactory {<br>    func createProductA() -&gt; AbstractProductA<br>    func createProductB() -&gt; AbstractProductB<br>}<br><br>//  MARK: - ConcreteFactory Classes:<br>/// Concrete Factories produce a family of products that belong to a  single variant.<br>/// The factory guarentees that resulting products are compatible. Note signature of ConcreteFactory<br>/// method return an abstract product, while inside the method a concrete product is instantiated.<br>class ConcreteFactory1: AbstractFactory {<br>    func createProductA() -&gt; AbstractProductA {<br>        ConcreteProductA1()<br>    }<br>    <br>    func createProductB() -&gt; AbstractProductB {<br>        ConcreteProductB1()<br>    }<br>}<br>/// Each ConcreteFactory clas has a corresponding product variant.<br>class ConcreteFactory2: AbstractFactory {<br>    func createProductA() -&gt; AbstractProductA {<br>        ConcreteProductA2()<br>    }<br>    <br>    func createProductB() -&gt; AbstractProductB {<br>        ConcreteProductB2()<br>    }<br>}<br><br><br><br><br>//  MARK: - AbstractProduct Interfaces:<br>/// Each distinct product of a product family should have a base protocol. All variants<br>/// of the product must implement this protocol.<br>protocol AbstractProductA {<br>    func usefulFunctionA() -&gt; String<br>}<br><br>//  MARK: - ConcreteProducts:<br>/// ConcreteProducts are created by correspoding ConcreteFactories.<br>class ConcreteProductA1: AbstractProductA {<br>    func usefulFunctionA() -&gt; String {<br>        &quot;The result of product A1&quot;<br>    }<br>}<br>class ConcreteProductA2: AbstractProductA {<br>    func usefulFunctionA() -&gt; String {<br>        &quot;The result of product A2&quot;<br>    }<br>}<br><br><br><br><br>/// Base protocol of another product. All products can interact with each other, but proper interaction<br>/// is possible only between products of the same concrete variants.<br>protocol AbstractProductB {<br>    /// Product B is able to do its own thing...<br>    func usefulFunctionB() -&gt; String<br>    <br>    /// ... but it also can calloborate with productA<br>    /// Abstract Factory makes sure that all products it creates are of the same variant and thus, compatible.<br>    func anotherUsefulFunctionB(collaborator: AbstractProductA) -&gt; String<br>}<br><br>//  MARK: - ConcreteProducts:<br>/// ConcreteProducts are created by corresponding Concrete Factories.<br>class ConcreteProductB1: AbstractProductB {<br>    func usefulFunctionB() -&gt; String {<br>        &quot;The result of the product B1.&quot;<br>    }<br>    <br>    /// This variant, ProductB1, is only able to work correctly with the variant, ProductA1. Nevertheless,<br>    /// it accepts any instance of AbstractProductA as an argument.<br>    func anotherUsefulFunctionB(collaborator: AbstractProductA) -&gt; String {<br>        let result = collaborator.usefulFunctionA()<br>        <br>        return &quot;The result of the B1 collaborating with the (\(result))&quot;<br>    }<br>}<br>class ConcreteProductB2: AbstractProductB {<br>    func usefulFunctionB() -&gt; String {<br>        &quot;The result of the product B2.&quot;<br>    }<br>    /// This variant, ProductB2, is only able to work correctly with the variant, ProductA2. Nevertheless,<br>    /// it accepts any instance of AbstractProductA as an argument.<br>    func anotherUsefulFunctionB(collaborator: AbstractProductA) -&gt; String {<br>        let result = collaborator.usefulFunctionA()<br>        <br>        return &quot;The result of the B2 collaborating with the (\(result))&quot;<br>    }<br>}<br><br><br><br><br>//  MARK: - Client:<br>/// Client  works with factories and products only through abstract types: AbstractFactory and AbstractProduct.<br>/// This lets you pass any factory or product subclass to the client code without breaking it.<br>class Client {<br>    static func someClientCode(factory: AbstractFactory) {<br>        let productA = factory.createProductA()<br>        let productB = factory.createProductB()<br>        print(productB.usefulFunctionB())<br>        print(productB.anotherUsefulFunctionB(collaborator: productA))<br>    }<br>}<br><br>class TestAbstractFactoryConceptual {<br>    func test() {<br>        print(&quot;Client: Testing client code with the first factory type:&quot;)<br>        Client.someClientCode(factory: ConcreteFactory1())<br>        print(&quot;Client: Testing the same client code with the second factory type:&quot;)<br>        Client.someClientCode(factory: ConcreteFactory2())<br>    }<br>}<br>let test = TestAbstractFactoryConceptual()<br>test.test()</pre><h4>Real World Example</h4><pre>import UIKit<br>import Foundation<br><br>enum AuthType {<br>    case login<br>    case signUp<br>}<br><br>//  MARK: - AbstractAuthViewFactory Interface<br>protocol AuthViewFactory {<br>    static func authView(for type: AuthType) -&gt; AuthView<br>    static func authController(for type: AuthType) -&gt; AuthViewController<br>}<br><br>//  MARK: - ConcreteAuthViewFactory1<br>class StudentAuthViewFactory: AuthViewFactory {<br>    static func authView(for type: AuthType) -&gt; AuthView {<br>        print(&quot;StudentView has been created.&quot;)<br>        switch type {<br>        case .login:<br>            return StudentLoginView()<br>        case .signUp:<br>            return StudentSignUpView()<br>        }<br>    }<br>    <br>    static func authController(for type: AuthType) -&gt; AuthViewController {<br>        let controller = StudentAuthViewController(contentView: authView(for: type))<br>        print(&quot;StudentViewController has been created.&quot;)<br>        <br>        return controller<br>    }<br>}<br>//  MARK: - ConcreteAuthViewFactory2<br>class TeacherAuthViewFactory: AuthViewFactory {<br>    static func authView(for type: AuthType) -&gt; AuthView {<br>        print(&quot;StudentView has been created.&quot;)<br>        switch type {<br>        case .login:<br>            return TeacherLoginView()<br>        case .signUp:<br>            return TeacherSignUpView()<br>        }<br>    }<br>    <br>    static func authController(for type: AuthType) -&gt; AuthViewController {<br>        let controller = TeacherAuthViewController(contentView: authView(for: type))<br>        print(&quot;TeacherViewController has been created.&quot;)<br>        <br>        return controller<br>    }<br>}<br><br>//  MARK: - AbstractAuthView Interface<br>protocol AuthView {<br>    typealias AuthAction = (AuthType) -&gt; Void<br>    <br>    var contentView: UIView { get }<br>    var authHandler: AuthAction? { get set }<br>    var description: String { get }<br>}<br><br>//  MARK: - ConcreteStudentSingUpView<br>class StudentSignUpView: UIView, AuthView {<br><br>    var contentView: UIView = StudentSignUpContentView()<br>    /// The handler will be connected for actions of buttons of this view.<br>    var authHandler: AuthView.AuthAction?<br>    <br>    private class StudentSignUpContentView: UIView {<br>        /// This view contains a number of features available only during a student authorization.<br>    }<br>    <br>    override var description: String {<br>        return &quot;Student-SignUp-View&quot;<br>    }<br>}<br>//  MARK: - ConcreteStudentLoginView<br>class StudentLoginView: UIView, AuthView {<br>    private let emailField = UITextField()<br>    private let passwordField = UITextField()<br>    private let signUpButton = UIButton()<br>    <br>    var authHandler: AuthView.AuthAction?<br>    var contentView: UIView {<br>        self<br>    }<br>    <br>    override var description: String {<br>        &quot;Student-Login-View&quot;<br>    }<br>}<br>//  MARK: - ConcreteTeacherSingUpView<br>class TeacherSignUpView: UIView, AuthView {<br><br>    var contentView: UIView = TeacherSignUpContentView()<br>    var authHandler: AuthView.AuthAction?<br>    <br>    private class TeacherSignUpContentView: UIView {<br>        /// This view contains a number of features available only during a teacher authorization.<br>    }<br>    <br>    override var description: String {<br>        return &quot;Teacher-SignUp-View&quot;<br>    }<br>}<br>//  MARK: - ConcreteTeacherLoginView<br>class TeacherLoginView: UIView, AuthView {<br>    private let emailField = UITextField()<br>    private let passwordField = UITextField()<br>    private let loginButton = UIButton()<br>    private let forgotPasswordButton = UIButton()<br>    <br>    var authHandler: AuthView.AuthAction?<br>    var contentView: UIView {<br>        self<br>    }<br>    <br>    override var description: String {<br>        &quot;Teacher-Login-View&quot;<br>    }<br>}<br><br><br>class AuthViewController: UIViewController {<br>    fileprivate var contentView: AuthView<br>    <br>    init(contentView: AuthView) {<br>        self.contentView = contentView<br>        super.init(nibName: nil, bundle: nil)<br>    }<br>    <br>    required convenience init?(coder: NSCoder) {<br>        nil<br>    }<br>}<br><br>class StudentAuthViewController: AuthViewController {<br>    /// Student oriented features<br>}<br>class TeacherAuthViewController: AuthViewController {<br>    /// Teacher oriented features<br>}<br><br><br>//  MARK: - ClientCode:<br>private class ClientCode {<br>    private var currentController: AuthViewController?<br>    private let factoryType: AuthViewFactory.Type<br>    <br>    private lazy var navigationController: UINavigationController = {<br>        guard let viewController = currentController else { return UINavigationController() }<br>        <br>        return UINavigationController(rootViewController: viewController)<br>    }()<br>    <br>    init(factoryType: AuthViewFactory.Type) {<br>        self.factoryType = factoryType<br>    }<br>    <br>    func presentLogin() {<br>        let controller = factoryType.authController(for: .login)<br>        navigationController.pushViewController(controller, animated: true)<br>    }<br>    <br>    func presentSignUp() {<br>        let controller = factoryType.authController(for: .login)<br>        navigationController.pushViewController(controller, animated: true)<br>    }<br>}<br><br>import XCTest<br><br>class TestAbstractFactoryRealWorld: XCTestCase {<br>    func test() {<br>        #if teacherMode<br>        let clientCode = ClientCode(factoryType: TeacherAuthViewFactory.self)<br>        #else<br>        let clientCode = ClientCode(factoryType: StudentAuthViewFactory.self)<br>        #endif<br>        clientCode.presentLogin()<br>        print(&quot;Login screen has been presented.&quot;)<br>        clientCode.presentSignUp()<br>        print(&quot;SingUp screen has been presented.&quot;)<br>    }<br>}<br>let test = TestAbstractFactoryRealWorld()<br>test.test()</pre><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d72489046d1f" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/abstract-factory-design-pattern-d72489046d1f">Abstract Factory Design Pattern</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Factory Method Design Pattern]]></title>
            <link>https://blog.stackademic.com/factory-method-design-pattern-764a924a9248?source=rss-6ca908bc68e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/764a924a9248</guid>
            <category><![CDATA[factory-method-pattern]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Ahmet Tarik DÖNER]]></dc:creator>
            <pubDate>Mon, 04 Nov 2024 16:05:35 GMT</pubDate>
            <atom:updated>2024-11-07T01:45:57.782Z</atom:updated>
            <content:encoded><![CDATA[<h4>One of the fundamental creational design patterns is the Factory Method. This pattern provides an interface for creating objects, but allows subclasses to alter the type of objects that will be created. In other words, the Factory Method pattern lets you delegate object creation to subclasses. This approach decouples the client code from the specifics of object creation, enabling flexibility and easier maintenance.</h4><p>Complexity: ⭐️★★<br>Popularity: ⭐️⭐️⭐️</p><h4><strong>The Problem Factory Method Solves</strong></h4><p>Imagine you&#39;re building a document processing application. Initially, your app only handles PDF documents, so the majority of your codebase is focused on the PDFDocument class.</p><p>As your application grows, you&#39;re asked to add support for other document formats like Word (.docx) and Markdown (.md). But your existing code is tightly coupled to the PDFDocument class, making it difficult to incorporate the new WordDocument and MarkdownDocument classes. Modifying the app to work with multiple document types would require changing a significant portion of your codebase, introducing conditional logic and complex switching app behavior between document objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wym2i3Lq3Nd5fha9427NRg.png" /><figcaption>Adding a new class to the program isn&#39;t that simple if the rest of code is already coupled to existing classes.</figcaption></figure><h4>The Factory Method Solution</h4><p>The Factory Method pattern suggests that you replace direct object construction calls with calls to a special factory method. The objects are then created within the factory method itself. These objects returned by the factory method are often referred to as “<em>products.</em>”</p><p>At first glance, this change might seem trivial — you’re just moving the constructor call to another part of the code. However, the real power of the Factory Method lies in the ability to override the factory method in subclasses and change the class of the products being created.</p><p>There’s a caveat: the products returned by the factory method must share a common base class or interface. The factory method in the base class should also have a return type declared as this interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rckZ5C5J0ondvghAMq95Ng.png" /><figcaption>All products must follow the same interface.</figcaption></figure><p>Each class implements this method differently. The factory method in PDFDocProcessor class returns the PDFDocument, whereas WordDocProcessor class returns WordDocument and MDDocProcessor class returns MarkDownDocument.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gu07GwY9hlxiSE7VErdIeA.png" /><figcaption>As long as all product classes implement a common interface, you can pass their object to the client code without breaking it.</figcaption></figure><p>The client code that uses the factory method (often called “client code”) doesn’t need to know the specific type of document object it’s working with — it only knows that the returned objects implement the common DocumentProcessor interface.</p><h4>The Factory Method Structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2wDVu3f4YsPcWLPJ6e_big.png" /><figcaption>Structure diagram of the Factory Method</figcaption></figure><h4>Domain of Applicability</h4><ul><li><strong>When you don’t know beforehand the exact types and dependencies of the objects your code should work with.</strong> The Factory Method allows you to create objects without exposing the creation logic to the client.</li><li><strong>When you want to save system resources by reusing existing objects instead of rebuilding them each time.</strong> The Factory Method can help you implement an object pool to manage and reuse objects.</li></ul><h4>How does the Factory Method Implements:</h4><ol><li><strong>Define a common interface for all products</strong>: This interface should include methods that all products will implement.</li><li><strong>Add an empty factory method to the creator class</strong>: The return type of this method should match the common product interface.</li><li><strong>Replace product constructor calls with the factory method</strong>: Update the creator class to use the factory method instead of directly calling constructors.</li><li><strong>Create subclasses for each product type</strong>: For each product, create a subclass that overrides the factory method, injecting the specific construction code for that product.</li><li><strong>Use a control parameter if there are many product types</strong>: If creating a subclass for each product type is not feasible, consider using a parameter in the base class to manage product creation.</li><li><strong>Make the base factory method abstract if it’s no longer needed</strong>: Once subclasses handle all specific product creation, you can simplify the base class by making the factory method abstract.</li></ol><h4>Conceptual Example</h4><pre>//  MARK: - Product Interface<br>/// Product protocol declares the operations that all concrete products must implement.<br>protocol Product {<br>    func operation() -&gt; String<br>}<br><br>//  MARK: - Concrete Products<br>/// Concrete Products provide various implementations of the Product protocol.<br>class ConcreteProduct1: Product {<br>    func operation() -&gt; String {<br>        &quot;Result of the ConcreteProduct1&quot;<br>    }<br>}<br>class ConcreteProduct2: Product {<br>    func operation() -&gt; String {<br>        &quot;Result of the ConcreteProduct2&quot;<br>    }<br>}<br><br>//  MARK: - Creator<br>/// Creator protocol declares the factory method that&#39;s supposed to return a new object of a Product class.<br>/// The Creator&#39;s subclasses usually provide the implementation of this method<br>protocol Creator {<br>    func factoryMethod() -&gt; Product<br>    func someOperations() -&gt; String<br>}<br>/// Implement a default behavior. This behavior can be overridden in subclasses.<br>extension Creator {<br>    func someOperations() -&gt; String {<br>        let product = factoryMethod()<br>        <br>        return &quot;Creator: The same creator&#39;s code has just worked with &quot; + product.operation()<br>    }<br>}<br><br>/// Concrete Creators override the factory method in order to change the resulting product type.<br>class ConcreteCreator1: Creator {<br>    func factoryMethod() -&gt; Product {<br>        ConcreteProduct1()<br>    }<br>}<br>class ConcreteCreator2: Creator {<br>    func factoryMethod() -&gt; Product {<br>        ConcreteProduct2()<br>    }<br>}<br><br>class Client {<br>    static func someClientCode(creator: Creator) {<br>        print(&quot;Client: I don&#39;t care of the creator&#39;s class, but it still works.\n&quot; + creator.someOperations())<br>    }<br>}<br><br>class TestFactoryMethodConceptual {<br>    func test() {<br>        print(&quot;App: Launched with the ConcreteCreator1&quot;)<br>        Client.someClientCode(creator: ConcreteCreator1())<br>        print(&quot;\nApp: Launched with the ConcreteCreator2&quot;)<br>        Client.someClientCode(creator: ConcreteCreator2())<br>    }<br>}<br>let test = TestFactoryMethodConceptual()<br>test.test()</pre><h4>Real World Example</h4><pre>//  MARK: - Product Interface<br>/// Abstract projector interface.<br>protocol Projector {<br>    var currentPage: Int { get }<br>    <br>    func present(info: String)<br>    func sync(with projector: Projector)<br>    func update(with page: Int)<br>}<br>extension Projector {<br>    func sync(with projector: Projector) {<br>        projector.update(with: currentPage)<br>    }<br>}<br><br>//  MARK: - Concrete Products<br>class WiFiProjector: Projector {<br>    var currentPage: Int = 0<br>    <br>    func present(info: String) {<br>        print(&quot;Info is presented over WiFi: \(info)&quot;)<br>    }<br>    <br>    func update(with page: Int) {<br>        currentPage = page<br>    }<br>}<br><br>class BluetoothProjector: Projector {<br>    var currentPage: Int = 0<br>    <br>    func present(info: String) {<br>        print(&quot;Info is presented over Bluetooth: \(info)&quot;)<br>    }<br>    <br>    func update(with page: Int) {<br>        currentPage = page<br>    }<br>}<br><br>//  MARK: - Creator<br>protocol ProjectorFactory {<br>    func createProjector() -&gt; Projector<br>    func syncedProjector(with projector: Projector) -&gt; Projector<br>}<br>extension ProjectorFactory {<br>    func syncedProjector(with projector: Projector) -&gt; Projector {<br>        let newProjector = createProjector()<br>        newProjector.sync(with: projector)<br>        <br>        return newProjector<br>    }<br>}<br><br>//  MARK: - Concrete Creators<br>class WiFiFactory: ProjectorFactory {<br>    func createProjector() -&gt; Projector {<br>        WiFiProjector()<br>    }<br>}<br><br>class BluetoothFactory: ProjectorFactory {<br>    func createProjector() -&gt; Projector {<br>        BluetoothProjector()<br>    }<br>}<br><br>//  MARK: - ClientCode<br>private class ClientCode {<br>    private var currentProjector: Projector?<br>    <br>    func present(info: String, with factory: ProjectorFactory) {<br>        guard let projector = currentProjector else {<br>            let projector = factory.createProjector()<br>            projector.present(info: info)<br>            self.currentProjector = projector<br>            <br>            return<br>        }<br>        self.currentProjector = factory.syncedProjector(with: projector)<br>        self.currentProjector?.present(info: info)<br>    }<br>}<br><br>let info = &quot;Very important info of the presentation.&quot;<br>private let clientCode = ClientCode()<br>clientCode.present(info: info, with: WiFiFactory())<br>clientCode.present(info: info, with: BluetoothFactory())</pre><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=764a924a9248" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/factory-method-design-pattern-764a924a9248">Factory Method Design Pattern</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Design Patterns]]></title>
            <link>https://blog.stackademic.com/understanding-design-patterns-eeb7b7f7c431?source=rss-6ca908bc68e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/eeb7b7f7c431</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Ahmet Tarik DÖNER]]></dc:creator>
            <pubDate>Mon, 04 Nov 2024 13:03:06 GMT</pubDate>
            <atom:updated>2024-11-07T01:46:05.005Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>In the ever-evolving world of software development, engineers often encounter similar problems across different projects. Rather than reinventing the wheel each time, wouldn’t it be wonderful to have proven, reliable solutions ready to be implemented? This is where design patterns come into play.</strong></h4><h4>What are Design Patterns?</h4><p>Design patterns are elegant solutions to recurring problems in software design. Think of them as blueprints that experienced architects have refined over time — they’re not finished designs that can be directly copied into code, but rather templates that can be adapted to solve similar problems in different situations. These patterns represent the collective experience of software developers who have faced and solved similar problems before. <em>It&#39;s important to distinguish design patterns from algorithms.</em></p><h4><strong>Design Pattern vs Algorithm: Understanding the Distinction</strong></h4><p>Though both serve as tools in a developer’s toolkit, it’s important to distinguish between them. An <strong><em>algorithm</em></strong> is a well-defined sequence of steps aimed at solving a specific problem or performing a task. On the other hand, a <strong><em>design pattern</em></strong> is more conceptual, focusing on how components interact within a system. Patterns guide the structure of your code rather than the specific actions it takes.</p><ul><li><strong>Design Pattern</strong>: <em>A design pattern serves as a general reusable solution to a commonly occurring problem in software design. It captures the essence of a solution in a way that can be adapted to various context.</em></li><li><strong>Algorithm</strong>: <em>An algorithm is a step-by-step procedure or formula for solving a specific problem. It outlines a clear and finite set of actions that lead to a desired outcome.</em></li></ul><h4>Classification of Design Patterns</h4><p>Design patterns vary in complexity, level of detail, and application scope. Some are small-scale solutions, often called <strong>idioms</strong>, while others, known as <strong>architectural patterns</strong>, are high-level structures that can shape the entire architecture of an application.</p><p>We can broadly classify design patterns into three main categories:</p><ul><li><strong>Creational Patterns</strong>: These patterns offer mechanisms for creating objects in a way that promotes flexibility and reusability. By abstracting the instantiation process, they allow you to manage and reuse code efficiently.</li><li><strong>Structural Patterns</strong>: These patterns focus on assembling objects and classes into larger structures, while keeping those structures flexible and efficient. They help streamline complex relationships between different parts of a system.</li><li><strong>Behavioral Patterns</strong>: These patterns emphasize effective communication and responsibility distribution between objects. They ensure that components interact smoothly to carry out larger functionalities within a program.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B9QxAFZ1qKgNranKc5lN-w.png" /><figcaption>The Catalog of Design Patterns</figcaption></figure><p>In the continuation of this article series, we will cover the design patterns highlighted in the catalog above, which are frequently used in the industry. Additionally, a comprehensive article on the Singleton pattern will be shared in the future.</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eeb7b7f7c431" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/understanding-design-patterns-eeb7b7f7c431">Understanding Design Patterns</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Concurrency in Swift: A Comprehensive Guide for iOS Developers Part-2.]]></title>
            <link>https://blog.stackademic.com/mastering-concurrency-in-swift-a-comprehensive-guide-for-ios-developers-part-2-443b6dc5c37f?source=rss-6ca908bc68e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/443b6dc5c37f</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[operationqueue]]></category>
            <dc:creator><![CDATA[Ahmet Tarik DÖNER]]></dc:creator>
            <pubDate>Tue, 10 Sep 2024 20:34:27 GMT</pubDate>
            <atom:updated>2024-11-07T01:46:34.750Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8gpL8fF1T8KR2L7SotPSZQ.png" /></figure><h4><strong>Dispatch Groups</strong></h4><blockquote>In the world of iOS development, we often encounter scenarios where we need to manage multiple asynchronous tasks simultaneously. While dispatch queues allow us to execute tasks asynchronously or concurrently, there are situations where we need more control over a collection of related tasks. This is where <strong>Dispatch Groups</strong> come into play.</blockquote><p>Imagine you’re developing a splash screen for your app, and you need to make several API calls or download multiple images before proceeding. How do you ensure all these operations complete before moving forward? Dispatch Groups provide an elegant solution to this challenge.</p><p>Dispatch groups provide a powerful solution for managing such scenarios. By grouping related tasks together, you can:</p><ul><li>Execute multiple tasks as a cohesive unit</li><li>Wait for all the tasks in the group to finish before proceeding, or continue with other tasks while being notified when the group completes</li></ul><p>To leverage the power of Dispatch Groups, you’ll primarily work with four key methods:</p><ol><li>enter(): Signals that a task is being added to the group</li><li>leave(): Indicates that a task in the group has completed</li><li>wait(): You can hold the current thread’s execution until the tasks in the group are finished. Be cautious using .wait() on the main thread as it blocks execution. There’s also an option to include a timeout parameter.</li><li>notify(): Sets up a callback to be executed when all tasks in the group have completed</li></ol><p>Imagine a scenario where we want Process4 to run only after Process1, Process2, and Process3 have completed. By using a DispatchGroup, our workflow would look like this: Process1, Process2, and Process3 are grouped together and start simultaneously, and once all of them finish, Process4 will execute. This approach can significantly improve both time efficiency and performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KTzlmJ7-nEqEQlLyNoJxSQ.png" /><figcaption>An Illustration of Grouping Tasks together</figcaption></figure><p><strong>Methods &amp; Usage</strong></p><p>1 - Initialization</p><pre>let group = DispatchGroup()</pre><p>2 - Entering and Leaving a Group</p><pre>group.enter()<br>DispatchQueue.global().async {<br>    // Perform some asynchronous work<br>    group.leave() // Call leave when the work is done<br>}</pre><ul><li>When you want to start a task that should be tracked by the group, you call enter() on the group.</li><li>When that task finishes, you call leave() on the group.</li><li>These calls must always be balanced, meaning every enter() must have a corresponding leave().</li></ul><p>- Automatic Group Management</p><p>You can also add a block of code to the group directly using group.async</p><pre>DispatchQueue.global().async(group: group) {<br>    // Perform some asynchronous work<br>}</pre><p>This method automatically handles the enter() and leave() calls for you.</p><p>3 - Waiting for Completion</p><p><strong>Synchronous Wait:</strong> You can wait for all tasks in the group to complete by using the wait() method. This will block the current thread until all tasks are finished.group.wait(timeout:) allows you to specify a timeout for waiting.</p><pre>group.wait()</pre><p><strong>Asynchronous Notification:</strong> You can set a block of code to be executed once all the tasks in the group have completed using notify(queue:).</p><pre>group.notify(queue: .main) {<br>    // Code to execute once all tasks are complete<br>}</pre><p>Here are another two examples with custom created queues:</p><pre>let group = DispatchGroup()<br>let queue1 = DispatchQueue(label: &quot;com.example.queue1&quot;)<br>let queue2 = DispatchQueue(label: &quot;com.example.queue2&quot;)<br><br>queue1.async(group: group) {<br>    // Task 1<br>}<br><br>queue2.async(group: group) {<br>    // Task 2<br>}<br><br>group.notify(queue: .main) {<br>    print(&quot;Both tasks completed&quot;)<br>}<br><br><br>let dispatchGroup = DispatchGroup()<br>let concurrentQueue = DispatchQueue(label: &quot;com.example.queue&quot;, attributes: .concurrent)<br>// Tasks to be executed concurrently and monitored as a group<br>concurrentQueue.async(group: dispatchGroup) {<br>    print(&quot;Task 1: Start&quot;)<br>    print(&quot;Task 1 Thread&quot;, Thread.current)<br>    // Perform some work<br>    print(&quot;Task 1: End&quot;)<br>}<br><br>concurrentQueue.async(group: dispatchGroup) {<br>    print(&quot;Task 2: Start&quot;)<br>    print(&quot;Task 2 Thread&quot;, Thread.current)<br>    // Perform some work<br>    print(&quot;Task 2: End&quot;)<br>}<br><br>// Wait for all tasks in the group to finish<br>dispatchGroup.wait()<br>print(&quot;All tasks are done!&quot;)</pre><p><strong>Use Cases:</strong></p><ul><li><strong>Waiting for Multiple Asynchronous Operations<br></strong>For example, when downloading multiple files, you can use aDispatchGroup to trigger an action once all downloads are complete.</li><li><strong>Batch Processing</strong><br>You can start multiple tasks and wait for all of them to complete before moving on to the next step.</li><li><strong>Thread Synchronization</strong><br>Ensuring that certain pieces of code are executed only after multiple conditions are met.</li></ul><h4><strong>Dispatch Work Items</strong></h4><p>Similar to dispatch groups, Grand Central Dispatch (GCD) also provides dispatch work items. A dispatch work item allows you to encapsulate a block of code, turning it into a work item that can be dispatched to either a dispatch group or a dispatch queue. This gives you the flexibility to cancel a work item before its execution starts, which is particularly useful in situations where you might want to cancel tasks that are no longer relevant.</p><p>One of the key features of a dispatch work item is the ability to <strong><em>cancel </em></strong>it. For example, consider a scenario where you are implementing a search functionality. Typically, an API call is made every time a user types a letter in the search bar. However, the user might only be interested in the results after they finish typing. In this case, you can cancel any ongoing or pending API calls whenever a new letter is typed, preventing unnecessary network requests.</p><p><strong>How Canceling Works?</strong></p><ul><li>If you set the cancel property to true before the execution starts, the task will not be executed.</li><li>If the work item is canceled during execution, the isCancelled property will return true, but the system will not abort the execution. The code block will run to completion.</li></ul><pre>final class SearchController {<br>    var workItem: DispatchWorkItem?<br>    <br>    // Gets triggered everytime when user types new letter<br>    func getSearchResults(for query: String) {<br>        workItem?.cancel()<br>        let newWorkItem = DispatchWorkItem {<br>            print(&quot;Sent a request for \(query)&quot;)<br>            // Async task to fetch results based on query<br>        }<br>        workItem = newWorkItem<br>        DispatchQueue.global().asyncAfter(<br>            deadline: .now() + .milliseconds(50),<br>            execute: newWorkItem<br>        )<br>    }<br>}<br><br>let searchController = SearchController()<br>searchController.getSearchResults(for: &quot;c&quot;)<br>searchController.getSearchResults(for: &quot;co&quot;)<br>searchController.getSearchResults(for: &quot;con&quot;)<br>Thread.sleep(forTimeInterval: Double.random(in: 1...5))<br>searchController.getSearchResults(for: &quot;conc&quot;)<br>searchController.getSearchResults(for: &quot;concu&quot;)</pre><p>In the getSearchResults(for:) method, the WorkItem will be executed only after the user hasn’t typed anything for 50 milliseconds.</p><p>We are essentially canceling the previous workItem when a new letter is typed within the specified delay. Since we set the main thread to sleep for more than 50 milliseconds after typing con, the background thread started executing the WorkItem.</p><p>This can also be implemented for text fields that require server-side validation. Let&#39;s say you have a text field where the user is typing a username, and you need to check if the username is available by making API calls. With a dispatch work item, you can cancel previous API requests each time a new character is typed, ensuring that only the most recent request is processed.</p><p>The notify() function is used to schedule the execution of a specific work item after the current work item has completed. This allows you to chain tasks, ensuring that one task finishes before the next begins. Let&#39;s take a look.</p><pre>final class NetworkManager {<br>    func getData() {<br>        // work item fetch data from server<br>        let newWorkItem = DispatchWorkItem {<br>            print(&quot;Fetching data...&quot;)<br>            // async tasks to fetch results<br>        }<br>        let viewNotifier = DispatchWorkItem {<br>            print(&quot;The data has arrived.&quot;)<br>        }<br>        // Get executed when newWorkItem finished its execution<br>        newWorkItem.notify(queue: .main) {<br>            viewNotifier.perform()<br>        }<br>        DispatchQueue.global().async(execute: newWorkItem)<br>    }<br>}<br><br>let manager = NetworkManager()<br>manager.getData()</pre><p>This can be used to perform two or more tasks in a serial manner and particularly useful when you need to perform multiple tasks in a specific order, such as fetching data on a background thread and then updating the UI on the main thread once the data is ready.</p><p>For example, you might load data for a table view on a background queue and then use notify() to trigger an update on the main queue, ensuring the UI is refreshed only after the data has been fully retrieved.</p><p>The perform() method on a DispatchWorkItem initiates the execution of the work item synchronously on the current thread. This method is particularly useful when you need to manage the execution order of tasks within the same thread.</p><h4>DispatchWorkItemFlags</h4><p>Dispatch work items come with a set of behaviors that can be controlled using DispatchWorkItemFlags. These flags allow you to manage the Quality of Service (QoS) of the work item, create barriers, or even spawn new detached threads. Here are the six available flags:</p><ul><li><strong>assignCurrentContext</strong><br>The work item will inherit the attributes of the current execution context.</li><li><strong>detached<br></strong> The work item will be disassociated from the current execution context.</li><li><strong>enforceQoS</strong>:<br>The QoS of the work item will override the QoS of the current execution context.</li><li><strong>inheritQoS<br></strong> The work item will inherit the QoS from the current execution context.</li><li><strong>noQoS<br></strong>The work item will not have any QoS assigned.</li><li><strong>barrier<br></strong>Causes the work item to act as a barrier block when submitted to a concurrent queue.</li></ul><pre>func async(<br>    group: DispatchGroup? = nil,<br>    qos: DispatchQoS = .unspecified,<br>    flags: DispatchWorkItemFlags = [],<br>    execute work: @escaping @convention(block) () -&gt; Void<br>) {<br>    <br>}</pre><p>A common use case for the barrier flag is when you need to control access to a shared resource to avoid race conditions. For instance, if tasks 1, 2, and 3 are being processed concurrently, but you need to ensure that task 4 has exclusive access to a resource, you would use a barrier. Basically the idea is that: no other task should be executed at the time when this particular task is being executed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*28HHvB_65PSCqjK1NpoYpg.png" /><figcaption>An Illustration of Barrier Task</figcaption></figure><pre>let queue = DispatchQueue(label: &quot;com.example.concurrentQueue&quot;, attributes: .concurrent)<br><br>queue.async {<br>    print(&quot;Task 1&quot;)<br>}<br><br>queue.async {<br>    print(&quot;Task 2&quot;)<br>}<br><br>queue.async(flags: .barrier) {<br>    print(&quot;Task 4: Needs to exclusive access.&quot;)<br>}<br><br>queue.async {<br>    print(&quot;Task 3&quot;)<br>}</pre><p>In the example above, tasks 1, 2, and 3 will run concurrently, but task 4 will wait until tasks 1 and 2 are finished before executing. Once task 4 completes, task 3 can start.</p><h4>Dispatch Semaphore</h4><p>When dealing with race conditions, a dispatch semaphore can be an effective solution. A semaphore allows you to control access to a <strong>critical section</strong> of your code, ensuring that only one thread can access a shared resource at a time, thus preventing data inconsistency.</p><p>A critical section is a part of the program that tries to access shared resources. When a critical section is accessed by multiple threads simultaneously, there is a high risk of data inconsistency. To mitigate this, you can use dispatch semaphores to ensure exclusive access to the critical section.</p><pre>class ThreadSafeCounter {<br>    private var count = 0<br>    private let semaphore = DispatchSemaphore(value: 1)<br>    <br>    func increment() {<br>        semaphore.wait()<br>        count += 1<br>        semaphore.signal()<br>    }<br>    <br>    func decrement() {<br>        semaphore.wait()<br>        count -= 1<br>        semaphore.signal()<br>    }<br>    <br>    func value() -&gt; Int {<br>        semaphore.wait()<br>        let result = count<br>        semaphore.signal()<br>        return result<br>    }<br>}</pre><p>In this example, the semaphore ensures that only one thread can access the count variable at a time, preventing race conditions.</p><h4>4. Operation and OperationQueues in Swift</h4><blockquote><strong><em>When considering concurrency in Swift, developers often face the choice between using Grand Central Dispatch (GCD) and Operation Queues. Understanding when to use each can significantly impact the design and functionality of your application.</em></strong></blockquote><p><strong>GCD vs. OperationQueues</strong></p><p>Comparing GCD and Operation Queues is akin to comparing apples and oranges; they serve different purposes and offer distinct functionalities. Operation Queues are built on top of GCD, providing a higher level of abstraction.</p><ul><li><strong>GCD</strong><br>is typically preferred for simpler tasks where you do not need to manage the state of execution. It is ideal for straightforward, non-complex tasks that do not require features like pause, resume, or dependencies. GCD is more lightweight and efficient for these scenarios.</li><li><strong>Operation Queues</strong><br>In contrast, Operation Queues are better suited for more complex tasks where you need greater control over the execution state. If you want to introduce dependencies between tasks, encapsulate reusable blocks of functionality, or manage task execution more intricately, Operation Queues are the preferred choice.</li></ul><p>While some developers advocate for always using Operation Queues due to Apple’s recommendation to use the highest level of abstraction available, it’s essential to recognize that creating an operation for trivial tasks can be overkill.</p><p><strong>Understanding Operations</strong></p><p>An Operation represents a single unit of synchronous work that can be executed. In Swift, <strong>Operation</strong> is an abstract class, meaning you can’t use it directly. Instead, you must subclass it to define the specific task you want to perform. However, Swift provides two built-in subclasses of Operation that you can use out of the box:</p><ol><li><strong>NSInvocationOperation<br></strong>This class executes a method defined by a target or selector. However, it is worth noting that NSInvocationOperation is primarily available in Objective-C and does not exist in Swift.</li><li><strong>Block Operation<br></strong>This class executes a block of code. It is more commonly used in Swift because it allows for greater flexibility and ease of use.</li></ol><p>Since Swift does not support <em>abstract classes</em> in the traditional sense, think of Operation as a base class that you extend to create custom operations. By subclassing Operation, you can encapsulate complex tasks, add dependencies between operations, and control their execution.</p><p><strong>Submitting Operations to an Operation Queue</strong></p><p>When it comes to executing an operation, you might wonder why you can’t just run it directly. Technically, you can, but <em>operations are synchronous by default</em>. Running a synchronous task on the main thread can block the UI, leading to a poor user experience. This is where OperationQueue comes in—it allows you to offload operations from the main thread to a background thread, ensuring that your app remains responsive.</p><p>Here’s a simple example of using an Operation Queue:</p><pre>let operationQueue = OperationQueue()<br>let operation = BlockOperation {<br>    print(&quot;Executing tasks in the background.&quot;)<br>}<br>operationQueue.addOperation(operation)</pre><p>Operations can be added to the queue for simultaneous execution:</p><pre>let queue = OperationQueue()<br>queue.addOperation {<br>    print(Thread.current)<br>}<br><br>queue.addOperation{ print(&quot;1&quot;, Thread.current) }<br>queue.addOperation{ print(&quot;2&quot;, Thread.current) }</pre><p>However, similar to threads, the execution order in the queue is not guaranteed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*pCBtceJym4VK78POCKdV7A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*mV92wV02wBkvJZeT0OQ6fA.png" /><figcaption>An console output which might represents differ order each time</figcaption></figure><blockquote><em>Operations in queues share similar features with threads. For instance, you can set the priority of an operation using </em><em>qualityOfService:</em></blockquote><pre>let queue = OperationQueue()<br>let operation = BlockOperation {<br> print(Thread.current)<br>}<br>operation.qualityOfService = .background<br>queue.addOperation(operation)</pre><p>An OperationQueue can handle multiple operations concurrently, and it provides a number of powerful features:</p><ul><li><strong>Concurrency<br></strong>You can configure the maximum number of concurrent operations allowed, which helps in managing the workload efficiently.</li><li><strong>Dependencies<br></strong>You can establish dependencies between operations to control the order in which they execute. For example, you might want to ensure that a data fetch operation completes before a data processing operation starts.</li><li><strong>Cancellation<br></strong>Operations can be canceled, but if they are already running, they may not stop immediately. Instead, they need to regularly check their isCancelled property and exit gracefully if it’s set to true.</li><li><strong>Operation States<br></strong>Operations can exist in several states, including ready, executing, and finished. Understanding these states is crucial for managing the lifecycle of an operation.</li></ul><p><strong>Operation States<br></strong>Operations can exist in several states, including:</p><pre>open var isReady: Bool { get }<br>open var isExecuting: Bool { get }<br>open var isFinished: Bool { get }<br>open var isCanceled: Bool { get }</pre><ul><li><strong>isReady<br></strong>When its been instantiated, the operation is ready to execute.</li><li><strong>isExecuting<br></strong>When invoked the start() method, the operation is currently executing.</li><li><strong>isFinished<br></strong>when the task finished, the operation has completed its execution.</li><li><strong>isCanceled<br></strong>When task is in progress and you call cancel , then it will transition to the <strong>isCancelled</strong> state before moving onto the <strong>isFinished</strong> state</li></ul><p>It is important to note that once an operation has finished executing, you cannot reuse the same instance for another execution. Each instance of an operation can only be used once.</p><p><strong>Methods to Create Operations</strong></p><p>1. BlockOperation (Concrete Class)<br>BlockOperation is a class that allows the execution of one or more block objects concurrently. When all associated blocks have completed, the operation itself is considered finished. With BlockOperation, you can take advantage of operation dependencies, KVO, notifications, and cancellation.</p><p><strong>Operations execute synchronously by default</strong>, meaning they run on the thread that calls their start method. For example, if start is called on the main thread, the operation will block it until completed.</p><pre>let operation = BlockOperation {<br>    for i in 0...10 {<br>        print(&quot;✅&quot;, i)<br>        print(Unmanaged.passUnretained(Thread.current).toOpaque())<br>        print(Thread.isMainThread)<br>    }<br>}<br>operation.start()</pre><p>We mentioned that the operations are being executed synchronously by default. Let&#39;s take a look the code snippets below:</p><pre>let operation = BlockOperation()<br><br>operation.addExecutionBlock {<br>    for i in 0...10 {<br>        print(&quot;First Block of Execution&quot;, i)<br>    }<br>}<br><br>operation.addExecutionBlock {<br>    for i in 0...10 {<br>        print(&quot;Second Block of Execution&quot;, i)<br>    }<br>}<br><br>operation.start()<br><br>print(&quot;Program ended here.&quot;)</pre><p>The blocks are being added to the block operation concurrently, however the blocks runs in manner of synchronous execution, which means block the current thread until the execution finishes. We can not exactly know the order, but we can say that the first block which has been added to the operation finished first. And then comes second execution block, after that program gives the output of “Program ended here.”</p><p>Now let&#39;s call the start() method on other thread and see:</p><pre>let operation = BlockOperation()<br><br>operation.addExecutionBlock {<br>    for i in 0...10 { print(&quot;1️⃣&quot;, i) }<br>}<br><br>operation.addExecutionBlock {<br>    for i in 0...10 { print(&quot;2️⃣&quot;, i) }<br>}<br><br>DispatchQueue.global(qos: .background).async {<br>    print(&quot;Current Thread is: &quot;, Thread.current)<br>    operation.start()<br>    print(&quot;The Current Thread which is also \(Thread.current) is going to block the execution.&quot;)<br>}<br><br>print(&quot;Program ended here.&quot;)</pre><p><strong>2. NSInvocationOperation (Concrete Class)</strong></p><p>In Objective-C, NSInvocationOperation allows you to create an operation based on an object and selector. However, this class is not available in Swift.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wPelUEgzZgHGrvO-4sXtug.png" /><figcaption><a href="https://developer.apple.com/library/archive/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationObjects/OperationObjects.html#//apple_ref/doc/uid/TP40008091-CH101-SW6">https://developer.apple.com/library/archive/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationObjects/OperationObjects.html#//apple_ref/doc/uid/TP40008091-CH101-SW6</a></figcaption></figure><p><strong>3. Custom Operations</strong></p><p>By subclassing Operation, you can fully customize your operations, including how they execute and report their status. In this way, you can implement non-concurrent or concurrent operations based on your needs.</p><p>For example, to create a concurrent operation, you would:</p><ul><li>Subclass the Operation class, overriding its main method with your task.</li><li>Handle cancellation within the main method to ensure proper state transitions.</li><li>Ensure that your operation runs asynchronously by taking the necessary steps, such as managing threads or queues.</li></ul><pre>class CustomOperation: Operation {<br>    override func main() {<br>        for i in 0...10 {<br>            print(&quot;⏹️&quot;, i)<br>            print(Unmanaged.passUnretained(Thread.current).toOpaque())<br>            print(Thread.isMainThread)<br>        }<br>    }<br>}<br>let operation = CustomOperation()<br>operation.start()</pre><p>In the code snippet above, we blocked the main thread by implementing custom non-concurrent operation.</p><p>We can set the <em>maxConcurrentOperationCount </em>manually which indicates the maximum number of dequeued operations that can execute at the same time. The default value is -1 which means let the system decide.</p><pre>let operation = OperationQueue()<br><br>let firstOperation = BlockOperation {<br>    for i in 0...10 {<br>        print(&quot;1️⃣&quot;, i)<br>        print(Unmanaged.passUnretained(Thread.current).toOpaque())<br>    }<br>}<br><br>let secondOperation = BlockOperation {<br>    for i in 0...10 {<br>        print(&quot;2️⃣&quot;, i)<br>        print(Unmanaged.passUnretained(Thread.current).toOpaque())<br>    }<br>}<br><br>operation.maxConcurrentOperationCount = 2<br>operation.addOperation(firstOperation)<br>operation.addOperation(secondOperation)<br><br>/*<br>1️⃣ 0<br>2️⃣ 0<br>0x0000600002abc340<br>0x0000600002ab9080<br>1️⃣ 1<br>2️⃣ 1<br>0x0000600002abc340<br>0x0000600002ab9080<br>.<br>.<br>.<br>*/<br></pre><p><strong>Operation Dependencies</strong></p><p>Dependencies can be established between operations, allowing for complex task sequencing. This feature is particularly useful when certain operations must wait for others to complete before beginning execution.</p><p>For example, consider operations X and Y where Y depends on X:</p><pre>let queue = OperationQueue()<br>let operationX = BlockOperation {<br> print(&quot;X&quot;)<br> Thread.sleep(forTimeInterval: 1)<br>}<br>let operationY = BlockOperation {<br> print(&quot;Y&quot;)<br>}<br>operationY.addDependency(operationX)<br>queue.addOperation(operationX)<br>queue.addOperation(operationY)</pre><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=443b6dc5c37f" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/mastering-concurrency-in-swift-a-comprehensive-guide-for-ios-developers-part-2-443b6dc5c37f">Mastering Concurrency in Swift: A Comprehensive Guide for iOS Developers Part-2.</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Concurrency in Swift: A Comprehensive Guide for iOS Developers Part-1.]]></title>
            <link>https://blog.stackademic.com/mastering-concurrency-in-swift-a-comprehensive-guide-for-ios-developers-part-1-6c0b1d4de307?source=rss-6ca908bc68e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c0b1d4de307</guid>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[grand-central-dispatch]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[concurrency-in-swift]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Ahmet Tarik DÖNER]]></dc:creator>
            <pubDate>Thu, 05 Sep 2024 21:35:51 GMT</pubDate>
            <atom:updated>2024-11-07T01:46:11.070Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*49wHcW6PZWmM3sATrv-b4Q.png" /></figure><blockquote><em>In the ever-evolving landscape of mobile applications, the demand for seamless performance and responsiveness has never been higher. As iOS apps become increasingly sophisticated, developers face the challenge of managing complex operations without compromising user experience. This is where concurrency comes into play, offering a powerful solution to handle multiple tasks efficiently. Before delving into Swift&#39;s concurrency paradigms, let&#39;s familiarize ourselves with foundational terminology.</em></blockquote><blockquote>Here&#39;s a outline of the article topic:<br><strong>1. Introduction to Concurrency<br>2. Concurrency vs Parallelism<br>3. Achieving Concurrency in iOS<br>4. Grand Central Dispatch(GCD)<br>5. Operation and Operation Queues<br>6. Modern Concurrency in Swift</strong></blockquote><h4><strong>1. Introduction to Concurrency</strong></h4><p>Concurrency is a fundamental concept in modern software development, especially crucial for iOS applications that need to maintain responsiveness while performing complex tasks. In programming terms, concurrency refers to the execution of multiple instruction sequences at the same time. This does not necessarily mean that the tasks are executed simultaneously; rather, they may be interleaved or overlapped in execution. It also means that an application can handle multiple tasks simultaneously, giving the appearance of parallel execution if the tasks are not truly running in parallel. If two tasks appear to be running at the same time, they are considered concurrent.</p><p>Imagine you have an app that processes an image (e.g., applying a filter) and fetches data from a remote server. Even though both tasks appear to be executed simultaneously, they are actually being handled by the CPU one after the other in very quick succession. Thanks to the <em>time slicing</em> and <em>context switching</em>. This creates the illusion of <em>parallelism</em>, but only one task is being executed at any given moment.</p><p><strong>Why is Concurrency Matter?<br></strong>Concurrency is vital for creating responsive and efficient applications.</p><ul><li><strong>Responsiveness<br></strong>It allows applications to remain responsive to user inputs while performing background tasks.</li><li><strong>Resource Utilization<br></strong>Concurrency enables better utilization of system resources, particularly on multicore processors, by distributing tasks across multiple cores.</li><li><strong>Efficiency<br></strong>It can lead to improved application performance by allowing multiple tasks to progress simultaneously.</li></ul><h4><strong>2. Concurrency vs Parallelism</strong></h4><p>Parallelism is the simultaneous execution of tasks across multiple processing units, guaranteeing genuine concurrent progression of operations. It’s a specific form of concurrency where tasks are actually executed at the same time. While often used interchangeably, concurrency and parallelism have distinct meanings.</p><p>To understand this better, lets consider two analogies:<br>- Concurrency is a juggler which is keeping multiple balls in the air by quickly switching attention between them.<br>- Parallelism are jugglers which are each handling their set of balls simultaneously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v5hQexiGyr0_MRw79UDDGQ.png" /><figcaption>An illustration of Parallel and Concurrent</figcaption></figure><p><strong>How Concurrency is Achieved in Computer Systems?<br></strong>Concurrency in computer systems is achieved through various mechanisms that allow multiple tasks to make progress simultaneously. Here are some key techniques used to enable concurrency:</p><ul><li><strong><em>Time Slicing</em></strong><br>is a technique where the operating system divides the CPU into small slices of time and allocates these slices to different processes in turn. This allows multiple processes to run seemingly simultaneously by sharing CPU time. The operating system rapidly switches between processes, giving each process a slice of CPU time before moving on to the next.</li><li><strong><em>Context Switching</em></strong><br>is the process of saving the state of a currently running process and loading the state of the next process. When the CPU switches from one process to another, it needs to save the current process’s state (registers, program counter, stack pointer, etc.) and restore the state of the next process.</li><li><strong><em>Interrupts</em></strong><br>are signals sent by hardware devices or software to the CPU, indicating that an event has occurred. When an interrupt is triggered, the CPU suspends its current execution, saves its state, and jumps to a specific location in memory to handle the interrupt. After the interrupt is serviced, the CPU restores its previous state and resumes normal execution. Interrupts enable concurrency by allowing the CPU to respond to external events without blocking the main execution flow.</li><li><strong><em>Asynchronous I/O</em></strong><br>operations allow the CPU to initiate an I/O request and continue executing other tasks while the I/O operation is in progress. When the I/O operation completes, the CPU is notified, usually through an interrupt or a callback function.</li><li><strong><em>Message Passing</em></strong><br>In message-passing concurrency models, processes or threads communicate by sending and receiving messages. Each process has its own private memory space and communicates with other processes by sending messages through a communication channel. Message passing allows for concurrency by enabling processes to operate independently and synchronize when necessary through message exchanges.</li></ul><p><strong>Common Problems with Concurrency<br></strong>Concurrency problems are a significant challenge in database management systems. These issues arise when multiple transactions attempt to access and modify the same data simultaneously without proper controls.</p><ul><li>Dirty Read Problem</li><li>Unrepeatable Read Problem</li><li>Lost Update Problem</li><li>Phantom Read Problem</li></ul><h4><strong>3. Achieving Concurrency in iOS</strong></h4><p>In iOS development, there are several ways to implement concurrency:</p><ul><li>Manuel Thread Creation (Not Recommended)</li><li>Grand Central Dispatch</li><li>Operation Queues</li><li>Modern Concurrency in Swift</li></ul><p><strong>Manuel Thread Creation</strong></p><p>Manual thread creation in Swift allows developers to have fine-grained control over thread management. While this approach gives more power to the developer, it also comes with increased complexity and potential pitfalls. Creating a thread in Swift is pretty simple using Thread class. You can either specify objc function through a selector as a starting point, or pass a closure, and, more convenient way, subclass Thread. Here’s an overview of how to create threads manually in Swift, along with an example.</p><pre>import Foundation<br>import PlaygroundSupport<br><br>func performTaskOnThread() {<br>    print(&quot;Task started on the thread: \(Thread.current)&quot;)<br>    for i in 1...5 {<br>      print(&quot;The task \(i) on the \(Thread.current)&quot;)<br>      Thread.sleep(forTimeInterval: 1)<br>    }<br>    print(&quot;Task completed on the thread: \(Thread.current)&quot;)<br>}<br>// Create a thread and start it<br>let myThread = Thread {<br>  performTaskOnThread()<br>}<br>myThread.name = &quot;My Custom Thread&quot;<br>myThread.start()<br><br>// Optionally, you can control the thread further<br>if myThread.isExecuting {<br>  print(&quot;Thread is currently executing.&quot;)<br>}<br>// To cancel the thread (though this won&#39;t stop the thread in progress)<br>myThread.cancel()<br>// If needed, you can set a custom stack size<br>let threadWithCustomStackSize = Thread {<br>    performTaskOnThread()<br>}<br>threadWithCustomStackSize.stackSize = 512 * 1024 // Set stack size to 512 KB<br>threadWithCustomStackSize.start()</pre><p><strong>Overview of Manual Thread Creation</strong></p><p><strong>1. Thread Class</strong>: In Swift, you can create a thread by instantiating the Thread class. This class provides a way to run a specific task on a new thread.<br>2. <strong>Thread Lifecycle</strong>: When you create a thread, you can control its lifecycle, including starting, canceling, and managing its execution state.<br>3. <strong>Auto Release Pool</strong>: Manually created threads do not have an auto-release pool managed by the system, which means you need to manage memory more carefully to avoid leaks.<br>4. <strong>Execution Order</strong>: Managing the order of execution can be challenging, as threads may not execute in the order they were started.<br>5. <strong>Memory Management</strong>: Improper management of threads can lead to memory leaks or crashes, particularly if resources are not released correctly.</p><blockquote>A <strong><em>program</em></strong> is a file that is executable and is made up of processes and threads.<br>A <strong><em>process</em></strong> is an instance of a program that is being executed. Processes are scheduled for the execution by the CPU.<br>A <strong><em>thread</em></strong> is the smallest executable element of a process. A process may have one <em>main thread</em> and several <em>background thread</em>s.</blockquote><p><strong>4. Grand Central Dispatch</strong></p><p>Grand Central Dispatch (GCD) is a framework provided by Apple that allows the developers to execute code concurrently on multicore hardware by submitting work to <em>dispatch queues</em> managed by the system.</p><p><em>GCD</em> is a queue-based API that allows developers to execute closures/blocks on a pool of worker thread in a <strong><em>First-In-First-Out (FiFO)</em> order</strong>. The key rule of GCD is that it decides which thread should be used to execute the task, rather than leaving this decision to the developer. GCD will execute tasks on an appropriate dispatch queue.<br><strong>Dispatch Queues </strong>are the abstraction layer on top of the actual queues that GCD manages. GCD maintains a collection of these dispatch queues, which are often simply referred to as “queues”. The work submitted to these dispatch queues is executed on a pool of thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IWdwQRu3ZSE7ZwjKxfYBlg.png" /><figcaption>Illustration of a Task, Task Queue and Thread Pool</figcaption></figure><p><strong>How can submit work to the dispatch queues?</strong></p><p>Developers can submit tasks to these dispatch queues in from of closures, or blocks either <em>synchronously</em> or <em>asynchronously</em>.</p><ul><li><strong>Order of Execution</strong>: determines whether the tasks are picked up <em>serially</em> or <em>concurrently</em>.</li><li><strong>Manner of Execution</strong>: controls whether the current thread is blocked until the task completes or if the current thread continues while the task run separately.</li></ul><p><strong>What is the difference between Synchronous vs Asynchronous?</strong></p><ul><li><strong>Synchronous: </strong>The current execution is blocked until the task is completed. This means the program waits for the task to finish before moving on to the next operation. (This refers to the manner of execution)</li><li><strong>Asynchronous: </strong>The current execution continues while the new task is executed concurrently. The method returns control immediately, allowing other tasks to start running without waiting for the asynchronous task to complete. (This also refers to the manner of execution)</li></ul><p><strong>Serial Queues vs Concurrent Queues in Grand Central Dispatch</strong></p><p>In GCD dispatch, there are two types of dispatch queues: serial queues and concurrent queues. Understanding the difference between these two type of queues is crucial for effectively managing concurrent tasks in iOS app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-1IVp_KDd5f5Ys-jxP9igA.png" /><figcaption>An Illustration of Queues by Time x Type axis</figcaption></figure><p><strong>Serial Queues</strong><br>A serial queue executes one task at a time, in order they were added to the queue. When you submit a task to a serial queue, it will be executed sequentially, one after the other. The key point about serial queues are:</p><ul><li>They execute tasks one at a time, in the order they were submitted.</li><li>If a task submitted to a serial queue is synchronous (i.e., it blocks the current thread), it will stop the execution of the current task until the new task completes.</li><li>The order of execution for tasks in a serial queue is always serial, meaning they will be dequeued and executed one after the other.</li></ul><p><strong>Concurrent Queues<br></strong>Concurrent queues, on the other hand, can execute multiple tasks at the same time. When you submit tasks to a concurrent queue, they may be executed concurrently, depending on the available system resources.</p><blockquote>However, it’s important to note that even though tasks are submitted to a concurrent queue, they are still dequeued and executed in a serial fashion, following the First-In-First-Out (FIFO) order.</blockquote><ul><li>They can execute multiple tasks simultaneously, depending on system resources.</li><li><strong>The order in which tasks are dequeued and executed is still serial (FIFO), even though the tasks may run concurrently.</strong></li><li>Submitting tasks to a concurrent queue does not guarantee that they will be executed in parallel. They may still be executed sequentially due to system constraints.</li></ul><p>In summary, the main difference between serial and concurrent queues is:</p><ul><li><strong>Serial Queues</strong>: Execute tasks one at a time, in the order they were submitted.</li><li><strong>Concurrent Queues</strong>: Can execute multiple tasks concurrently, but tasks are still dequeued and executed in a serial (FIFO) order.</li></ul><blockquote><strong><em>Serial/Concurrent affects the destination queue, determining whether tasks are executed one at a time or simultaneously.</em></strong></blockquote><blockquote><strong><em>Synchronous/Asynchronous affects the current thread, determining whether the execution should pause (synchronous) or continue running other tasks (asynchronous) while waiting for the operation to complete.</em></strong></blockquote><ul><li><strong>Synchronous vs. Asynchronous</strong>: Affects the current thread, determining whether the execution should pause (synchronous) or continue running other tasks (asynchronous) while waiting for the operation to complete.</li></ul><pre>import Foundation<br>import PlaygroundSupport<br><br>PlaygroundPage.current.needsIndefiniteExecution = true<br><br>var counter = 1<br><br>DispatchQueue.main.async {<br>    for i in 0...3 {<br>        counter = i<br>        print(&quot;\(counter)&quot;)<br>    }<br>}<br><br>for i in 4...6 {<br>    counter = i<br>    print(&quot;\(counter)&quot;)<br>}<br><br>DispatchQueue.main.async {<br>    counter = 9<br>    print(&quot;\(counter)&quot;)<br>}<br><br>// Output: 45601239</pre><p>In the example above, we have two tasks that are being added to the <em>main queue </em>in asynchronous manner, which means doesn&#39;t block the current execution of program. Don&#39;t forget even though tasks are concurrent, they are still dequeued and executed in a serial (FIFO) order.</p><p><strong>Kind of Dispatch Queues</strong></p><p>There are several types of dispatch queues, each serving different purposes and operating under specific conditions. Understanding these types is crucial for managing concurrency effectively in your applications. In iOS there are three types of dispatch queues:</p><ul><li><strong>Main Queue</strong></li><li><strong>Global Concurrent Queue</strong></li><li><strong>Custom Queue</strong></li></ul><p><strong>Main Queue<br></strong>The main queue is a <strong>serial queue</strong> that is automatically created by the system and runs on the <strong>main thread</strong> -it is the only queue that operates on the main thread. This queue is crucial because it’s responsible for executing all tasks that involve updating the user interface (UI) or interacting with UIKit. Since the main queue runs on the main thread, tasks are executed one at a time, ensuring that the UI remains responsive and free from conflicts caused by simultaneous operations. UIKit is tied to main thread which means all UI related operations must be performed on the main queue. Never dispatch long-running tasks to the main queue to avoid the blocking UI. Here are some key points for the main queue:</p><ul><li><em>Characteristics</em><br><strong>Serially in Nature, </strong>only one tasks executed at a time, ensuring that UI updates are performed in sequentially.<br><strong>UI Updates, </strong>All UI related operations must be performed on the main queue.</li><li><em>Usage</em><br>You typically dispatch tasks to the main queue when you need to update the UI after performing background operations. For example, after fetching data from a network request, you would update the UI on the main queue.</li></ul><pre>DispatchQueue.main.async {<br>  // Perform UI updating operations.<br>}</pre><p><strong>Global Concurrent Queues<br>are </strong>system-provided, concurrent queues that <strong>do not run on the main thread</strong>. These queues allow multiple tasks to execute simultaneously, optimizing performance by utilizing available CPU cores. Global concurrent queues are ideal for handling tasks that can run in parallel without affecting the main thread’s performance.</p><ul><li><em>Characteristics<br></em><strong>Concurrent in Nature, </strong>multiple tasks can run simultaneously, improving performance for tasks that can be executed in parallel.<br><strong>Quality of Service(QoS), g</strong>lobal queues are categorized by QoS classes, which help the system prioritize tasks based on their importance and urgency</li><li><em>Usage<br></em>Global concurrent queues are ideal for performing tasks that do not require immediate results or UI updates. For example, you might use a global queue to perform data processing or network requests.</li></ul><p>To be able to understand better what kind of dispatch queue execute on which thread, consider this example below:</p><pre>DispatchQueue.main.async {<br>    print(Thread.isMainThread ? &quot;Execution on Main Thread&quot; : &quot;Execution on some other Thread&quot;)<br>}<br><br>DispatchQueue.global().async {<br>    print(Thread.isMainThread ? &quot;Execution on Main Thread&quot; : &quot;Execution on global concurrent queue&quot;)<br>}</pre><p><strong>What is Quality of Service Classes?</strong></p><p>Quality of Service (QoS) in Swift determines the priority of tasks that are submitted to dispatch queues, giving the system insight into how important a task is and how it should allocate system resources like CPU time, memory, and energy. This concept allows the system to better manage tasks and ensure that more critical operations are prioritized, while less urgent tasks can be scheduled to run when resources are available.</p><p>Apple introduced QoS classes to help developers specify the intended purpose of a task, ensuring better resource management, power efficiency, and responsiveness in apps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_xHraLTHOyJ_U78f_sxraA.png" /><figcaption>Illustration a basic Sandbox of an Application</figcaption></figure><p>The figure illustrates the basic sandbox of an iOS application, specifically focusing on how the system handles threading and event management. When an app is launched by tapping on its icon, the system creates a <strong>main thread</strong>, and the application starts running. <strong>UIKit</strong>, which is responsible for handling the user interface, is closely tied to this <strong>main thread</strong>.</p><p>Once the app launches, the <strong>AppDelegate</strong> is invoked. This delegate handles various app lifecycle events. The <strong>main thread</strong> essentially waits for events, such as user interactions (e.g., tapping a button) or system calls. If your app needs data from a <strong>database</strong>, the AppDelegate initiates this request. During the database request, the <strong>main thread</strong> may become involved in waiting for the data to be retrieved. During this time, the main thread is unable to listen for other events, meaning the app becomes <strong>unresponsive</strong>. For example, if the user attempts to interact with the UI (like tapping buttons), the app won’t respond because the main thread is blocked. If the database query takes too long, the app appears to <strong>freeze</strong> or become sluggish. While this delay may go unnoticed if it’s brief, longer delays will affect the user experience. The solution to this problem is <strong>multithreading</strong>. By introducing a <strong>background queue</strong> (either a custom queue or a global concurrent queue using <strong>GCD</strong>), the database operations can be offloaded from the main thread.<br>In this case, the <strong>background queue</strong> handles the database calls, allowing the <strong>main thread</strong> to remain free for processing user events. Once the data is received, the <strong>UI</strong> is updated on the main thread, ensuring smooth interaction without freezing.</p><p>Now, let’s zoom out from the thread handling and focus on performance optimization. Imagine a device with a <strong>single-core processor</strong> (for simplicity, though modern devices use multi-core processors). Multiple apps are running on the device, each requiring resources. The processor is handling multiple tasks simultaneously, but it heats up due to the load. Devices like iPads and MacBooks, which are slim and fanless, need to manage this heat efficiently without affecting performance.</p><p>This is where <strong>Quality of Service (QoS)</strong> comes into play. By categorizing tasks based on their priority, the system ensures that <strong>critical tasks</strong> (like UI updates) are given higher priority, while <strong>background tasks</strong> (like database queries or syncing data) can be deprioritized. This management prevents overloading the processor, reduces the chances of device overheating, and ensures that the user interface remains <strong>smooth and responsive</strong>.</p><p>There are several predefined QoS classes, each representing a different priority level. Each class influences how the system schedules and executes tasks. Here’s a detailed breakdown in order of decreasing priority:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dv7kJCr9Bx8n4-t1zJysTQ.png" /><figcaption>An Illustration of QoS Classes</figcaption></figure><ol><li><strong>User Interactive</strong><br> -<em>Purpose</em>: For tasks that are <strong>immediately</strong> visible to the user and need to be completed <strong>instantly</strong> to maintain the responsiveness of the app.<br> -<em>Use Cases</em>: UI Updates, Animations, Event Handling<br> -<em>Impact</em>: This is the <strong>highest-priority</strong> class, meaning tasks will be executed as soon as possible. Resources are allocated immediately to prevent any lag in the user experience.</li><li><strong>User-Initiated<br></strong> -<em>Purpose: </em>For tasks initiated by the user that <strong>must complete quickly</strong> to deliver results. These are tasks that the user expects to complete soon but don’t directly impact the user interface.<br> -<em>Use Cases: </em>Loading content after the user requests it (e.g., fetching data from an API), Processing data that is required for immediate use.<br> -<em>Impact: </em>This class is slightly lower in priority than userInteractive, but still highly prioritized. It ensures tasks complete swiftly and provides the user with the results in a timely manner.</li><li><strong>Utility</strong><br> -<em>Purpose: </em>For tasks that the user is aware of, but <strong>don’t require immediate results</strong>. These tasks take a moderate amount of time and can run in the background without affecting the user interface.<br> -<em>Use Cases: </em>Downloading large files, Background data syncs or backups, Performing lengthy computations (e.g., analyzing a dataset)<br> -<em>Impact: </em>Tasks with this QoS class consume <strong>less energy</strong> and run with <strong>lower priority</strong> than userInitiated or userInteractive tasks. They can be executed over a longer period, making them ideal for operations that don’t need to be completed right away.</li><li><strong>Background<br>-</strong><em>Purpose: </em>For tasks that the user <strong>isn’t directly aware of</strong>, such as maintenance or syncing tasks that can be deferred until system resources are available.<br> -<em>Use Cases: </em>Database maintenance, Data syncing or indexing, Performing tasks that can run in the background without impacting the user experience.<br> -<em>Impact: </em>Tasks with this QoS class consume <strong>less energy</strong> and run with <strong>lower priority</strong> than userInitiated or userInteractive tasks. They can be executed over a longer period, making them ideal for operations that don’t need to be completed right away.</li><li><strong>Default<br>-</strong><em>Purpose: </em>This is the <strong>default QoS</strong> used when no specific QoS class is defined. It falls between userInitiated and utility.<br> -<em>Use Cases: </em>Generic tasks that don’t fall under the other QoS categories.<br> -<em>Impact: </em>It is less important than userInitiated but more important than utility.</li><li><strong>Unspecified<br>-</strong><em>Purpose: </em>This represents the <strong>absence</strong> of any specific QoS, which is generally discouraged for use. It may be used when you don’t need to provide any explicit priority information.<br>-<em>Use Cases: </em>Rarely used, typically reserved for system-level tasks where QoS isn’t applicable.</li></ol><pre>DispatchQueue.global(qos: .background).async {<br>    for i in 0...10 {<br>        print(i)<br>    }<br>}<br><br>DispatchQueue.global(qos: .userInteractive).async {<br>    for i in 11...20 {<br>        print(i)<br>    }<br>}</pre><p>In the code snippets above, we have two tasks on the global concurrent queue in manner of asynchronous execution.</p><p>We can not know the output of execution exactly. Because two works is being executed on two different threads asynchronously, which we do not know about. But we can predict which work to be finish its execution first depending on its QoS class. In the illustration above, the second work finishes first, because the priority level of user interactive QoS class is higher than background class. So it has more system resource to use.</p><p>Now lets take a look how to create a custom dispatch queue, and what are parameters that the initializer takes.</p><pre>let customQueue = DispatchQueue(<br>    label: &quot;com.example.customQueue&quot;,<br>    qos: .background,<br>    attributes: .concurrent,<br>    autoreleaseFrequency: .workItem,<br>    target: nil<br>)</pre><ul><li><strong>label<br></strong>The label is a descriptive name for your queue, which is useful for debugging and profiling. The label doesn’t affect the behavior of the queue itself but can help when analyzing performance in Instruments or Xcode’s Debug Navigator.</li><li><strong>qos<br></strong>This parameter determines the priority of the tasks being executed on this queue. You can select one of the predefined QoS classes.</li><li><strong>attributes</strong><br>A parameter that can be set to define the queue’s behavior.<br> <strong><em>.concurrent: </em></strong>Indicates that the queue will execute tasks concurrently. If this attribute is not specified, the queue will be serial by default.<br> <strong><em>.initiallyInactive: </em></strong>The queue is created in an inactive state and will not execute tasks until activated. This is useful for scenarios where you want to control when the queue starts processing tasks.</li></ul><p><strong>Target Queues in Swift</strong></p><p>Target queue is a dispatch queue that your custom queue utilizes behind the scenes for executing tasks. When you create a custom queue, you might assume that tasks dispatched to this queue will run directly on it. However, they are actually executed on the target queue. All tasks dispatched to either global concurrent queues or custom-created queues are executed on a fixed set of queues known as target queues. This underlying mechanism ensures that the system can manage resources efficiently.</p><p>The priority of a dispatch queue is inherited from its target queue. This means that when you create a custom queue, its execution priority is determined by the target queue it is associated with. If you do not specify a target queue when creating a custom queue, it defaults to using the global concurrent queue with a standard priority. This ensures that tasks are executed without requiring explicit configuration.</p><p>Why Do Target Queues Exist?</p><ul><li><strong>Resource Management</strong>: If GCD allowed an unlimited number of queues to directly handle execution, the system’s resources could be overwhelmed by excessive thread creation, leading to poor performance or crashes. The concept of target queues helps <strong>control resource usage</strong> by limiting the number of actual execution queues, while still allowing developers to create flexible, custom queues to organize their work.</li><li><strong>Control</strong>: By using custom queues that point to specific target queues, developers can manage task execution more granularly, without overburdening the system.</li></ul><pre>let firstQueue = DispatchQueue(label: &quot;com.example.firstQueue&quot;)<br>let secondQueue = DispatchQueue(<br>    label: &quot;com.example.secondQueue&quot;,<br>    attributes: .concurrent,<br>    target: firstQueue<br>)<br><br>firstQueue.async { for i in 0...5 { print(i) } }<br>firstQueue.async { for i in 6...10 { print(i) } }<br><br>secondQueue.async { for i in 11...15 { print(i) } }<br>secondQueue.async { for i in 15...20 { print(i) } }</pre><p>In the code snippets above, we instantiated two queues. The firstQueue is a serial queue, because unless specify the attributes as concurrent, default is serial queue. The secondQueue is a concurrent queue and its target queue is the firstQueue.</p><p>On the firstQueue we dispatching two blocks of codes in manner of asynchronous execution. Remember the firstQueue is a serial queue which means executes one task at a time, in order to they were added to the queue. Even though the secondQueue&#39;s attributes specified as concurrent, it behaves also as a serial queue, because its target is a serial queue. In the console we can see the output at the range of 0…20 in order.</p><p>One of the important things about to remember on target queue is that if you do not set the target during the time of initialization, you can not change it later. It ends up with a crash. Because we can not change the target of already activated queues.</p><pre>let firstQueue = DispatchQueue(label: &quot;com.example.firstQueue&quot;)<br>let secondQueue = DispatchQueue(<br>    label: &quot;com.example.secondQueue&quot;,<br>    attributes: .concurrent<br>)<br>secondQueue.setTarget(queue: firstQueue)<br><br>/*<br>error: Execution was interrupted, reason: EXC_BREAKPOINT (code=1, subcode=0x189df54ec).<br>The process has been left at the point where it was interrupted, use &quot;thread return -x&quot; to return to the state before expression evaluation.<br>*/</pre><p>We can use the state of .initiallyInactive, to be able to set the target after the initialization. Because its initial state is inactive, not activated yet.</p><pre>let firstQueue = DispatchQueue(label: &quot;com.example.firstQueue&quot;)<br>let secondQueue = DispatchQueue(<br>    label: &quot;com.example.secondQueue&quot;,<br>    attributes: [.concurrent, .initiallyInactive]<br>)<br>secondQueue.setTarget(queue: firstQueue)<br>secondQueue.activate()</pre><p><strong>Auto Release Frequency<br>Autorelease frequency</strong> setting determines how frequently objects are autoreleased within a dispatch queue. This setting is crucial for controlling memory management, especially when working with tasks that involve autoreleased objects. Understanding how and when autorelease pools are drained can help ensure efficient memory usage, avoiding potential memory leaks or unnecessary memory consumption.</p><p>In Objective-C and Swift, autorelease pools are used to manage memory for objects that are marked for <strong>autorelease</strong>. When an object is autoreleased, it is not immediately deallocated; instead, it is added to an <strong>autorelease pool</strong>. When the pool is drained (typically at the end of a run loop or at specific points in code), the objects in the pool are released, potentially leading to their deallocation if no other references exist.</p><p>There are three options available:</p><ul><li><strong>.inherit<br></strong>This option allows the dispatch queue to inherit its auto-release frequency from its target queue. This is the default behavior if no specific auto-release frequency is set. When you want the custom queue to follow the same memory management behavior as its target queue, ensuring consistency in how objects are released.</li><li><strong>.workItem<br></strong>Each work item dispatched to the queue will have its own auto-release pool. This means that temporary objects created during the execution of a work item will be released once the work item completes. This is useful when you want to isolate the memory management of individual work items, allowing for more granular control over when objects are released.</li><li><strong>.never<br></strong>This option indicates that the dispatch queue will not set up an individual auto-release pool for its work items. As a result, any temporary objects created during the execution of tasks will not be automatically released until the queue itself is deallocated. This can be beneficial in scenarios where you want to minimize overhead from creating multiple auto-release pools, but it requires careful management of memory to avoid leaks.</li></ul><p>Can you predict the output of the code below using all the information we’ve learned so far? Then, change the first async task to sync and compare.</p><pre>var value = 20<br>let queue = DispatchQueue(label: &quot;com.queue.Serial&quot;)<br><br>func executeAsyncTaskInSerialQueue() {<br>    for i in 1...3 {<br>        queue.async {<br>            Thread.isMainThread ? print(&quot;The task running on main thread.&quot;) : print(&quot;The task is running on other thread.&quot;)<br>            let imageURL = URL(string: &quot;https://upload.wikimedia.org/wikipedia/commons/0/07/Huge_ball_at_Vilnius_center.jpg&quot;)!<br>            let _ = try! Data(contentsOf: imageURL)<br>            print(i, &quot;finished downloading.&quot;)<br>        }<br>    }<br>}<br><br>executeAsyncTaskInSerialQueue()<br><br>queue.async {<br>    for i in 1...3 {<br>        value = i<br>        print(value, &quot;✅&quot;)<br>    }<br>}<br><br>print(&quot;Do you know the console output?&quot;)</pre><p>In this part of the article, we introduced concurrency and explored the differences between concurrency and parallelism. We then explained the techniques used to implement concurrency in computer science, along with common challenges. The article also delved into concurrency in iOS, providing a detailed explanation of Grand Central Dispatch (GCD).</p><p>In the next part, we’ll cover Dispatch Group, Dispatch Work Item, Dispatch Barrier, Semaphore, Work Item Flags, Operation, Operation Queues and much more.</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c0b1d4de307" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/mastering-concurrency-in-swift-a-comprehensive-guide-for-ios-developers-part-1-6c0b1d4de307">Mastering Concurrency in Swift: A Comprehensive Guide for iOS Developers Part-1.</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unraveling the Evolution of UI Design Patterns: From MVC to MVVM and MVP]]></title>
            <link>https://medium.com/@ahmettarikdoner/unraveling-the-evolution-of-ui-design-patterns-from-mvc-to-mvvm-and-mvp-53ac7bcc5b68?source=rss-6ca908bc68e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/53ac7bcc5b68</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Ahmet Tarik DÖNER]]></dc:creator>
            <pubDate>Fri, 01 Mar 2024 19:28:35 GMT</pubDate>
            <atom:updated>2024-03-01T19:28:35.711Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vzi598UPfwCDp7gAjXipHA.png" /></figure><p>-𝐍𝐨𝐧𝐞 𝐨𝐟 𝐭𝐡𝐨𝐬𝐞 𝐌𝐕 𝐚𝐜𝐫𝐨𝐧𝐲𝐦𝐬 𝐜𝐚𝐧 𝐛𝐞 𝐜𝐨𝐧𝐬𝐢𝐝𝐞𝐫𝐞𝐝 𝐚𝐬 𝐚𝐫𝐜𝐡𝐢𝐭𝐞𝐜𝐭𝐮𝐫𝐞, 𝐛𝐮𝐭 𝐔𝐈 𝐝𝐞𝐬𝐢𝐠𝐧 𝐩𝐚𝐭𝐭𝐞𝐫𝐧𝐬. Let’s take a look at how these patterns evolve into each other, and what responsibilities lie outside the scope of these patterns:</p><p>First of all MVC (1979-) is the first pattern all other MV acronym patterns and trying to solve very specific problem around computer-user interfaces. Let’s have a close look how dependencies look like in the original design.</p><ul><li>The User initiates an event — by pressing a key on the keyboard or a mouse clicking. This user event is then directed to the Controller.</li><li>The Controller object handles the event, generates commands, and forwards them to the Model. It manipulate Model interactions where the model hold the business logic or executing the data manipulation tasks. Once the model completes its operation, it broadcasts changes through mechanism such as Notifications, Callbacks, or Observers.</li><li>The View maintains an observer relationship with the model, awaiting notifications of data changes, formatting the data, and rendering it on the screen.</li></ul><p>As you can see the responsibilities were minimal in the old days. The Controller manage events and dispatched commands to the Model, which manipulating data according to the commands, broadcast messages and allowed the View to render them on the screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0HQ9rB7IlEX1tIOLsGqc2w.png" /></figure><p><strong><em>Examining the dependencies between modules:</em></strong></p><p>The Controller and the View depends on the Model layer, because of that the Model positioning at the center of the diagram.</p><p>Note that only arrow leaving the Model is broadcasting mechanism, indicating indirect communication. There is no dependency from the Model to the View, enabling the Model to be tested in isolation, reside in a separate module and be reused in various scenarios. For example it could be integrated into a terminal view, completely decoupled from the View. Similarly the View had no dependency on the Controller.</p><p>Over time, as different frameworks and types of applications emerged, this pattern evolved. For instance, with the advent of the web, Views could be in formats such as JSON, XML, or HTML and they couldn’t merely observe messages from the Model. Consequently, Controllers started referencing the View directly, allowing the passing of the Model through the View for formatting and rendering.</p><p>While this pattern always focused on the user interface, applications involve various other tasks such as database storage and networking. However, none of these fell under the concerns of MVC — they resided elsewhere in the application. Therefore, MVC was never considered an architecture but rather than a design pattern aimed at solving user interaction with the interface problem.</p><p>At that time, the prevailing advice was that every view on the screen should have a specific controller and a specific model. For instance, a button on the screen would have a button controller, and a checkbox would have a checkbox controller. Thus, the entire user interface comprised a collection of models, views, and controllers.</p><p><strong><em>Let’s delve into how this pattern is utilized in modern contexts:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rEn-1DzCHg6n9DMlncdwIA.png" /></figure><p>Apple, for instance, has slightly altered this design pattern to accommodate their own frameworks like UIKit and AppKit. A significant change in the flow of actions is notable in Apple’s version of MVC because, in their approach, events originate from the view itself. With touchscreens prevalent on phones, user events, such as touching the screen, are directed to the view. Consequently, the view becomes an observer. And the recommended practice is for the Controller to handle user events that originate from the view. This adjustment reshapes the pattern significantly. Unlike the original version of MVC, the Controller now occupies a central position within the pattern and serving as a mediator. The user events originate from the view, and the controller observes them through mechanism like target-action, delegation, or callbacks. Upon receiving these user events, the Controller converts them into commands and relays messages to the Model. The Model updates itself and broadcast changes, which is no longer directly affect the view. Instead, changes pass through the Controller again via notifications, callbacks, or observers. The controller then updates the view with these changes.</p><p>Some variations of this pattern involve developers binding the view directly to the model instead of inserting the controller in the middle. However, it’s clear that the Model never depends directly on the Controller or the View. Another significant change in this pattern is its classification as an architectural pattern, implying that all application responsibilities are now assigned to one of these layers. For instance, networking, storage, and database are now considered part of MVC. While this approach might suffice for very simple applications, as application grow, it tends to become messy. Hence the questions arises: where should these responsibilities reside within this pattern? It is commonly advised to retain business logic and data manipulation in the model layer, even though some developers move business logic to the controller. The recommendation always leans towards keeping it in the Model. Storage and database interactions, much like in web applications, sometimes reside in the controller, depending on the developers. However, the general advice is to keep them in the Model layer. Event handling remains in the Controller layer, while rendering stays in the View layer. Formatting, however, has been shifted to the controller. This decision ensures that if formatting responsibility is assigned to the view, it directly references the view, thereby breaking the defined separation of concerns. Hence, formatting typically resides in the Controller or in Model. Networking is another aspect that sometimes resides in the controller, along with routing, while parsing moves to the model. It is common to encounter code where the controller makes an API request, receives JSON data, and then asks the Model to map that JSON into a usable model. Opinions differ regarding whether networking should be in the model, and there is no clear consensus on this matter. Some argue to keep formatting in the view and reserve the controller solely for event handling and routing.</p><p>Regardless of how these objects are arranged, it often appears that one of the layers is burdened with too many responsibilities. There is no optimal separation in this regard as the application grows. One significant issue that arises is the tendency to define the entire screen as a single, oversized MVC structure. However, it doesn’t have to be this way; it’s up to the developers to break it down into a smaller MVCs. Nonetheless, it is common to encounter these oversized MVC screens, where one controller manages multiple views and models. As a result, the controller becomes unwieldy, and the models handle the database queries, networking, parsing, data manipulation, and more. Things can quickly spiral out of control in such scenarios, which leads us to MVVM.</p><p>In the realm of software architecture, the MVC pattern has long been staple, providing a structured approach to developing user interfaces. However, as technology evolves, new design patterns emerge, each addressing specific challenges and offering unique solutions. One such pattern that has gained traction is the MVVM (Model-View-ViewModel) design pattern. Unlike MVC -we don’t have a Controller in the middle, MVVM replaces the controller with a ViewModel. In an iOS application, user events still originate from the view, but they are managed through a binder, directing events to the ViewModel. The ViewModel then communicates with the model, and when the model undergoes changes, the ViewModel utilizes observable properties to notify the View.</p><p>A significant departure from MVC is evident in MVVM: the ViewModel does not maintain a reference to the View, nor does the View reference to the ViewModel directly. Instead, a binder facilitates the communication between the two layers. Originally conceptualized by Microsoft, MVVM sought to streamline the process of connecting presentable data. Through frameworks like XAML and binder mechanisms, MVVM automates the synchronization between the view and the model, minimizing the need for boilerplate coding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ys1zB4thWeQo8jmjAGxJxw.png" /></figure><p>The responsibilities addressed by MVVM are distinct: business logic, data manipulation, storage, and database operations remain within the domain of the model. Rendering, on the other hand, is delegated to the view. Notably, formatting and presentation tasks are assigned to the ViewModel, along with the handling of user events. However, MVVM is not designed to tackle all aspects of application development. Concerns such as networking, parsing, and routing are left unaddressed by MVVM. Unlike MVC or MVVM, which delineate responsibilities more clearly, decisions regarding the placement of networking, parsing, and routing logic are left to the discretion of the developer. The pattern emphasizes the separation of concerns, urging developers to allocate responsibilities judiciously.</p><p>Ultimately, MVVM underscores the importance of segregating user interface concerns from other aspects of application development. While it streamlines the process of data presentation and interaction, it does not purport to address the full spectrum of application requirements. Rather, MVVM serves as a specialized tool, offering a structured approach to user interface development while leaving room for flexibility in addressing other application concerns.</p><p>In summary, MVVM represents a departure from traditional MVC architecture, offering a refined approach to user interface development. By introducing the ViewModel and emphasizing a clear operation of concerns, MVVM provides a framework for creating robust and maintainable user interfaces in modern software application. Furthermore, while optimization is necessary, it’s important to recognize that the best approach may vary depending on the specific requirements of your project. Ultimately, the decision lies with the developers to determine what makes the most sense. However, if feasible, it’s advisable to keep these additional responsibilities separate from the primary pattern and utilize it specifically for resolving user interface concerns.</p><p><strong><em>Let’s now delve into the MVP design pattern</em></strong></p><p>In MVP, if we maintain the flow of user events originating from the view, the concept aims to eliminate the controller or rebrand it as the Presenter, attributing it with clear responsibilities. The major divergence between MVP and MVVM lies in the presenter retaining a reference to the View. However, this reference isn’t direct; there is a protocol in between, which the view implements. This inversion of dependencies means that the Presenter, or the presentation layer, isn’t reliant on the UI as it is in MVC. Instead, it communicates with the model layer through interfaces and receives model events via interfaces as well. Consequently, the presenter implements model layer notifications, and passing it to the View protocol for rendering on the screen. Additionally, when an event occurs, it traverses through the presenter, which can then propagate it forward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kTyFmj-Z1XmEVedDCW1nTA.png" /></figure><p>There are various approaches to implementing MVP, where the Presenter doesn’t handle the user events. However, this aspect will be explored in a separate article. MVVM and MVP both involve renaming Controller layer and assigning specific responsibilities to it in their implementation. In MVP, protocols are used for communication, whereas MVVM utilizes binders. However, does MVP effectively resolve issues pertaining to networking, parsing, routing, and database responsibilities? Let’s delve deeper:</p><p>MVP advocates for business logic to remain in the model layer behind interfaces, rendering to reside in the View, and user event handling and formatting handled by the presentation layer. However, there’s no defined location for everything else, leaving it to the developer’s discretion to decide where to allocate these responsibilities. Consequently, there is no optimal separation of concerns in MVP, as it also attempt to address communication between the user interface and the Model. Thus, regardless of the combination, it results in a suboptimal solution. However, all these patterns serve as effective methods to organize the user interface layer.</p><p><strong><em>Now how do this patterns translate when integrated with UIKit?</em></strong></p><p>In UIKit applications implementing MVVM, the structure typically resembles a Model, ViewModel, ViewControllers, and Views setup. In the absence of binding mechanism similar to XAML, binding code often finds its place in the ViewController. Visually, this setup closely resembles MVC, featuring a Controller, a View, and a Model, albeit named ViewModel. The arrows indicating dependencies remain consistent. However, in MVVM, the observer pattern is implemented, with the controller serving a a binder, which proves convenient and facilitates the creation of frameworks. For instance, RxSwift is commonly employed for binding, significantly reducing boilerplate code. Upon closer inspection, an MVC framework is embedded within MVVM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MpcmBRAoCa9WjwPBgrNHrg.png" /></figure><p>UIKit predominantly utilizes MVC due to the manner in which views are interconnected. UIViewController serves as the presentation of the screen, with multiple UIViewControllers potentially present on a single screen. Controllers maintain references to the view, and as recommended, views should not directly reference the controller or the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hy2vtH8AEJMp9yMAvfaNxw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53ac7bcc5b68" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>