<?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 Abdullah Althobetey on Medium]]></title>
        <description><![CDATA[Stories by Abdullah Althobetey on Medium]]></description>
        <link>https://medium.com/@Abdullah_th?source=rss-775503c5e098------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*njjWgNwgVJgN7AtJVFKbyA.jpeg</url>
            <title>Stories by Abdullah Althobetey on Medium</title>
            <link>https://medium.com/@Abdullah_th?source=rss-775503c5e098------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 05:53:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Abdullah_th/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[Designing and Organizing Product Teams]]></title>
            <link>https://medium.com/@Abdullah_th/designing-and-organizing-product-teams-51e600fe9835?source=rss-775503c5e098------2</link>
            <guid isPermaLink="false">https://medium.com/p/51e600fe9835</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[leadership]]></category>
            <category><![CDATA[product]]></category>
            <category><![CDATA[agile]]></category>
            <dc:creator><![CDATA[Abdullah Althobetey]]></dc:creator>
            <pubDate>Sun, 23 Oct 2022 19:10:59 GMT</pubDate>
            <atom:updated>2022-10-23T19:10:59.491Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, I want to discuss how to design and organize product teams. When I say product teams, I don’t mean product management teams, but rather, a team who builds products. To build a product, you need various skills such as engineering, design, product management, support.</p><p>Products typically start with a small team or even only one engineer. It depends, but you usually need to think about team design when you reach at least ten people working on the product.<br>After you reach that number, you need to divide work between teams. You might also want multiple teams to work in parallel. But how to do that? Well, there are a lot of ways.</p><p>You might have a system or an app. That system consists of multiple components, and you have numerous features on the pipeline.<br>To better explain the situation, let’s say you have three teams, three components in your system, and three features you want to develop.<br>Your team has grown in numbers, and it’s a waste of time to have three teams to work on feature A until done, then do feature B, and then C.<br>Bear in mind, you typically want the teams to work in parallel.</p><h3>Feature Teams</h3><p>To do this, you assign a feature to each team. That sound reasonable enough.<br>In the diagram below, F stands for a Feature, and C stands for a Component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dHzasBQtU3Q3KVn7fwjjVA.jpeg" /></figure><p>It sounds nice that each team works independently on a complete and separate feature, and they work in parallel. Now, we can deliver features faster, right? Or so, I thought.</p><p>The big downside of this approach is that to take a feature and implement it from A to Z, you need to touch multiple components, and here in our small system with only three components, you need to touch all three of them! That’s a lot of stepping on other people’s work and potential areas of conflict. You need a lot of coordination between the teams to make this happen so you really get back to one big team.</p><p>Another downside is that the teams have no ownership over these components. Everyone’s goal will be to deliver the feature they are assigned to, even if that means doing changes in one component that will negatively impact other teams’ features.</p><p>In short, there will be <strong>chaos over the artifacts</strong> produced by the team, be that the code, design, documents, and so on, because different teams will change these artifacts based on different purposes.</p><h3>Component Teams</h3><p>Ok, how about we divide the team by components instead of features?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y8qZROFpgoXx4DZIU4pavg.jpeg" /></figure><p>Now, each team has complete ownership over its components. It also sounds reasonable because each change in a component is typically well-thought-of and will not (hopefully) break other changes related to other features.</p><p>But, of course, there will be downsides. The biggest one is that now to implement a feature, you need to talk to three teams, you need to decompose the feature into three sub-features for each team, and each team needs to understand the full feature to tackle the sub-feature.</p><p>So, there will be a lot of back and forth between the teams to develop these features, drastically slowing down the work. Again, you really get back to one big team</p><p>In short, there will be <strong>chaos in communications</strong> between the teams.</p><h3>Factory Teams</h3><p>There is a third bad way to organize product teams, and really the worst. Yet, I saw teams work this way in my career.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A1zMhJiDotcEyb-KJlGbCw.jpeg" /></figure><p>In this way, no team is assigned to a particular component or a particular feature, they work in constant iterations (or so-called sprints), and at each iteration, they rotate teams or rotate members within the teams. The rotation is typically based on availability, or managers throw “jokers” around, thinking they will speed up the highest priority tasks.</p><p>Another rationale I sometimes hear working this way is that when rotating people, they will be masters of everything inside the system. But most likely, they will be masters of none.</p><p>Typically, the purpose of such an organization is to be a features factory, manufacturing features without any real value or purpose. Only delivering one feature after another and leaving behind a wake of destruction.</p><p>This is <strong>absolute mayhem</strong>; please don’t use this form of organization (or lack of).</p><h3>Domain Teams</h3><p>The best way to organize product teams is by <strong>domain</strong>.</p><p>The term domain has many definitions. The simplest is that the domain is an area of interest to the business.</p><p>Here is a more advanced definition by Eric Evans:</p><blockquote>A sphere of knowledge, influence, or activity. The subject area to which the user applies a program is the domain of the software.</blockquote><p>Domain-Driven Design is a well-known software design technique that uses a common language between system builders and business domain experts.</p><p>It’s not easy to identify domains, unlike features and components. But it’s critical to identify them in order to design truly independent, empowered, and expert products teams.</p><p>So, for our purpose in designing or organizing product teams, let’s define a domain as a group of related components.</p><p>Features, in most cases, require changes in multiple components, but they typically map one-to-one to domains.</p><p>So, if you have a domain team, the team will be responsible for the same related components in that domain. They will have complete ownership over these components.</p><p>The domain team will also be able to do features from A to Z that are related to that domain. So, you really take the best of both the component team and the feature team we discussed above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OusNLVpRn4kc2arbjAy7hA.jpeg" /></figure><p>If a feature needs changes in two domains, think twice about the feature or the boundary between domains. Most likely, the feature is actually a multiple of features, not one. Or if it’s really one feature, then the domains are probably not designed well.</p><p>The difficulty with designing domain teams is to actually identify the domains. There is no simple solution, but i will give a simple example and more resources to checkout at the end of the article.</p><h3>Domain Teams Example</h3><p>Let’s say you have a car renting application. Users will use your app to discover cars. If they like one, they can reserve it and then pay and collect it.</p><p>Notice in this simple sentence, we can identify three areas of interest to the business:</p><ul><li><strong>Discoverability</strong>: users should have a way to discover available cars based on distance, preference, etc..</li><li><strong>Reservation</strong>: users should be able to reserve a car once they find a suitable one.</li><li><strong>Payment</strong>: users should be able to pay through the application.</li></ul><p>So, we identified three domains. Now we can organize our teams based on these domains:</p><ul><li><strong>Discovery Team</strong></li><li><strong>Reservation Team</strong></li><li><strong>Payment Team</strong></li></ul><p>As we discussed above, features typically map one-to-one with domains.</p><p>For example, let’s say we want to implement a new feature. We want users to filter cars based on a luxury level. Well, that’s a discoverability concern for sure, so we assign this feature to the discovery team.</p><p>Let’s also say we don’t want users only to reserve one car; maybe some customers need several cars at once. That’s a reservation concern; we can assign this feature to the reservation team.</p><p>As the last example, maybe we want users to be able to split their payment or have payment plans. That’s a payment concern, so we assign this feature to the payment team.</p><p>Please note these are trivial examples. I just wanted to give you an idea about domain teams before ending this article. If you think hard enough, you might come up with a feature that requires changes in two or three of the domains we identified above. That’s why there are more involved techniques for identifying domains in your business, such as domain event storming, domain message flow modeling, bounded context, and context mapping.</p><h3>Team’s Cognitive Load</h3><p>Each domain can be pretty complex. Imagine the scenarios and edge cases that need to be handled by the reservation team, such as:</p><ul><li>Cars availability, such as cars already rented, cars that need maintenance, or cars that are being transported from one branch to another.</li><li>Renter eligibility based on law or history.</li><li>Notification and status update about a reservation, such as reserved, ready to pick up, in progress, or declined.</li></ul><p>I’m sure there are a lot more.</p><p>The reservation domain team can and should be masters of reservation and all its intricacies. But they cannot nor should be masters of discovery and all its intricacies and payment and all its intricacies.</p><p>When designing teams, we should thoughtfully think about the cognitive load required for each team.</p><h3>Conclusion</h3><p>The domain teams are really powerful. With domain teams, you will have the following:</p><ul><li>Independent teams with minimum coordination between them.</li><li>Complete ownership over their work, from planning, requirements gathering, and design to development, testing, and deploying to production.</li><li>They can’t be experts in all of your business and its systems, but they are masters of their domains.</li><li>Manageable cognitive load for each team</li><li>Expect things to move really fast without sacrificing quality.</li><li>Expect novel solutions to business problems.</li></ul><p>Thanks for reading.</p><h3>Useful Resources</h3><ul><li><a href="https://medium.com/nick-tune-tech-strategy-blog/domains-subdomain-problem-solution-space-in-ddd-clearly-defined-e0b49c7b586c">Domain, Subdomain, Bounded Context, Problem/Solution Space in DDD: Clearly Defined</a></li><li><a href="https://github.com/orgs/ddd-crew/repositories?type=all">Domain-Driven Design Crew</a></li><li><a href="https://www.youtube.com/watch?v=pw686Oyeqmw&amp;t=17s">Why Your Software Team CAN’T Scale</a></li><li><a href="https://teamtopologies.com/book">Team Topologies Book</a></li><li><a href="https://www.svpg.com/books/empowered-ordinary-people-extraordinary-products/">Empowered Book</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51e600fe9835" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stable vs. Volatile Dependencies]]></title>
            <link>https://medium.com/@Abdullah_th/stable-vs-volatile-dependencies-ab7162be6edd?source=rss-775503c5e098------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab7162be6edd</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Abdullah Althobetey]]></dc:creator>
            <pubDate>Mon, 21 Feb 2022 23:14:48 GMT</pubDate>
            <atom:updated>2022-02-21T23:14:48.360Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*RHDAdU-yDf5eDOy2qGcZVg.png" /></figure><p>In previous posts, we described dependency injection, which is a technique to inject an object into another object that needs it. But, should we inject all objects that an object needs? Of course not. We should inject volatile dependencies. We can safely directly depend on stable dependencies. This post is about these two concepts.</p><h4>Stable Dependencies</h4><p>Stable dependencies contain deterministic behavior. That is, given input (or no input), it always returns the same result (or does the same side-effect).</p><p>For example, say we have a simple cart class that calculates the total of given items:</p><pre>class Cart {<br>    private var items = [Item]()<br>    <br>    var total: Int {<br>        var result = 0<br>        items.forEach { result += $0.amount }<br>        return result<br>    }<br>    <br>    func add(item: Item) {<br>        items.append(item)<br>    }<br>}</pre><p>The behavior of this class is deterministic. When we add an item with an amount of 1, we will always get 1 as the total. When we add another item also of amount 1, we will always get 2 as the total.</p><p>So, if we have, for example, a CartViewController class that wants to use this Cart class, we can safely depend on Cart directly.</p><pre>class CartViewController: UIViewController {<br>    let cart = Cart()<br>    <br>    // ...<br>}</pre><p>In the book <em>Dependency Injection Principles, Practices, and Patterns</em> by <em>Steven van Deursen</em> and <em>Mark Seemann</em>, they describe this rule for stable dependencies:</p><blockquote>In general, DEPENDENCIES can be considered stable by exclusion. They’re stable if they aren’t volatile.</blockquote><p>I find this general rule very helpful when deciding if I need to inject a dependency or create it directly. So let’s look at how to spot volatile dependencies.</p><h4>Volatile Dependencies</h4><p>A volatile dependency, on the other hand, contains a <strong>nondeterministic</strong> behavior. You give it some input, and you get some output. But If you rerun it with the same input, you might get a different output.</p><p>A volatile dependency is volatile because:</p><ul><li>It depends on an external world to do its work. It’s known as out-of-process dependencies because it does their work outside of the application process.</li><li>Do a nondeterministic computation such as computations based on random numbers, date, or time</li><li>It’s under development or doesn’t exist yet, so we don’t know the outcome of using it.</li></ul><p>Let’s look at an example for each one of them.</p><h4>Out-of-process dependencies</h4><p>An out-of-process dependency, as the name suggests, does their work outside of our application process. That is, it depends on an external world that is outside of our world (the application world).</p><p>The obvious example of such dependencies is the network. When you send a request across the network, your request is processed on some external system, a server, or the cloud (which is another name for a server 😄).</p><p>For example, this ProductsViewController class directly depends on a volatile dependency:</p><pre>class ProductsViewController: UIViewController {<br>    let session = URLSession.shared<br>    <br>    func fetchProducts() {<br>        let request = URLRequest(url: URL(string: &quot;https://example.com/api&quot;)!)<br>        session.dataTask(with: request) { data, response, error in<br>            // ...<br>        }<br>    }<br>}</pre><p>URLSession is a volatile dependency because it deals with the network, an outside world to our application. You will never certainly know the outcomes of the requests it sends. It may fail from the operating system side (e.g., No connection available), it may reach the server, but the server is down, or the server may respond with an unexpected response.</p><p>To decouple our view controller from this uncertainty, we should instead inject URLSession:</p><pre>class ProductsViewController: UIViewController {<br>    let session: URLSession<br>    <br>    init(session: URLSession) {<br>        self.session = session<br>        super.init(nibName: nil, bundle: nil)<br>    }<br>    <br>    func fetchProducts() {<br>        let request = URLRequest(url: URL(string: &quot;https://example.com/api&quot;)!)<br>        session.dataTask(with: request) { data, response, error in<br>            // ...<br>        }<br>    }<br>}</pre><p>Now you can inject a URLSession with any configuration you want, not just URLSession.shared. Moreover, you can mock network requests using URLProtocol so that you can <strong>control</strong> the response coming from URLSession either for development or testing purposes:</p><pre>let config = URLSessionConfiguration.default<br>config.protocolClasses = [URLProtocolMock.self]<br>let session = URLSession(configuration: config)<br>let productsViewController = ProductsViewController(session: session)</pre><p>For more about mocking with URLProtocol, see this post(https://www.hackingwithswift.com/articles/153/how-to-test-ios-networking-code-the-easy-way).</p><h4>Nondeterministic computation dependencies</h4><p>The main problem with dependencies that has nondeterministic computations is that you cannot unit test them. Because every time you run them, they will produce a different result.</p><p>As an example, say we need to greet a user and tell them either good morning or good evening based on time:</p><pre>func great(user: User) -&gt; String {<br>    let now = Date()<br>    let components = Calendar.current.dateComponents([.hour], from: now)<br>    guard let hour = components.hour else { return &quot;Hello \(user.name)!&quot; }<br>    let isMorning = (0...11).contains(hour)<br>    let greeting = isMorning ? &quot;Good morning&quot; : &quot;Good evening&quot;<br>    return greeting + &quot; \(user.name)!&quot;<br>}<br><br>great(user: User(name: &quot;Abdullah&quot;))<br>// Output will be &quot;Good morning Abdullah!&quot; or &quot;Good evening Abdullah!&quot;</pre><p>Here is an attempt to test this code:</p><pre>class GreetingTests: XCTestCase {<br>    func test_greetUser() {<br>        let user = User(name: &quot;Abdullah&quot;)<br>        XCTAssertEqual(greet(user: user), &quot;Good morning Abdullah!&quot;)<br>    }<br>}</pre><p>The problem with this test is that it will succeed in the morning but fail in the evening. This is because our greet function directly depends on a volatile dependency, which is Date().</p><p>So, the solution is to use DI to inject a Date:</p><pre>func greet(user: User, at date: Date) -&gt; String {<br>    let components = Calendar.current.dateComponents([.hour], from: date)<br>    guard let hour = components.hour else { return &quot;Hello \(user.name)!&quot; }<br>    let isMorning = (0...11).contains(hour)<br>    let greeting = isMorning ? &quot;Good morning&quot; : &quot;Good evening&quot;<br>    return greeting + &quot; \(user.name)!&quot;<br>}<br><br>greet(user: User(name: &quot;Abdullah&quot;), at: Date())<br>// Output will be &quot;Good morning Abdullah!&quot; or &quot;Good evening Abdullah!&quot; based on current time</pre><p>And here is how we can easily test this new implementation:</p><pre>class GreetingTests: XCTestCase {<br>    func test_greetUserAtMorning() {<br>        let user = User(name: &quot;Abdullah&quot;)<br>        let date = Calendar.current.date(bySettingHour: 9, minute: 0, second: 0, of: Date())!<br>        XCTAssertEqual(greet(user: user, at: date), &quot;Good morning Abdullah!&quot;)<br>    }<br>    <br>    func test_greetUserAtEvening() {<br>        let user = User(name: &quot;Abdullah&quot;)<br>        let date = Calendar.current.date(bySettingHour: 16, minute: 0, second: 0, of: Date())!<br>        XCTAssertEqual(greet(user: user, at: date), &quot;Good evening Abdullah!&quot;)<br>    }<br>}</pre><h4>Under development dependencies</h4><p>Let’s say you want to create the user interface of a news application. You didn’t yet implement how to fetch that news, or maybe someone else is working on that. To start implementing the UI, you need at least a stub(https://en.wikipedia.org/wiki/Method<em>stub) to fetch some news and drive your UI.</em></p><pre>struct News {<br>    let title: String<br>    let content: String<br>}<br><br>protocol NewsLoader {<br>    func fetch(completion: (Result&lt;[News], Error&gt;) -&gt; Void)<br>}<br><br>class StubNewsLoader: NewsLoader {<br>    func fetch(completion: (Result&lt;[News], Error&gt;) -&gt; Void) {<br>        completion(.success([<br>            News(<br>                title: &quot;Title 1&quot;,<br>                content: &quot;Content 1 ...&quot;<br>            ),<br>            News(<br>                title: &quot;Title 2&quot;,<br>                content: &quot;Content 2 ...&quot;<br>            ),<br>            News(<br>                title: &quot;Title 3&quot;,<br>                content: &quot;Content 3 ...&quot;<br>            )<br>        ]))<br>    }<br>}<br><br>class NewsViewController: UIViewController {<br>    let newsLoader: NewsLoader<br>    <br>    init(newsLoader: NewsLoader) {<br>        self.newsLoader = newsLoader<br>        super.init(nibName: nil, bundle: nil)<br>    }<br>}</pre><p>Once you or someone else is done implementing the real news fetching, you can inject the actual implementation instead of the stub.</p><pre>class APINewsLoader: NewsLoader {<br>    let session: URLSession<br>    <br>    init(session: URLSession) {<br>        self.session = session<br>    }<br>    <br>    func fetch(completion: (Result&lt;[News], Error&gt;) -&gt; Void) {<br>        session.dataTask(with: request) { data, response, error in<br>            // ...<br>        }<br>    }<br>}<br><br>// Somewhere in your application<br>let apiNewsLoader = APINewsLoader(session: .shared)<br>let newsViewController = NewsViewController(newsLoader: apiNewsLoader)</pre><h4>Stable Dependency That Depends on Volatile Dependency</h4><p>So we described that volatile dependencies should be injected and not directly created. On the other hand, we can safely depend on stable dependencies.</p><p>But can we depend on a stable dependency that has a volatile dependency? Let’s see if we do.</p><p>Let’s say we want to create a view model for our news example. The view model will handle the fetching of news, so we will inject a NewsLoader in the view model instead of the view controller.</p><pre>class NewsViewModel {<br>    @Published var allNews = [News]()<br>    @Published var loadingError: Error? = nil<br>    let newsLoader: NewsLoader<br>    <br>    init(newsLoader: NewsLoader) {<br>        self.newsLoader = newsLoader<br>    }<br>    <br>    func load() {<br>        newsLoader.fetch { [weak self] result in<br>            switch result {<br>            case .success(let loadedNews):<br>                self?.allNews = loadedNews<br>            case .failure(let error):<br>                self?.loadingError = error<br>            }<br>        }<br>    }<br>}</pre><p>The NewsViewModel depends on NewsLoader, which is a volatile dependency, so we inject it. In NewsViewController, we cannot create NewsViewModel directly because it requires a NewsLoader.</p><p>One solution is to inject a NewsLoader into NewsViewController, and then the NewsViewController passes the NewsLoader to the NewsViewModel.</p><pre>class NewsViewController: UIViewController {<br>    let newsViewModel: NewsViewModel<br>    <br>    init(newsLoader: NewsLoader) {<br>        self.newsViewModel = NewsViewModel(newsLoader: newsLoader)<br>        super.init(nibName: nil, bundle: nil)<br>    }<br>}</pre><p>As you can see, we only pass NewsLoader to NewsViewController so that we can create a NewsViewModel. This is similar to the middle-man anti-pattern(https://refactoring.guru/smells/middle-man).</p><p>Indeed the NewsViewController needs a NewsViewModel, but it doesn’t have to create it.</p><p>A better solution is to inject the NewsViewModel into the NewsViewController directly.</p><pre>class NewsViewController: UIViewController {<br>    let newsViewModel: NewsViewModel<br>    <br>    init(newsViewModel: NewsViewModel) {<br>        self.newsViewModel = newsViewModel<br>        super.init(nibName: nil, bundle: nil)<br>    }<br>}</pre><p>Somewhere in your application, you create the NewsViewController like the following:</p><pre>let apiNewsLoader = APINewsLoader(session: .shared)<br>let newsViewModel = NewsViewModel(newsLoader: apiNewsLoader)<br>let newsViewController = NewsViewController(newsViewModel: newsViewModel)</pre><p>By the way, the NewsViewModel should be considered as a <strong>volatile dependency</strong>, not a stable dependency that depends on a volatile one.</p><p>Once a type depends on a volatile dependency, it itself also becomes volatile. I included this section because it’s a common mistake.</p><h4>Injecting stable dependencies to pass data</h4><p>The last thing I want to touch upon is that you might use DI to inject stable dependencies just to pass data.</p><p>For example, let’s say we want to display each news on it’s own screen.</p><pre>class NewsDetailViewController: UIViewController {<br>    let news: News<br>    <br>    init(news: News) {<br>        self.news = news<br>        super.init(nibName: nil, bundle: nil)<br>    }<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        display(news)<br>    }<br>    <br>    private func display(_ news: News) {<br>        // ...<br>    }<br>}</pre><p>The news struct is pretty stable, it’s just two fields of type String, but we don’t know at compile time which News to pass.</p><p>At run time, when, for example, we tap on a news in NewsViewController, the news will be passed to NewsDetailViewController.</p><pre>class NewsViewController: UIViewController {<br>    let newsViewModel: NewsViewModel<br>    <br>    init(newsViewModel: NewsViewModel) {<br>        self.newsViewModel = newsViewModel<br>        super.init(nibName: nil, bundle: nil)<br>    }<br>    <br>    func tappedOn(news: News) {<br>        let newsDetailViewController = NewsDetailViewController(news: news)<br>        show(newsDetailViewController, sender: nil)<br>    }<br>}</pre><h4>Conclusion</h4><p>We looked at the difference between stable and volatile dependencies and that we should always inject the volatile ones. Because volatile dependencies are hard to control, you will lose control of your application if you always create your volatile dependencies directly. If you inject them instead, you will have absolute control over these difficult dependencies.</p><p>If each type keeps asking the layer before it for its dependencies, you will find yourself creating all of your dependencies at the root (entry point) of your application, and that is a good thing.</p><p>The next post will be about the composition root pattern, a way to create and control all your app dependencies and extend or intercept them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab7162be6edd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency Injection Patterns]]></title>
            <link>https://medium.com/@Abdullah_th/dependency-injection-patterns-623b175256f?source=rss-775503c5e098------2</link>
            <guid isPermaLink="false">https://medium.com/p/623b175256f</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Abdullah Althobetey]]></dc:creator>
            <pubDate>Mon, 21 Feb 2022 01:14:04 GMT</pubDate>
            <atom:updated>2022-02-21T01:14:04.119Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*ZC3nbzDWo2VLghG2qL9pUA.png" /></figure><p>In this post, I will explain dependency injection with examples written in Swift</p><p>Dependency injection (DI for short) is a software engineering technique where an object, method, or function receives other objects or functions that it needs.</p><p>Unfortunately, many developers often overlook DI (I certainly did in the past) despite their incredible benefits, especially when your project grows.</p><h4>Why dependency injection</h4><p>For me, the most significant benefit of DI is <strong>control</strong>. With proper DI, you will have more control over your program. Without DI, and as your program grows, your program will probably control you more. We’ve all been there; think of that legacy library or framework you couldn’t replace because it’s used all over the place.</p><p>For more about DI benefits, see my <a href="https://medium.com/@Abdullah_th/why-dependency-injection-6a7c5b0a352e">previous post</a>. For now, let’s focus on DI patterns in Swift.</p><h4>Initializer injection</h4><p>Initializer injections is the act of defining the required dependencies as parameters to the type’s initializer. It can be applied to a class, struct, or enum, and the dependencies can be other classes, structs, enums, or functions.</p><p>For example:</p><pre>class Profile {<br>    private let user: User<br>    <br>    init(user: User) {<br>        self.user = user<br>    }<br>}</pre><p>Initializer injection is the most important pattern in DI, and it should be your go-to pattern unless required (see other patterns below).</p><p>In the code example above, it doesn’t make sense for a Profile to exists without a User, so if you want to use the Profile class, you have to supply a User when you create it.</p><p>This will save your code from optionals mayhem. If we define user as an optional inside Profile, we will have a lot of if lets or guards in all over the place in the Profile class.</p><h4>Method/function injection</h4><p>Like initializer injection, in method/function injection, you supply the required dependencies as parameters to the method or function.</p><p>The reason to use method/function injection instead of initializer injection is that the required dependencies may vary with each method/function call.</p><p>For example, let’s say in Profile, we can redeem some kind of coupon for user, and the user can redeem any number of coupons. So the dependency (coupon) can vary at each call to the redeem service:</p><pre>class Profile {<br>    private let user: User<br>    private let couponRedemption: CouponRedemption<br>    <br>    init(user: User, couponRedemption: CouponRedemption) {<br>        self.user = user<br>        self.couponRedemption = couponRedemption<br>    }<br>    <br>    func redeem(coupon: Coupon) {<br>        couponRedemption.redeem(coupon)<br>    }<br>}</pre><p>To do the actual redemption, we need to call some sort of a service object. In this case, it’s CouponRedemption, which is another excellent example of initializer injection!</p><h4>Property injection</h4><p>Property injection can be applied when a type exposes a writeable property so that callers can replace the property value with another one.</p><p>Property injection is often used when a type has a good default dependency. But beware that the default dependency should be what it’s often called a <strong>stable</strong> dependency and not a <strong>volatile</strong> one. If the dependency is volatile, you should use the initializer injection instead. I’ll save the explanation about stable dependency versus volatile dependency in another post.</p><p>Another thing to be aware of is the default dependency should originate from the same module or layer. Because if you use a dependency from another module, you will unnecessarily couple the two modules together. In that case, initializer injection is the way to go. Again I will hopefully write about this in another post. For now, let’s focus on DI patterns.</p><p>As an example of a property injection, let’s say in profile, we want the user to select a theme for the application. Of course, we will have a default theme for the app. It’s not wise to tell the user to choose a theme the first time they open our app!</p><pre>enum Theme {<br>    case darkOrange<br>    case liteOrange<br>    case gray<br>    case blackAndWhite<br>}<br><br>class Profile {<br>    private let user: User<br>    private let couponRedemption: CouponRedemption<br>    var theme: Theme = .darkOrange<br>    <br>    init(user: User, couponRedemption: CouponRedemption) {<br>        self.user = user<br>        self.couponRedemption = couponRedemption<br>    }<br>    <br>    func redeem(coupon: Coupon) {<br>        couponRedemption.redeem(coupon)<br>    }<br>}</pre><h4>Conclusion</h4><p>As a good tip, always prefer initializer injection unless required. If the dependency your type requires will vary through method/function calls, then use method/function injection. If you have a good default dependency that is stable and originate in the same module or layer, use property injection.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=623b175256f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Dependency Injection?]]></title>
            <link>https://medium.com/@Abdullah_th/why-dependency-injection-6a7c5b0a352e?source=rss-775503c5e098------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a7c5b0a352e</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[dependency-inversion]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Abdullah Althobetey]]></dc:creator>
            <pubDate>Sat, 19 Feb 2022 22:52:17 GMT</pubDate>
            <atom:updated>2022-02-19T22:52:17.015Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EBRwP0NChJoHPJvjvZ8vwQ.png" /></figure><p>In the <a href="https://medium.com/@Abdullah_th/what-is-dependency-injection-c21325686fa7">previous post</a>, we discussed the what of DI. In this post, we will explore the why.</p><p>DI enables many benefits; before discussing those benefits, let us establish an example. let’s say we have a view controller that can display news:</p><pre>class NewsViewController: UIViewController {<br>    let newsLoader: NewsLoader<br> <br>    init(newsLoader: NewsLoader) {<br>        self.newsLoader = newsLoader<br>        super.init(nibName: nil, bundle: nil)<br>    }<br>}</pre><p>The NewsViewController uses DI because it doesn’t create a NewsLoader. Instead, it states that it needs a NewsLoader. <br>The NewsLoader is defined as a protocol:</p><pre>protocol NewsLoader {<br>    func load(completion: (Result&lt;[News], Error&gt;) -&gt; Void)<br>}</pre><p>And we have two types that implement the NewsLoader protocol. One fetches the news from the network. The other fetches the news from a database:</p><pre>class APINewsLoader: NewsLoader {<br>    func load(completion: (Result&lt;[News], Error&gt;) -&gt; Void) {<br>        // load news from the network<br>    }<br>}</pre><pre>class DatabaseNewsLoader: NewsLoader {<br>    func load(completion: (Result&lt;[News], Error&gt;) -&gt; Void) {<br>        // load news from a local database<br>    }<br>}</pre><p>So you can use the same NewsViewController to display news from different sources. If you want to fetch news from the network, you use:</p><pre>let apiNewsLoader = APINewsLoader()<br>let newsViewController = NewsViewController(newsLoader: apiNewsLoader)</pre><p>If you want to display news from a database, you use:</p><pre>let databaseNewsLoader = DatabaseNewsLoader()<br>let newsViewController = NewsViewController(newsLoader: databaseNewsLoader)</pre><p>With this example established, let’s explore the benefits of DI.</p><h3>Late binding</h3><p>Late binding basically means that you bind the dependency later. That is, you decide which dependency to use at run time instead of compile time. <br>For example, say we want to display news from the network only if the device is online. If the device is offline, we will display news from the database instead:</p><pre>if Network.isOnline {<br>    let newsViewController = NewsViewController(newsLoader: apiNewsLoader)<br>} else {<br>    let newsViewController = NewsViewController(newsLoader: databaseNewsLoader)<br>}</pre><h3>Dependency Inversion</h3><p>If our NewsViewController doesn’t use DI and creates its news loader dependency directly like so:</p><pre>class NewsViewController: UIViewController {<br>    let newsLoader = APINewsLoader()<br>}</pre><p>Then we can say our NewsViewController directly depends on APINewsLoader.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*7IWEyWmQ3zT8KsYSuVco8Q.png" /></figure><p>However, when NewsViewController doesn’t depend on APINewsLoader but depends on NewsLoader. Then in order to make APINewsLoader work with NewsViewController we need to confirm it to the NewsLoader protocol. So we inverted the dependency</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LFe9jXJ_r8zLsMRO69GK_g.png" /></figure><p>Note that instead of the arrow going from NewsViewController to APINewsLoader, the arrow goes back from APINewsLoader to NewsLoader, hence the name dependency inversion.</p><p>It is worth noting that NewsLoader should be owned by the module (or layer) that owns the NewsViewController. If not, then NewsViewController still has a direct dependency to another module/layer.</p><p>If we re-draw the previous diagram between the modules/layers instead of the individual classes, the dependency inversion concept will be more apparent.</p><p>So, without using NewsLoader to invert the dependency, we will have a direct dependency between the module that has NewsViewController and the module that has APINewsLoader</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*Wyf_XbABCTnAhlfRCCTyoA.png" /></figure><p>If we define NewsLoader inside the same module that has APINewsLoader, then we still have a direct dependency from the first module to the second one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ASnyEYCwTaOIJKLV1J3CUA.png" /></figure><p>To invert the dependency, we define NewsLoader inside the same module that has NewsViewController.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4jrmYPs8ZPV2LVw-bWszEQ.png" /></figure><p>Dependency inversion is an essential technique in architecture, where we might want to protect some modules from depending on others. Typically, we want our application code not to depend on frameworks.</p><p>In our example, APINewsLoader indeed uses some framework to do the actual networking calls. Since NewsViewController doesn’t directly depend on it, we can change or replace that framework without needing to change our UI.</p><h3>Testability</h3><p>To unit test the NewsViewController, we want to focus on the NewsViewController behavior itself, and not any collaborating objects. However, we cannot run NewsViewController without a NewsLoader. Since we are using DI to inject NewsLoader, we don’t have to inject a real implementation such as APINewsLoader or DatabaseNewsLoader. Instead, we can define a <strong>mock</strong> implementation of NewsLoader</p><pre>class MockNewsLoader: NewsLoader {<br>    func load(completion: (Result&lt;[News], Error&gt;) -&gt; Void) {<br>        // No need to hit the real network or call the real database<br>        // you can return any news you want here to use in testing<br>    }<br>}</pre><pre>class NewsViewControllerTests: XCTestCase {<br>    func test_theThingYouWantToTest() {<br>       let mockNewsLoader = MockNewsLoader()<br>       let newsViewController = NewsViewController(newsLoader: mockNewsLoader)<br> <br>       // test code here …<br>    }<br>}</pre><h3>Extensibility</h3><p>Let’s say that you want to load news related to Apple only, and you want to reuse the same NewsViewController to display Apple news.<br> <br>The two classes we defined above, APINewsLoader and DatabaseNewsLoader, return all news. We don’t have to write, for example, APIAppleNewsLoader and DatabaseAppleNewsLoader and implement the same behavior except filtering the news. That is too much unnecessary work.</p><p>With proper DI, we can implement this feature without changing existing ones. We can define AppleNewsLoader that implements the same NewsLoader and inject into it another NewsLoader. So we can reuse previous implementations and add on them (extent) new ones.</p><pre>class AppleNewsLoader: NewsLoader {<br>    let newsLoader: NewsLoader<br> <br>    init(newsLoader: NewsLoader) {<br>        self.newsLoader = newsLoader<br>    }<br> <br>    func load(completion: (Result&lt;[News], Error&gt;) -&gt; Void) {<br>        newsLoader.load { result in<br>            switch result {<br>            case .success(let news):<br>                let appleNews = getAppleNews(from: news)<br>                completion(.success(appleNews))<br>            case .failure(let error):<br>                completion(.failure(error))<br>            }<br>        }<br>    }<br> <br>    private func getAppleNews(from: [News]) -&gt; [News] {<br>        // filter and return Apple news …<br>    }<br>}</pre><p>To use our new AppleNewsLoader with news either from the network or the database, depending on the status of the device network, we can construct our objects as follow:</p><pre>let newsLoader: NewsLoader = Network.isOnline ? APINewsLoader() : DatabaseNewsLoader()<br>let appleNewsLoader = AppleNewsLoader(newsLoader: newsLoader)<br>let newsViewController = NewsViewController(newsLoader: appleNewsLoader)</pre><p>As you can see, DI enables us to compose and extent our objects in unprecedented ways!</p><h3>Conclusion</h3><p>There are many benefits to DI. We only discussed the main ones. These primary benefits also, in turn, enable other benefits. For example, testability enables maintainability, and dependency inversion enables loos-coupling and parallel development.</p><p>I will continue to write about DI in my blog, and I’m planning to do a complete sample project. So if you are interested, please subscribe to my newsletter.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a7c5b0a352e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is Dependency Injection?]]></title>
            <link>https://medium.com/@Abdullah_th/what-is-dependency-injection-c21325686fa7?source=rss-775503c5e098------2</link>
            <guid isPermaLink="false">https://medium.com/p/c21325686fa7</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Abdullah Althobetey]]></dc:creator>
            <pubDate>Fri, 18 Feb 2022 15:49:06 GMT</pubDate>
            <atom:updated>2022-02-18T16:23:04.138Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3lkJStyNjJN5WZHR_25bCA.png" /></figure><p>Dependency injection (DI for short) at its core is a very simple technique, but using it will enable other advanced patterns and principles that will help you develop clean and loosely-coupled applications.</p><h3>DI Definitions</h3><p>Let’s explore some popular definitions of DI.</p><blockquote>dependency injection is a technique in which an object receives other objects that it depends on, called dependencies. <a href="https://en.wikipedia.org/wiki/Dependency_injection">Wikipedia</a></blockquote><p>In StackOverflow, the popular Q&amp;A website for developers, John Munsch gave an excellent explanation of DI in response to the question “How to explain dependency injection to a 5-year-old?”</p><blockquote>When you go and get things out of the refrigerator for yourself, you can cause problems. You might leave the door open, you might get something Mommy or Daddy doesn’t want you to have. You might even be looking for something we don’t even have or which has expired.<br>What you should be doing is stating a need, “I need something to drink with lunch,” and then we will make sure you have something when you sit down to eat. <a href="https://stackoverflow.com/questions/1638919/how-to-explain-dependency-injection-to-a-5-year-old">stackoverflow</a></blockquote><p>Another very compact definition of DI given by James Shore:</p><blockquote>Dependency injection means giving an object its instance variables. <a href="https://www.jamesshore.com/v2/blog/2006/dependency-injection-demystified">jamesshore.com</a></blockquote><p>A final definition I will include here is one from the book <em>Dependency Injection Principles, Practices, and Patterns by Steven van Deursen and Mark Seemann</em>. It’s a bit advanced, which states the whole goal of DI:</p><blockquote>Dependency Injection is a set of software design principles and patterns that enables you to develop loosely coupled code.</blockquote><p>I will write in this blog about many of these principles and patterns. So be around! For now, let’s try to use DI in Swift.</p><h3>DI in Swift</h3><p>Here is a basic DI example in Swift:</p><pre>class Profile {<br>    private let user: User<br> <br>    init(user: User) {<br>        self.user = user<br>    }<br>}</pre><p>The Profile class doesn’t create a user; it **<em>states</em>** that it needs a user in order to instantiate it. Clients of the Profile class will need to supply the user dependency.</p><p>Swift is a general-purpose and multi-paradigm programming language. You can write Swift code in an imperative style (object-oriented programming or procedural programming) or in a declarative style (functional programming).</p><p>In Swift, we have *classes*, *structs*, *enums*, *methods*, and *functions*. All of these types can receive dependencies which are other *classes*, *structs*, *enums* or *functions*.</p><p>Here is an example of a function that receives a dependency:</p><pre>func calculate(bill: Bill) -&gt; Int {<br>   var result = 0<br>   bill.items.forEach { result += $0.cost }<br>   return result<br>}</pre><p>Another example where a function receives another function as a dependency:</p><pre>func print(bill: Bill, billCalculator: (Bill) -&gt; Int) {<br>    bill.items.forEach { print(“\($0.name): \($0.cost)”)}<br>    let total = billCalculator(bill)<br>    print(“Total: \(total)”)<br>}</pre><h3>Conclusion</h3><p>We only scratch the surface of DI. There are many benefits that DI enables, such as late binding, dependency inversion, extensibility, and testability. We will explore them in the next post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c21325686fa7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>