<?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 Tung Vu Duc 🇻🇳 on Medium]]></title>
        <description><![CDATA[Stories by Tung Vu Duc 🇻🇳 on Medium]]></description>
        <link>https://medium.com/@tungvuduc2805?source=rss-30f65d7d355a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*Xf3tDXlq5WBFQXPGx0XQyw.jpeg</url>
            <title>Stories by Tung Vu Duc 🇻🇳 on Medium</title>
            <link>https://medium.com/@tungvuduc2805?source=rss-30f65d7d355a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 22:26:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tungvuduc2805/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[Dependency Injection: It’s more powerful than you think.]]></title>
            <link>https://tungvuduc2805.medium.com/dependency-injection-its-more-powerful-than-you-think-80a99da95cb3?source=rss-30f65d7d355a------2</link>
            <guid isPermaLink="false">https://medium.com/p/80a99da95cb3</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Tung Vu Duc ]]></dc:creator>
            <pubDate>Mon, 12 Apr 2021 04:50:28 GMT</pubDate>
            <atom:updated>2022-10-04T07:15:27.935Z</atom:updated>
            <content:encoded><![CDATA[<p>How are you using dependency injection ?</p><p>Today we’re going to learn about dependency injection (DI) through a case study I recently faced at work and I think you guys will find familiar with it.</p><p>In case you aren’t familiar with dependency injection concept. You can watch a video of mine here (it’s in Vietnamese):<br><a href="https://tungvuduc2805.medium.com/dependency-injection-explained-dependency-2aa411a5258a">https://tungvuduc2805.medium.com/dependency-injection-explained-dependency-2aa411a5258a</a></p><h3>Case study</h3><p>I have an application that allows logged in user to scan an identity card using NFC technology and then navigate to the detail screen to show the card’s information. Behind the sense after user scan their card, I’ll call an API to check if the card is registered in the database or not. Base on that result and the user’s role the detail screen will show differently as shown bellow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tr8JBJ7byj2WylCV.png" /></figure><p>The card’s information at the top of the screen is exactly the same in all cases but the button at the bottom of the screen is different. As you can see we have three cases I can assume as follow:</p><ul><li>If you are a regular user you can simply back to the app’s main screen regardless the card is registered or not.</li><li>If you logged in as an admin and the card is not registered. You can register the card.</li><li>If you are an admin and the card is already registered. You can report it for some reasons in order to delete the card from database.</li></ul><p>OK so it’s our problem. If you were me, how would you solve this ? Stop here and try to find a solution before continue. In the next section, I’m going to show you a bad solution (and the most common solution) I’ve seen in many codebases.</p><h3>Bad solution</h3><p>The bad solution is using if-else statements inside the detail screen to switch between cases. You’ll see something like this:</p><pre><em>class</em> CardDetailViewController: <em>UIViewController</em> {<br>    <br>    @IBOutlet var footerButton: <em>UIButton</em>!<br>    var cardModel: <em>CardModel</em>!</pre><pre>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        if <em>UserManager</em>.shared.isAdmin {<br>            if cardModel.isRegistered {<br>                footerButton.setTitle(&quot;Report&quot;, for: .normal)<br>                footerButton.backgroundColor = <em>UIColor</em>.systemRed<br>                footerButton.setTitleColor(.white, for: .normal)<br>                footerButton.addTarget(self, action: #selector(reportCard), for: .touchUpInside)<br>            } else {<br>                footerButton.setTitle(&quot;Register card&quot;, for: .normal)<br>                footerButton.setTitleColor(.white, for: .normal)<br>                footerButton.backgroundColor = <em>UIColor</em>.systemGreen<br>                footerButton.addTarget(self, action: #selector(registerCard), for: .touchUpInside)<br>            }<br>        } else {<br>            footerButton.setTitle(&quot;Back to main&quot;, for: .normal)<br>            footerButton.backgroundColor = <em>UIColor</em>.clear<br>            footerButton.addTarget(self, action: #selector(backToMain), for: .touchUpInside)<br>        }<br>    }<br>    <br>    @objc func reportCard() {<br>        // navigate to report card screen<br>    }<br>    <br>    @objc func registerCard() {<br>        // navigate to register card screen<br>    }<br>    <br>    @objc func backToMain() {<br>        // back to main screen<br>    }<br>}</pre><p>Why is that solution bad ?</p><ol><li>When view controller responsible for displaying views. It’s not responsible for checking user’s role so by doing as above you’re making the view controller doing a thing it’s not responsible for which violates single responsibility principle.</li><li>What if I my application getting more complicated with more roles ? Then the more role added the more if-else case I need to add to the CardDetailViewController and then it’ll quickly become overwhelmed. Also it violates another principle that is open-closed principle.</li></ol><p>I think that two main reason is enough for us to find a better solution we need a way to move that logic away from CardDetailViewController and I think the best way and easiest way to do it is using dependency injection. So let’s try to apply it.</p><h3>Dependency Injection</h3><p>If you’re familiar with DI concept. You’ve known that it’s a concept that we manage/inject dependencies from outside its client. But sometimes we mistakenly think dependency is something should be big, it should be a class that we created or it should be a module. But it is not. Dependency is everything your client needs from its outside in order to do some operations so you you have a function that need an url of type URL:</p><pre>func functionA(url: URL) {}</pre><p>or another function needs an id of type Integer:</p><pre>func functionA(id: <em>Int</em>) {}</pre><p>Many many more. URL, Int,… all of those are considered as dependencies.</p><p>So apply to our case study. Instead of let the view controller decide how the button look like and what action when tap on the button. We’ll inject it.</p><p>First, I want to encapsulate variants of the button into a module could simply a struct like this:</p><pre>struct <em>ButtonAttributes</em> {<br>    let title: <em>String</em><br>    let font: <em>UIFont</em><br>    let backgroundColor: <em>UIColor</em><br>    let titleColor: <em>UIColor</em><br>    let action: () -&gt; <em>Void</em><br>}</pre><p>Second, I inject dependencies to CardDetailViewController:</p><pre><em>class</em> CardDetailViewController: <em>UIViewController</em> {<br>    <br>    @IBOutlet var footerButton: <em>UIButton</em>!<br>    var cardModel: <em>CardModel</em>!<br>    var footerButtonAttribute: <em>ButtonAttributes</em>!  </pre><pre>   convenience init(model: <em>CardModel</em>, footerButtonAttribute: <em>ButtonAttributes</em>) {<br>        self.init()<br>        self.cardModel = model<br>        self.footerButtonAttribute = footerButtonAttribute<br>    }<br>}</pre><p>And finally, remove the if-else logic from CardDetailViewController and now the view controller just display the way it is given to:</p><pre><em>class</em> CardDetailViewController: <em>UIViewController</em> {<br>     ....<br>     override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        footerButton.setTitle(footerButtonAttribute.title, for: .normal)<br>        footerButton.backgroundColor = footerButtonAttribute.backgroundColor<br>        footerButton.setTitleColor(footerButtonAttribute.titleColor, for: .normal)<br>        footerButton.titleLabel?.font = footerButtonAttribute.font<br>        footerButton.addTarget(self, action: #selector(footerButtonTapped), for: .touchUpInside)<br>    }</pre><pre>    @objc func footerButtonTapped() {<br>        footerButtonAttribute.action()<br>    }<br>}</pre><p>And then we can initiate CardDetailViewController by compose its dependency from outside like this ✅</p><pre>var detailViewController: <em>CardDetailViewController</em>!<br>if <em>UserManager</em>.shared.isAdmin {<br>   if cardModel.isRegistered {<br>      let attributes = ButtonAttributes(title: &quot;Back to main&quot;,<br>                                 font: .systemFont(ofSize: 17),<br>                                 backgroundColor: .clear,<br>                                 titleColor: .systemBlue,<br>                                 action: {<br>                                    navigationController.popToRoot(animated: true)<br>   })<br>       detailViewController = CardDetailViewController(model: model, footerButtonAttribute: attributes) <br>   } else {<br>       ....<br>   }<br>} else {<br>   ...<br>}</pre><pre>navigationController.pushViewController(detailViewController, animated: true)</pre><h3>Conclusion</h3><p>So that’s it. Dependency injection is one of the the most powerful tool I’ve learn so far. So if you aren’t know about it then learn it. If you’ve learn it, practice it more.<br>Finally I hope you’ve got something for yourself from this post. If you like it don’t forget to share and claps to promote my work, if you have any questions relate to this topic feel free to comment down bellow.</p><p>Thank you, don’t forget to practice on your own. You can visit my personal blog to see more posts from me:</p><p><a href="https://learnwithtung.co/">https://learnwithtung.co/</a></p><p>See you in the next post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80a99da95cb3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using DiffableDataSource and Combine.]]></title>
            <link>https://tungvuduc2805.medium.com/using-diffabledatasource-and-combine-711555dc8734?source=rss-30f65d7d355a------2</link>
            <guid isPermaLink="false">https://medium.com/p/711555dc8734</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[diffable-data-sources]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Tung Vu Duc ]]></dc:creator>
            <pubDate>Mon, 25 Jan 2021 05:04:55 GMT</pubDate>
            <atom:updated>2021-01-25T05:05:19.266Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*9ypEBACv5AVcAZbqBnqhjw.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@cottonbro?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">cottonbro</a> from <a href="https://www.pexels.com/photo/white-and-blue-ball-on-brown-wooden-drawer-5097280/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p><strong>Visit my website to read the original post:</strong></p><p><a href="http://learnwithtung.co/2021/01/using-diffabledatasource-combine/">http://learnwithtung.co/2021/01/using-diffabledatasource-combine/</a></p><p>DiffableDataSource is an API was introduced in iOS 13. It helps us more efficiently and easily setup datasource for a table view or collection view. Today, we’re gonna increase its powerful by using it with the Combine framework. OK, let’s see how it work together.</p><p>Before start feel free to download and then open the starter project:</p><p><a href="https://github.com/LearnWithTung/DiffableCombine/tree/master/starter">LearnWithTung/DiffableCombine</a></p><h3>Networking with Combine</h3><p>After you open the project. Let’s move to <strong>APIService.swift</strong> file and add this code bellow the line //Write your code below :</p><pre>// 1<br> func fetchUsers() -&gt; <em>AnyPublisher</em>&lt;[<em>User</em>], <em>Error</em>&gt;{<br>        // 2<br>        let url = URL(string: &quot;https://jsonplaceholder.typicode.com/users&quot;)!<br>        // 3<br>        let publisher = <em>URLSession</em>.shared.dataTaskPublisher(for: url)<br>            // 4<br>            .map(\.data)<br>            // 5<br>            .decode(type: [<em>User</em>].self, decoder: JSONDecoder())<br>            // 6<br>            .eraseToAnyPublisher()<br>        // 7<br>        return publisher<br>    }</pre><ol><li>We define the function in order to gets data from API and then returns a publisher will emit either a list of User or an error if something went wrong.</li><li>Very native we create a URL from the string.</li><li>If before we have something like URLSession.shared.dataTask(with: URL) and then call resume() now by using combine we create a publisher responsible for download data from URL by calling dataTaskPublisher(for: URL) .</li><li>Using map key path operator in order to get only data from response</li><li>We use another operator called decode. The operator will try to decode the data above and map it to given type by given decoder.</li><li>A Special operator helps us hide all the return detail types</li><li>Finally, we return the publisher, clients will free to call and interact with it.</li></ol><p>Now open <strong>FeedViewController.swift</strong>, add this line of code right bellow where the class was defined and above @IBOutlet weak var tableView: UITableView!:</p><pre>// 1<br>    private var subscriptions = [AnyCancellable]()<br>    // 2<br>    @Published var users = [User]()</pre><ol><li>To store publishers in this list and Combine will automatically release all publisher for you when the view controller deallocate.</li><li>To store list users we fetched from URL. Notice that it’s not just an array, we make it a publisher by mark @Published.</li></ol><p>Then add this code bellow viewDidLoad() to use what we created above:</p><pre>private func loadPosts(){<br>        // 1<br>        <em>APIService</em>.shared.fetchUsers()<br>            // 2<br>            .sink { (error) in<br>                // handle error<br>            // 3<br>            } receiveValue: { (users) in<br>                self.users = users<br>            }<br>            // 4<br>            .store(in: &amp;subscriptions)<br>    }</pre><ol><li>Call fetchUsers method from APIService.</li><li>Listen to error. In the scope of this post, we do nothing with any errors.</li><li>Listen to list of users. When users received we store if in our property.</li><li>Store this publisher to the subscriptions.</li></ol><pre>loadPosts()</pre><h3>Using DiffableDataSource and Combine.</h3><p>DiffableDataSource is an API was introduced in iOS 13. It helps us more efficiently and easily setup datasource for a table view or collection view. Today, we’re gonna increase its powerful by using it with the Combine framework. OK, let’s see how it work together.</p><p>Before start feel free to download and then open the starter project:</p><p><a href="https://github.com/LearnWithTung/DiffableCombine/tree/master/starter">https://github.com/LearnWithTung/DiffableCombine/tree/master/starter</a></p><h3>Networking with Combine</h3><p>After you open the project. Let’s move to <strong>APIService.swift</strong> file and add this code bellow the line //Write your code below :</p><pre>// 1<br> func fetchUsers() -&gt; <em>AnyPublisher</em>&lt;[<em>User</em>], <em>Error</em>&gt;{<br>        // 2<br>        let url = URL(string: &quot;https://jsonplaceholder.typicode.com/users&quot;)!<br>        // 3<br>        let publisher = <em>URLSession</em>.shared.dataTaskPublisher(for: url)<br>            // 4<br>            .map(\.data)<br>            // 5<br>            .decode(type: [<em>User</em>].self, decoder: JSONDecoder())<br>            // 6<br>            .eraseToAnyPublisher()<br>        // 7<br>        return publisher<br>    }</pre><ol><li>We define the function in order to gets data from API and then returns a publisher will emit either a list of User or an error if something went wrong.</li><li>Very native we create a URL from the string.</li><li>If before we have something like URLSession.shared.dataTask(with: URL) and then call resume() now by using combine we create a publisher responsible for download data from URL by calling dataTaskPublisher(for: URL) .</li><li>Using map key path operator in order to get only data from response</li><li>We use another operator called decode. The operator will try to decode the data above and map it to given type by given decoder.</li><li>A Special operator helps us hide all the return detail types</li><li>Finally, we return the publisher, clients will free to call and interact with it.</li></ol><p>Now open <strong>FeedViewController.swift</strong>, add this line of code right bellow where the class was defined and above @IBOutlet weak var tableView: UITableView!:</p><pre>// 1<br>    private var subscriptions = [AnyCancellable]()<br>    // 2<br>    @Published var users = [User]()</pre><ol><li>To store publishers in this list and Combine will automatically release all publisher for you when the view controller deallocate.</li><li>To store list users we fetched from URL. Notice that it’s not just an array, we make it a publisher by mark @Published.</li></ol><p>Then add this code bellow viewDidLoad() to use what we created above:</p><pre>private func loadPosts(){<br>        // 1<br>        <em>APIService</em>.shared.fetchUsers()<br>            // 2<br>            .sink { (error) in<br>                // handle error<br>            // 3<br>            } receiveValue: { (users) in<br>                self.users = users<br>            }<br>            // 4<br>            .store(in: &amp;subscriptions)<br>    }</pre><ol><li>Call fetchUsers method from APIService.</li><li>Listen to error. In the scope of this post, we do nothing with any errors.</li><li>Listen to list of users. When users received we store if in our property.</li><li>Store this publisher to the subscriptions.</li></ol><p>Inside viewDidLoad() after super.viewDidLoad() we call the function:</p><pre>loadPosts()</pre><h3>Setup datasource using DiffableDataSource</h3><p>Below @IBOutlet weak var tableView: UITableView! we define data source type and snapshot type like this:</p><pre>// 1<br>    typealias <em>DiffableDataSource</em> = <em>UITableViewDiffableDataSource</em>&lt;<em>Int</em>, <em>User</em>&gt;<br>    // 2<br>    typealias <em>Snapshot</em> = <em>NSDiffableDataSourceSnapshot</em>&lt;<em>Int</em>, <em>User</em>&gt;</pre><ol><li>Define our data source type as UITableViewDiffableDataSource of section as Int, and cell model as User.</li><li>Define snap shot type as NSDiffableDataSourceSnapshot of type section as Int, and cell model as User.</li></ol><p>It’s important that data source type and snap shot type must match.</p><p>Then inside viewDidLoad() bellow where we call loadPost() Add this code:</p><pre>// 1<br>        let dataSource = DiffableDataSource(tableView: tableView) { (tableView, indexPath, user) -&gt; <em>UITableViewCell</em>? in<br>            // 2<br>            let cell = tableView.dequeueReusableCell(withIdentifier: &quot;FeedCell&quot;, for: indexPath) as! <em>FeedCell</em><br>            // 3<br>            cell.configure(with: user)<br>            // 4<br>            return cell<br>        }</pre><ol><li>Initial datasource by passing a table view and a closure.</li><li>Create cell by a native method dequeueReusableCell</li><li>Configure cell with a user</li><li>Return the cell.</li></ol><p>Straightforward so far, isn’t it ? We almost have everything we need, let’s try to run our application for the first time.<br>We see… nothing but an empty table view. What’s missing here ? If you notice we haven’t had something like reloadData() as we usually do in native way, right ?</p><p>But by using Combine we don’t use that way to refresh tableview, as I mention before posts is also a publisher and it’s responsible for listening changes itself, we will use that property to manipulate our tableview. Add this code inside viewDidLoad() and bellow where dataSource declared :</p><pre>// 1<br>        $users<br>            // 2<br>            .receive(on: <em>DispatchQueue</em>.main)<br>            // 3<br>            .sink {[weak self] (_) in<br>                // 4<br>                self?.applySnapshot(to: dataSource)<br>            }<br>            // 5<br>            .store(in: &amp;subscriptions)</pre><ol><li>Notice that we need to prefix $ sign in order to use users as a publisher not its value.</li><li>Use this operator in order to dispatch changes to main queue.</li><li>By calling sink we receive values when users changes. In this case, we update table view regardless changes.</li><li>This method will be define bellow.</li><li>Store this publisher to the subscriptions</li></ol><p>And then add this function bellow viewDidLoad() :</p><pre>private func applySnapshot(to dataSource: <em>DiffableDataSource</em>) {<br>        // 1<br>        var snapshot = Snapshot()<br>        // 2<br>        snapshot.appendSections([0])<br>        // 3<br>        snapshot.appendItems(users)<br>        // 4<br>        dataSource.apply(snapshot)<br>    }</pre><ol><li>Create a snapshot</li><li>Add sections to the snapshot. In this case we only have one section so we can simply append [0]</li><li>Append current state of users to the snapshot.</li><li>Apply the snapshot to the datasource</li></ol><p>DiffableDataSource use snapshot mechanism every time you apply a snapshot to the datasource it will compare the new to the old and change the tableview if needed.</p><p>Good job ! I think we got everything we need. Let’s run our application. Yes !! We finally see what we want 🥰. Try to run again but this time focus on how DiffableDataSource handle the fantastic animation for us. 🎇</p><p>You can download the final project here:</p><p><a href="https://github.com/LearnWithTung/DiffableCombine/tree/master/final">https://github.com/LearnWithTung/DiffableCombine/tree/master/final</a></p><h3>Conclusion</h3><p>In this post I showed you how to use DiffableDataSource and Combine together. I hope you got the concept, don’t forget to practice more I believe you’ll familiar it easily.</p><p>In part 2, I’ll show you how to custom a DiffableDataSource and interact with tableview such as swipe to delete.</p><p>If you have any questions please feel free to comment in the comment section or mail me. Don’t forget to share, claps for this post and visit my website to support me, thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=711555dc8734" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Compositional Layout in UICollectionView]]></title>
            <link>https://tungvuduc2805.medium.com/compositional-layout-in-uicollectionview-432f942249b6?source=rss-30f65d7d355a------2</link>
            <guid isPermaLink="false">https://medium.com/p/432f942249b6</guid>
            <category><![CDATA[uicollectionviewlayout]]></category>
            <category><![CDATA[uicollectionview]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Tung Vu Duc ]]></dc:creator>
            <pubDate>Sat, 15 Aug 2020 17:23:26 GMT</pubDate>
            <atom:updated>2020-09-25T10:02:05.097Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction to the new API.</h4><p>I had a lot of fun when explore the new API so I decided to make a post to share with you guys what I’ve learned. Let’s get started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N3ky0h9_rbfJLhaaPXXG4A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@yogendras31?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Yogendra Singh</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><blockquote>Updated:</blockquote><blockquote>I’ve created a instagram-like layout using Compositional Layout. You can check it out here:</blockquote><blockquote><a href="https://github.com/LearnWithTung/InstagramGridLayout">https://github.com/LearnWithTung/InstagramGridLayout</a></blockquote><h3>A boring introduction (but it’s worth to read)</h3><p>Compositional Layout has been introduced in WWDC 2019 event which contains a lot of power that helps developer build more complex collection layout but much less code.</p><p>On the one hand, if you just need a simple layout like a collection of identical items UICollectionViewFlowLayout is the best candidate for the job, it’s simple, it’s easy to implement. On the other hand, if you need more complex layout (I think most of the app nowadays), before Compositional Layouts you’ll need to create your own custom layout by subclass a bunch of classes, calculate rows, cells and stuff which is not easy to implement.</p><p>But Compositional Layout come to save. Now it becomes much easier to us to build whatever layout we wanted. Only thing I’m very sorry to say is <strong>it only support iOS 13.0 or above.</strong></p><p><strong>Advantages</strong>:</p><ul><li>Composable</li><li>Flexible</li><li>Fast</li></ul><h3>Disadvantages:</h3><ul><li>Only support iOS13.0 or above.</li></ul><p>Now let take a look under the hood to better understand how it works.</p><h3>Compositional Layouts: Under the Hood</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u5TBB2-8O7FcbNeMYliNog.png" /><figcaption>Hierarchy of a compositional layout</figcaption></figure><p>Compositional Layout compose small layout groups together as you can see in the photo above. A layout consists of sections. Each section consists of groups, every group consists of items .</p><h3>Core Concepts</h3><p>To build any compositional layout, the following four classes need to be implemented:</p><ul><li>NSCollectionLayoutSize — The width and height dimensions are of the type NSCollectionLayoutDimension which can be defined by setting the fractional width/height of the layout (percentage relative to its container), or by setting the absolute or estimated sizes.</li><li>NSCollectionLayoutItem — This is your layout’s cell that renders on the screen based on the size.</li><li>NSCollectionLayoutGroup — It holds the NSCollectionLayoutItem in either horizontal, vertical, or custom forms.</li><li>NSCollectionLayoutSection — This is used to initialize the section by passing along the NSCollectionLayoutGroup. Sections eventually compose the compositional layouts.</li></ul><p>Notice that all the classes above have prefix NS not UI. That’s because the new API is universal API which can be use not just on iOS but MacOS, WatchOS, iPadOS.</p><h3>Interesting Implementation Code</h3><h4>Horizontal paging layout</h4><p>Take a look at the snippet of code bellow :</p><pre><strong>init</strong>(){</pre><pre><strong>     let</strong> layout = UICollectionViewCompositionalLayout { (section, env) -&gt; NSCollectionLayoutSection? <strong>in</strong></pre><pre>         // 1</pre><pre><strong>         let</strong> item = NSCollectionLayoutItem(layoutSize:   .init(widthDimension: .fractionalWidth(1.0), heightDimension: .absolute(200)))</pre><pre>         // 2</pre><pre><strong>         let</strong> group = NSCollectionLayoutGroup.horizontal(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .absolute(200)), subitems: [item])</pre><pre>         // 3</pre><pre><strong>         let</strong> section = NSCollectionLayoutSection(group: group)</pre><pre><strong>         return</strong> section</pre><pre>    }</pre><pre><strong>    super</strong>.init(collectionViewLayout: layout) </pre><pre>}</pre><ul><li>1. Declare item with size.fractionalWidth(1.0) means items will take up full width of its container which is the group. absolute(200) means items are 200 point height.</li><li>2. The group will take up full width of the section and 200p height. It holds a list of items and because we want to build a horizontal list of item so we use horizontal class function.</li><li>3. Lastly, we initialize section contain the group created above.</li></ul><p>Just few lines of code. Everything seem correct but if you run your application, this is what we got:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*yDx5TrbUTU8CRd22mVhfjw.png" /></figure><p>It’s a bit hard to see, so add this line of code bellow the line we declare item</p><pre>item.contentInsets = .init(top: 10, leading: 10, bottom: 10, trailing: 10)</pre><p>Run your application again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*zJXZ3A4b4q7RO_V_Ud6Qhg.png" /></figure><p>Uhm… It layouts vertically instead of horizontally, why is that ? Behind the scene the section create 3 group instead of one. Each row you see on your screen is a group, and each group contains an item. That’s because section always try to keep items inside its frame by default. To tell section scroll horizontally we need to add this line of code bellow where you declare section:</p><pre>section.orthogonalScrollingBehavior = .continuous</pre><p>Run your application, now we got what we expected:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*hhLBnKC3jE_lDoRaK-IJCw.gif" /></figure><h3>Conclusion</h3><p>This article is a bit long so I decided to split it into multiple parts, we’ll build a really interesting layout in the next part. So if you want to get more about don’t forget to follow me 😉 (and sorry for my poor english).</p><p>Compositional Layout is a very powerful API. I’m very glad that it’s been released. Throughout this introduction article I hope you guys enjoy it and understand the basic concept of how Compositional Layout works. See you in the next part.</p><h4>Learn more &amp; References</h4><ul><li><a href="https://developer.apple.com/videos/play/wwdc2019/215">Advances in Collection View Layout - WWDC19 - Videos - Apple Developer</a></li><li><a href="https://medium.com/better-programming/ios-13-compositional-layouts-in-collectionview-90a574b410b8">iOS 13 Compositional Layouts in CollectionView</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=432f942249b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apply multiple MVCs pattern to solve dynamic cells Table View]]></title>
            <link>https://tungvuduc2805.medium.com/apply-multiple-mvcs-pattern-to-solve-dynamic-cells-table-view-b1441e73f08?source=rss-30f65d7d355a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1441e73f08</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[vietnamese]]></category>
            <category><![CDATA[mvc]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Tung Vu Duc ]]></dc:creator>
            <pubDate>Sun, 07 Jun 2020 07:56:30 GMT</pubDate>
            <atom:updated>2020-06-07T08:08:25.947Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hiiD6SkO3awzR522CW5ZCQ.jpeg" /></figure><p>Bên cạnh UICollectionView, UITableView có lẽ là loại View được các iOS Developers sử dụng nhiều nhất. UITableView giúp chúng ta dễ dàng xây dựng một giao diện dạng list, theo chiều dọc.</p><p>Ngoài những Table Views đơn giản chỉ có duy nhất một cell type, trên thực tế đi làm bạn sẽ gặp hầu hết là các Table Views phức tạp hiển thị nhiều loại thông tin khác nhau và đòi hỏi phải sử dụng nhiều cell types còn được gọi là dynamic cells table view.</p><p>Thành thật mà nói nếu làm theo cách “thông thường” (mình sẽ đề cập cách này ở phần tiếp theo) thì việc xây dựng một dynamic cells table view cũng không quá khó khăn. Nhưng trong bài viết này, hãy cùng mình tiến hoá từ “thông thường” thành “pro” để code clean hơn, dễ dàng mở rộng, thay đổi hơn.</p><p>Trước khi đi vào nội dung chính, mình muốn shout out tới <a href="https://medium.com/u/ef3a6091931a">Stan Ostrovskiy</a>, tác giả của bài viết dưới đây và chính bài viết đó cũng là cảm hứng để mình ngồi viết bài này, vì mình tin mình vẫn có thể làm tốt hơn cách mà anh ấy đã làm.</p><p><a href="https://medium.com/@stasost/ios-how-to-build-a-table-view-with-multiple-cell-types-2df91a206429">iOS: How to build a Table View with multiple cell types</a></p><p>Mình cùng sẽ mượn source code của bài viết đó như là starter-project để sử dụng và bắt đầu cải tiến từ đó. Các bạn có thể tải source code trong bài viết trên hoặc tải tại đây, mình đã update syntax cho Swift 5. OK chúng ta cùng bắt đầu.</p><p><a href="https://github.com/TungVuDuc2805/TableViewWithMultipleMVCs">TungVuDuc2805/TableViewWithMultipleMVCs</a></p><h3>Determine the problem</h3><p>Chạy starter-project, các bạn sẽ được một dynamic table view với năm sections: Main Info, About, Email, Attributes và Friends, mỗi section lại có các cells với layout khác nhau:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*KXkKs0XIn1ot3HyUfxmAoQ.png" /></figure><p>Cách “thông thường” mà mình nói tới ở phần đầu của bài viết chính là : xác định cell type dựa trên index của UITableView, sử dụng if-else khắp nơi</p><pre>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {   <br>   if indexPath.row == 0 {<br>        //cell.model = models[indexPath.row]</pre><pre>} else if indexPath.row == 1 {<br>        //cell.model = models[indexPath.row]<br>   }<br>   ...<br>}</pre><p>Nếu cần xử lý các sự kiện khác trong Table View, chúng ta lại phải phải thêm hàng loại câu lệnh if-else tương tự:</p><pre>override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {</pre><pre>   if indexPath.row == 0 {<br>        // event when tap on cell at indexPath = 0<br>   } else if indexPath.row == 1 {<br>        // event when tap on cell at indexPath = 0<br>   }<br>   ...</pre><pre>}</pre><p>Như mình cũng đã nói, cách này không khó làm nhưng vấn đề của nó, đầu tiên dễ nhận ra là sự lặp lại code, thứ hai quan trọng hơn là nó quá <strong>rigid</strong> và “dễ vỡ”, mọi thay dù nhỏ trên TableView đều khiến mình phải thay đổi rất nhiều trong codebase thậm chí là viết lại toàn bộ Controller, duới đây là một số trường hợp chứng minh :</p><ul><li>Nếu muốn thay đổi thứ tự của các cell =&gt; viết lại toàn bộ những đoạn if-else .</li><li>Nếu muốn chèn một cell vào vị trí bất kì trong Table View =&gt; viết lại toàn bộ những đoạn if-else .</li><li>Nếu muốn bỏ một cell nào đó =&gt; viết lại toàn bộ những đoạn if-else .</li></ul><p>Thêm nữa, việc check indexPath.row == 0 chẳng đưa cho người đọc một chút ngữ cảnh nào, mình tin rằng những người khác hay thậm chí chính cả bạn sau một vài tháng sau nhìn lại chắc chắn cũng sẽ bối rối khi đọc lại chính những đoạn code do mình viết ra. Trong bài viết của tác giả <a href="https://medium.com/u/ef3a6091931a">Stan Ostrovskiy</a> anh ấy đã sử dụng enum để cải thiện ngữ cảnh, nhưng vẫn chưa giải quyết được những vấn đề còn lại.</p><p>Mình thích gọi cách làm này là <strong>Do and Pray</strong>, <em>pray</em> rằng spec sẽ không thay đổi, <em>pray</em> rằng giao diện sẽ không đổi để bạn không phải viết lại toàn bộ logic, nhưng đáng tiếc điều đó là không thực tế vì <strong>phần mềm luôn thay đổi.</strong></p><p>Điểm tốt trong cách làm của <a href="https://medium.com/u/ef3a6091931a">Stan Ostrovskiy</a> là ViewController (Controller) rất clean (chỉ hơn 30 dòng code), nó chỉ chịu trách nhiệm configure UITableView, nhưng ProfileViewModel (data source) đang nhận quá nhiều responsibilities nên chúng ta sẽ chỉ cần tập trung improve ProfileViewModel .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*d28Fh-MnFCaCt7C-Zkzy0Q.png" /><figcaption>ProfileViewModel’s responsibilities</figcaption></figure><h3>Multiple Tiny MVCs</h3><p>Mở ProfileViewModel , trong method tableView(_ tableView:cellForRowAt indexPath) các bạn sẽ thấy các models (Model) đang được truyền thằng vào các cells (View) qua đó vi phạm mô hình <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">MVC</a>, mô hình MVC nói rằng Model và View không nên giao tiếp trực tiếp với nhau mà thông qua Controller. Vậy làm thế nào để giải quyết ?</p><p>Cách đầu tiên, các bạn có thể configure cell ngay trong hàm tableView(_ tableView:cellForRowAt indexPath) :</p><pre>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {   <br>   if indexPath.row == 0 {<br>        //cell.imageView.image = ...<br>        //cell.titleLabel.text = ...</pre><pre>} else if indexPath.row == 1 {<br>        //configure cell type 2<br>   }<br>   ...<br>}</pre><p>Cách này rất phổ biến, mình cũng thấy rất nhiều, nhưng nó không phù hợp với mục đích của chúng ta là giảm responsibilities của ProfileViewModel.</p><p>Cách thứ hai, bạn có thể sử dụng các mô hình khác như MVVM, MVP,… Các này hoàn toàn ổn và tốt hơn MVC, tuy nhiên trong bài viết này mình muốn giới thiệu tới các bạn một cách thứ ba, chúng ta vẫn sẽ sử dụng MVC 😉</p><p>Cách thứ ba, áp dụng mô hình multiple MVCs. Một trong những sự lầm tưởng mình thường thấy là các bạn nghĩ rằng một screen chỉ được chứa một MVC, nhưng thực sự không phải như vậy, ở đây để giải quyết việc couple giữa Model và View thì <strong>mỗi cell hoàn toàn có thể là một tiny MVC</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*7Vy75ogulDdiHlX9Z7dlXw.png" /><figcaption>tiny MVCs</figcaption></figure><h3>Implementation</h3><h4>Model</h4><p>Mình sửa lại các models như sau, đồng thời chuyển nó sang một file riêng (vì nó xứng đáng):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7781049040c870f3b9e996d15d8fc862/href">https://medium.com/media/7781049040c870f3b9e996d15d8fc862/href</a></iframe><h4>Controller</h4><p>Đầu tiên tạo một protocol tên ProfileCellProtocol như sau, mục đích để các Controllers conform theo:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e8d92f17aa368b6dcd3cf813089894e/href">https://medium.com/media/6e8d92f17aa368b6dcd3cf813089894e/href</a></iframe><p>Sau đó, mình implement các Cell Controllers như sau:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4440e3e6d229127b34285cc12c5557ce/href">https://medium.com/media/4440e3e6d229127b34285cc12c5557ce/href</a></iframe><p>Các bạn có thể thấy thay vì để DataSource, giờ đây mỗi Cell Controller sẽ chịu trách nhiệm tạo và configure cell bằng Model được truyền vào thông qua constructor injection.</p><p>Tiếp theo, vì chúng ta có năm sections nên mình tạo một ProfileSectionControllerProtocol và ProfileSectionController để chứa các Cell Controllers vừa tạo:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e4b58e6866154664c0d9f7697612525/href">https://medium.com/media/0e4b58e6866154664c0d9f7697612525/href</a></iframe><h4>Parsing Data</h4><p>Mình cũng muốn di chuyển phần parse dữ liệu ra khỏi ProfileViewModel vì đây rõ ràng không phải trách nhiệm của một Datasource:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73b2808a5a51c23326ed2c4c3a47ba18/href">https://medium.com/media/73b2808a5a51c23326ed2c4c3a47ba18/href</a></iframe><h4>Finally the ProfileViewModel</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07ef3912a1cb525b9fe750586237c0da/href">https://medium.com/media/07ef3912a1cb525b9fe750586237c0da/href</a></iframe><p>Chỉ 22 dòng code, rất gọn gàng phải không 🥳. Không còn Switch case, không còn if-else, tự do làm sao. Hãy cùng xem diagram dưới đây để xem chúng ta đã đạt được những gì:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DVPFGBt4FBaiC0GWW-Of4w.png" /></figure><p>Bằng cách chia sẻ responsibilities cho các component khác chúng ta đã tạo ra những component gọn gàng hơn, flexible hơn nhiều. Giờ đây, ProfileViewModel không còn cần phải quan tâm nó đang render cell gì, model là gì,… qua đó dễ dàng thêm Cell, xoá Cell, mà không ảnh hưởng gì tới ProfileViewModel .Chúng ta cũng đã giải quyết được vấn đề couple giữa View và Model.</p><h3>Conclusion</h3><p>Mặc dù bài viết của <a href="https://medium.com/u/ef3a6091931a">Stan Ostrovskiy</a> rất viral, rất nhiều claps nhưng không có nghĩa rằng chúng ta không có gì để cải tiến, ở bài viết này mình đã chứng minh điều đó.</p><p>Tổng kết lại, có 2 điểm mình muốn nhấn mạnh thông qua bài viết này:</p><ul><li>Đừng gắn với suy nghĩ rằng một screen chỉ có thể chứa một MVC, nó có thể chứa rất nhiều MVCs con.</li><li>Kể cả những bài viết rất viral trên mạng cũng không luôn luôn là silver bullet cho bạn, đừng chỉ copy and paste, hãy luôn cố gắng cải tiến nó.</li></ul><p>Các bạn có thể tải source code của bài viết tại đây:</p><p><a href="https://github.com/TungVuDuc2805/TableViewWithMultipleMVCs">TungVuDuc2805/TableViewWithMultipleMVCs</a></p><p>Và cuối cùng, nếu các bạn cảm thấy bài viết hữu ích đừng quên claps và follow mình. Cảm ơn các bạn đã đọc bài.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1441e73f08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Giới thiệu sách hay: Practical object-oriented design in ruby]]></title>
            <link>https://tungvuduc2805.medium.com/gi%E1%BB%9Bi-thi%E1%BB%87u-s%C3%A1ch-hay-practical-object-oriented-design-in-ruby-26e114c627d6?source=rss-30f65d7d355a------2</link>
            <guid isPermaLink="false">https://medium.com/p/26e114c627d6</guid>
            <category><![CDATA[vietnamese]]></category>
            <category><![CDATA[book-recommendations]]></category>
            <category><![CDATA[object-oriented-design]]></category>
            <dc:creator><![CDATA[Tung Vu Duc ]]></dc:creator>
            <pubDate>Fri, 22 May 2020 15:30:20 GMT</pubDate>
            <atom:updated>2020-05-22T15:30:20.826Z</atom:updated>
            <content:encoded><![CDATA[<h4>One of the best books I’ve read.</h4><p>Mình đã đọc cuốn sách này hai lần cách đây vài tháng, nảy ra ý tưởng viết review khi đang kẹt xe trên đường đi làm về, và khi đang viết bài này mình đọc lại nó một lần nữa. Qua mỗi lần đọc, mình lại hiểu rõ hơn những kiến thức mà tác giả trình bày và cũng ôn lại những thứ đôi khi quên mất.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*OibJyUek3OmrIEQDvL0Rvw.jpeg" /></figure><p><em>Practical Object-Oriented Design In Ruby</em> viết bởi tác giả <a href="https://www.sandimetz.com/"><em>Sandi Metz</em></a> đề cập tới tất cả những khái niệm cơ bản trong OO. Như cái tên đã bộc lộ, code mẫu trong sách được viết bằng Ruby, nhưng như chính tác giả cũng đã nói bạn không cần biết Ruby có thể đọc và hiểu. Với mình, đây là một cuốn sách không quá dày (~247 trang) nhưng vẫn đủ chi tiết để mang lại cho người đọc một cái nhìn về object-oriented design (OOD).</p><blockquote>“Every application is a collection of code; the code’s arrangement is the <em>design.</em>”</blockquote><p>Tác giả mở đầu chương một bằng cách đưa ra khái niệm và tầm quan trọng của design trong phầm mềm. Nếu bạn thắc mắc “<em>Tại sao lại cần design ? Tôi chẳng biết gì về design nhưng phần mềm tôi viết vẫn chạy bình thường</em>” thì chương này sẽ trả lời cho bạn.</p><p>Trong tám chương còn lại, thông qua một case study xuyên suốt Sandi Metz đi sâu vào các khái niệm như dependencies management, inheritance vs composition, LoD, Tell don&#39;t ask, testing…Với mỗi khái niệm cô đều phân tích và đưa ra ví dụ cụ thể, so sánh ưu-nhược của các giải pháp, đó cũng là điều khiến mình thích ở cuốn sách này.</p><h3>Conclusion</h3><p>Mình muốn giữ bài viết này ngắn thôi vì mình nghĩ các bạn tự đọc và cảm nhận thì tốt hơn (nên mình mới đặt tiêu đề là giới thiệu chứ không phải review 😂). Tuy nhiên, đây chắc chắn là một cuốn sách mà mình highly recommend các bạn nên đọc. <strong>So just go and give it a try !</strong></p><p>Nếu đọc sách cảm thấy hay đừng quên quay lại claps cho mình nhé. Trong tương lai mình sẽ tiếp tục giới thiệu các bạn những cuốn sách hay nữa nên tiện thì hãy ấn follow mình nhé.</p><h4>Find more about the author</h4><p><a href="https://www.sandimetz.com/">https://www.sandimetz.com/</a></p><h3>TL;DR (Viết chán; không đọc)</h3><ul><li>Nếu bạn không quan tâm tới chất lượng code, hay không có nhu cầu cải thiện. Bỏ qua cuốn sách này.</li><li>Đây là một cuốn sách hay, cô đọng về thiết kế phần mềm trong lập trình hướng đối tượng, mang đến cho bạn rất nhiều khái niệm sẽ giúp bạn cải thiện tư duy lập trình.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26e114c627d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to functional programming in Swift]]></title>
            <link>https://tungvuduc2805.medium.com/introduction-to-functional-programming-in-swift-bc1a1e390555?source=rss-30f65d7d355a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc1a1e390555</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[vietnamese]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Tung Vu Duc ]]></dc:creator>
            <pubDate>Sun, 17 May 2020 11:20:39 GMT</pubDate>
            <atom:updated>2020-05-17T11:39:57.895Z</atom:updated>
            <content:encoded><![CDATA[<h4>Map, flatMap, Reduce and Filter.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aW5-LWijUU38CfbvhogaLQ.jpeg" /><figcaption>photo taken by me ❤</figcaption></figure><p>Hôm trước mình được đề nghị tìm một số bài viết về functional programming cho các anh em dev đọc vì khách hàng đang muốn áp dụng nó vào trong dự án của họ tuy nhiên nhiều anh em chưa biết hoặc hiểu nhiều về cách sử dụng. Uhm… Mình nghĩ tại sao không viết một bài, dù sao mình cũng đã sử dụng functional programming khá lâu rồi và cảm thấy chúng rất hay và hữu dụng.</p><p>Trong bài viết này mình sẽ đề cập và đưa ra ví dụ bốn hàm mình hay sử dụng nhất: Filter, Map, Reduce, compactMap. OK, let&#39;s get it 🔥.</p><h3>Skip the definition</h3><p>Mình xin phép được bỏ qua định nghĩa functional programming là gì ? Các bạn có thể đọc nó ở <a href="https://topdev.vn/blog/functional-programming-la-gi/">đây</a>. Tuy nhiên, có vài ưu điểm khi sử dụng functional programming mình muốn nêu ra ở đây:</p><ul><li>Functional programming giúp code nhanh hơn, gọn hơn, nguy hiểm hơn.</li><li>Functional programming giúp code an toàn hơn vì tất cả những gì bạn cần làm với functional programming là đưa cho nó input và nhận về output.</li></ul><h3>Map</h3><p>Hàm này được sử dụng để biến đổi từng phần tử trong một mảng sang kiểu mà bạn muốn.</p><blockquote>Input: an array <br>Output: an array</blockquote><h4>Problem</h4><p>Bạn có một mảng FeedItem như sau, giờ bạn muốn lấy tất cả các thumbnailURL từ mảng đó.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/526c66a50a1fc8cc45a9b4620724d7ef/href">https://medium.com/media/526c66a50a1fc8cc45a9b4620724d7ef/href</a></iframe><p><strong>Imperative Approach</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee8c97fe6425c16f2ebd36704ef98a60/href">https://medium.com/media/ee8c97fe6425c16f2ebd36704ef98a60/href</a></iframe><p><strong>Functional Approach</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7264539934a00cc116dd78697c8cf96/href">https://medium.com/media/a7264539934a00cc116dd78697c8cf96/href</a></iframe><p>Muốn ngắn hơn nữa ? No problem :)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc22d8f375a72ab911f09e863f2ca127/href">https://medium.com/media/fc22d8f375a72ab911f09e863f2ca127/href</a></iframe><p>Nếu bạn để ý kỹ sẽ thấy ở Functional Approach là let urls có nghĩa rằng nó an toàn hơn so với Imperative Approach<strong> </strong>bạn cần khai báo var urls vì bạn có thể chắc chắn rằng mảng urls sẽ không thể bị thay đổi… nhưng nếu bạn muốn thay đổi ? vậy bạn cũng hoàn toàn có thể khai báo var thay cho let.</p><blockquote>Độ phức tạp: O(n) trong đó n là số phần tử của mảng đầu vào .</blockquote><h3>compactMap</h3><p>Tương tự như Map nhưng compactMap thường được sử dụng để loại bỏ các giá trị optional</p><blockquote>Input: an array <br>Output: an array</blockquote><h4>Problem</h4><p>Cũng có một mảng FeedItem nhưng lần này thumbnailURL là biến optional, bạn muốn lấy tất cả các thumbnailURL từ mảng đó.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc74fa5729b3733d1fae4a97edf6f0e8/href">https://medium.com/media/fc74fa5729b3733d1fae4a97edf6f0e8/href</a></iframe><p><strong>Imperative Approach</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6ab0a34a55639ea657294b3f4ebf860/href">https://medium.com/media/a6ab0a34a55639ea657294b3f4ebf860/href</a></iframe><p><strong>Functional Approach</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e79bb4ef797e3ec38474c1834c977410/href">https://medium.com/media/e79bb4ef797e3ec38474c1834c977410/href</a></iframe><p>Hoặc:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e1b1b3b2d8306cb302f633af68f8cfa/href">https://medium.com/media/4e1b1b3b2d8306cb302f633af68f8cfa/href</a></iframe><p>Behind the scene, compactMap thực hiện 2 vòng loop, vòng đầu tiền giống hệt với Map — biến đổi từng phần tử trong mảng sang kiểu mong muốn. Vòng loop thứ hai, nó loại bỏ tất cả các giá trị nil.</p><blockquote>Độ phức tạp: O(m + n). Trong đó n là số phần từ của mảng input, m là số phần tử của mảng trước khi loại bỏ các item giá trị nil.</blockquote><h3>Filter</h3><blockquote>Input: an array <br>Output: an array</blockquote><h4>Problem</h4><p>Giả sử FeedItem có thêm thuộc tính isFavorite và bạn muốn lấy ra tất cả các items có giá trị isFavorite = true</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1d511901cf03e4c9e1fb63f6b535974/href">https://medium.com/media/e1d511901cf03e4c9e1fb63f6b535974/href</a></iframe><p><strong>Imperative Approach</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc1baef131bec34c9c0789d1495ece98/href">https://medium.com/media/dc1baef131bec34c9c0789d1495ece98/href</a></iframe><p><strong>Functional Approach</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5a3d7d654ad41023ec8caa77677d973/href">https://medium.com/media/c5a3d7d654ad41023ec8caa77677d973/href</a></iframe><p>Ngắn hơn:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6eec81b1d08233a9690ae5e00406c159/href">https://medium.com/media/6eec81b1d08233a9690ae5e00406c159/href</a></iframe><blockquote>Độ phức tạp: O(<em>n</em>). Trong đó n là số phần tử trong mảng đầu vào.</blockquote><h3>Reduce</h3><p>Hàm này trả về kết quả sau khi kết hợp các phần tử trong một mảng thành một giá trị duy nhất.</p><blockquote>Input: an array <br>Output: a single value</blockquote><h4>Problem</h4><p>Tiếp tục phát triển FeedItem, thêm thuộc tính numberOfLike , giờ bạn muốn lấy được tổng số lượt thích từ mảng</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1c36792d70f6bf04a3de857ceac2e08/href">https://medium.com/media/e1c36792d70f6bf04a3de857ceac2e08/href</a></iframe><p><strong>Imperative Approach</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a28ddec0c825ae169883f0d31e2c7a2/href">https://medium.com/media/4a28ddec0c825ae169883f0d31e2c7a2/href</a></iframe><p><strong>Functional Approach</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d0f8179b28e92b84bfa1ceb7b5f4276/href">https://medium.com/media/6d0f8179b28e92b84bfa1ceb7b5f4276/href</a></iframe><p>Áp dụng shorthand syntax:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/420bf2df80e45fcc569f4832fb98afb5/href">https://medium.com/media/420bf2df80e45fcc569f4832fb98afb5/href</a></iframe><p>Có thể thấy reduce nhận vào tham số là một giá trị hằng (0 trong ví dụ trên). Tham số này có ý nghĩa là giá trị khởi. Nếu ở ví dụ trên mình đặt giá trị ban đầu đó bằng 10, kết quả sẽ là 70 thay vì 60.</p><blockquote>Độ phức tạp: O(<em>n</em>). Trong đó n là số phần tử của mảng đầu vào.</blockquote><h3>Conclusion</h3><p>Với mình việc hiểu và sử dụng functional programming là một kỹ năng quan trọng cần phải có đặc biệt là những hàm cơ bản, bên cạnh đó mình nghĩ nó cũng không quá khó để học và áp dụng.</p><p>Vậy là chúng ta đã cùng tìm hiểu xong về bốn hàm mình thường sử dụng nhất trong công việc, ngoài ra còn rất nhiều hàm khác như: sorted, dropFirst, dropLast,… các bạn có thể tự tìm hiểu thêm nhé.</p><p>Cảm ơn các bạn đã đọc bài, đừng quên claps và chia sẻ nếu thấy bài viết hữu ích, nếu có câu hỏi hãy để lại ở phần comment ❤️.</p><blockquote>Tham khảo:</blockquote><blockquote><a href="https://developer.apple.com/">https://developer.apple.com/</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc1a1e390555" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Strategy Design Pattern - 21 Guns]]></title>
            <link>https://tungvuduc2805.medium.com/strategy-design-pattern-21-guns-4bf776af3daf?source=rss-30f65d7d355a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bf776af3daf</guid>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[design-pattern-ios]]></category>
            <category><![CDATA[vietnamese]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[strategy-design-pattern]]></category>
            <dc:creator><![CDATA[Tung Vu Duc ]]></dc:creator>
            <pubDate>Tue, 05 May 2020 03:28:18 GMT</pubDate>
            <atom:updated>2020-05-11T07:36:40.324Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ctCd0hVznerVut8dusYXmg.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@derwin-edwards-939973?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Derwin Edwards</a> from <a href="https://www.pexels.com/photo/semi-automatic-pistol-4204234/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>Dạo gần đây mình hay nghe lại các bài hát us-uk ngày xưa, nghe đến 21 Guns — Green day thì tự nhiên muốn viết về Strategy pattern, tất nhiên nội dung bài hát thì không gì đến liên quan Strategy rồi, chỉ là cái tên làm mình liên tưởng tới thôi 😆. Dù sao thì đây cũng là một pattern rất hay, trong bài viết này hãy cùng mình tìm hiểu về nó nhé.</p><h3>Definition</h3><blockquote>Strategy design pattern thuộc nhóm behavioral. Strategy design pattern định nghĩa một nhóm các thuật toán, đóng gói từng thuật toán, và chúng có thể thay thế cho nhau một cách dễ dàng. Strategy cũng giúp các thuật toán này độc lập với client sử dụng.</blockquote><p>Pattern này làm mình liên tưởng tới mấy game bắn súng mà hồi còn ăn ngủ cùng game mình từng chơi như Counter Strike, Call of duty,… Khi bạn có thể mang cùng một lúc nhiều vũ khí khác nhau nhưng chỉ có thể sử dụng một vũ khí ở một thời điểm và có thể thay đổi lên tục trong suốt ván game tuỳ vào tình hình. Ôi nói tới lại ngứa tay quá, chắc viết xong bài này phải làm vài game mới được 😆… Hơi lạc đề chút xíu nhưng bạn hoàn toàn có thể hiểu Strategy theo cách đó.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FLPNe9AUeMr6nyflQnG%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FLPNe9AUeMr6nyflQnG%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FLPNe9AUeMr6nyflQnG%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="184" frameborder="0" scrolling="no"><a href="https://medium.com/media/485aaeb936b22e09ba0fd6d0ab0e7e2d/href">https://medium.com/media/485aaeb936b22e09ba0fd6d0ab0e7e2d/href</a></iframe><h3>Structure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*3Gm2HBw2uZx1sXHl4b2Emg.png" /></figure><p>Có thể thấy các thuật toán (ConcreteStrategyA và ConcreteStrategyB) cùng chia sẻ chung một Interface. Từ góc nhìn của client, nó không quan tâm và cũng không biết cụ thể thuật toán được sử dụng là gì, client chỉ giao tiếp với Interface, việc quyết định sử dụng thuật toán nào sẽ do một component khác lo.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c87b6a371ae1b5907898adfcbf754314/href">https://medium.com/media/c87b6a371ae1b5907898adfcbf754314/href</a></iframe><h3>Case study</h3><h4>Requirement</h4><p>Ứng dụng của bạn cần load một list bài viết từ API server, để tăng performance cho ứng dụng cũng như tiết kiệm dung lượng cho người dùng , bạn sẽ load list bài viết này từ các nguồn khác nhau tuỳ vào từng trường hợp:</p><ul><li>Nếu người dùng sử dụng Wifi API <em>http://api.com/wifi/posts sẽ trả về 20 bài viết trên mỗi lần request.</em></li><li>Nếu người dùng sử dụng 3G API <em>http://api.com/c</em>ellular<em>/posts sẽ trả về 10 bài viết trên mỗi lần request</em></li><li>Nếu người dùng sử dụng không có kết nối internet sẽ lấy bài viết từ local</li></ul><h4>Define algorithms</h4><pre>protocol Loader {<br> func load(url: URL, completion: <a href="http://twitter.com/escaping">@escaping</a> (Result&lt;[FeedItem],     Error&gt;) -&gt; Void)<br>}</pre><pre>class WifiLoader: Loader {<br>    private let url: URL<br>    init(url: URL){<br>       self.url = url<br>    }</pre><pre>     func load(completion: <a href="http://twitter.com/escaping">@escaping</a> (Result&lt;[FeedItem], Error&gt;) -&gt;     Void) {<br>        …<br>      }<br>}</pre><pre>class CellularLoader: Loader {<br>    private let url: URL<br>    init(url: URL){<br>     self.url = url<br>    }</pre><pre>    func load(completion: <a href="http://twitter.com/escaping">@escaping</a> (Result&lt;[FeedItem], Error&gt;) -&gt; Void) {<br>     …<br>   }<br>}</pre><pre>class LocalLoader: Loader {<br>     func load(completion: <a href="http://twitter.com/escaping">@escaping</a> (Result&lt;[FeedItem], Error&gt;) -&gt; Void) {<br>     …<br>  }<br>}</pre><h4>Usage</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32ac3976d7b826aa7e5aea7856af60c0/href">https://medium.com/media/32ac3976d7b826aa7e5aea7856af60c0/href</a></iframe><p>Không hề khó đúng không 🥳. Thuật toán cụ thể sẽ được truyền vào tuỳ theo kết nối internet của người dùng bằng cách sử dụng <a href="https://medium.com/@tungvuduc2805/dependency-injection-explained-n%C6%A1i-t%C3%ACnh-y%C3%AAu-b%E1%BA%AFt-%C4%91%E1%BA%A7u-4efe3c968223">constructor injection</a>. Tuy nhiên, một vấn đề với cách làm này là thuật toán sẽ không thể thay đổi ở <em>runtime</em>. Ví dụ, ban đầu người dùng không có kết nối internet, ta sẽ load bài viết từ local, tuy nhiên sau đó người dùng có kết nối internet trở lại, ta sẽ muốn các bài viết được lấy từ Wifi hoặc Cellular, nhưng với cách làm như trên thì không thể được. Hmm… <em>Làm thế nào nhỉ</em> ?</p><p>Ta có thể kết hợp sử dụng Composite pattern cùng với Strategy để giải quyết vấn đề trên một cách dễ dàng. Mình cũng đã có một bài viết về Composite, các bạn có thể tham khảo thêm ở đây:</p><p><a href="https://medium.com/@tungvuduc2805/design-pattern-y%C3%AAu-th%C3%ADch-c%E1%BB%A7a-m%C3%ACnh-composite-637620cb2fa4">Design pattern yêu thích của mình: Composite</a></p><h3>Change algorithms in runtime</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fa661f85ce4c1b1748ab58bacf9a840/href">https://medium.com/media/8fa661f85ce4c1b1748ab58bacf9a840/href</a></iframe><h4>Usage</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/032c143b390a22adbbb84853df822c8d/href">https://medium.com/media/032c143b390a22adbbb84853df822c8d/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FXR9Dp54ZC4dji%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FXR9Dp54ZC4dji%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FXR9Dp54ZC4dji%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="261" frameborder="0" scrolling="no"><a href="https://medium.com/media/555aa009f0f2a80ceb08a30b0ca0029d/href">https://medium.com/media/555aa009f0f2a80ceb08a30b0ca0029d/href</a></iframe><h3>Conclusion</h3><p>Vậy là chúng ta đã cùng tìm hiểu xong về Strategy rồi đấy 🥳. Mình thấy đây là một design pattern rất hay và được áp dụng cũng khá nhiều trong các dự án, hy vọng các bạn đã hiểu hơn về nó qua bài viết của mình. Hãy học và áp dụng vào công việc hàng ngày nhé.</p><p>Nếu cảm thấy bài viết có ích, đừng quên claps và ấn follow để xem được những bài viết mới của mình. Nếu có câu hỏi hoặc bất cứ đóng góp ý kiến gì hãy để lại ở phần comment, cảm ơn các bạn 🥰.</p><p><em>Tài liệu tham khảo:<br>- </em>Design Patterns: Elements of Reusable Object-Oriented Software (Gang of four)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bf776af3daf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency Injection Explained:  nơi tình yêu bắt đầu…]]></title>
            <link>https://tungvuduc2805.medium.com/dependency-injection-explained-n%C6%A1i-t%C3%ACnh-y%C3%AAu-b%E1%BA%AFt-%C4%91%E1%BA%A7u-4efe3c968223?source=rss-30f65d7d355a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4efe3c968223</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[vietnamese]]></category>
            <category><![CDATA[ios-development]]></category>
            <dc:creator><![CDATA[Tung Vu Duc ]]></dc:creator>
            <pubDate>Mon, 27 Apr 2020 07:13:11 GMT</pubDate>
            <atom:updated>2020-05-05T15:04:10.359Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dependency Injection Explained: Nơi tình yêu bắt đầu…</h3><h4>Phần hai: Dependency không ăn được. Vậy dependency injection thì sao ?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q-rj6HsZRmdXzmQqmja0GQ.jpeg" /><figcaption>source: của một bạn trên fan page của DSK</figcaption></figure><blockquote>Updated: Video cho bài viết này. Các bạn có thể xem ở đây, tuy nhiên đọc bài viết sẽ chi tiết hơn nhé:</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F78-8Jtd3vEo%3Fstart%3D3%26feature%3Doembed%26start%3D3&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D78-8Jtd3vEo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F78-8Jtd3vEo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d5329cb23192f23862f753780d9fffd/href">https://medium.com/media/6d5329cb23192f23862f753780d9fffd/href</a></iframe><p>Ở phần một chúng ta đã cùng tìm hiểu về Dependency. Nếu các bạn chưa đọc thì mình sẽ để link ở đây, hãy đọc nó trước khi tiếp tục bài viết này nhé.</p><p><a href="https://medium.com/@tungvuduc2805/dependency-injection-explained-dependency-2aa411a5258a">Dependency Injection Explained: Dependency</a></p><p>Trong phần này chúng ta sẽ tìm hiểu về dependency injection. Một nhóm các nguyên tắc cơ bản và quan trọng nhất để viết được một phần mềm tốt.</p><blockquote>Một phần mềm tốt cho phép các developers làm việc độc lập, dễ dàng bảo trì, thêm, sửa hay thậm chí xoá chức năng, dễ dàng test và debug, có khả năng tái sử dụng các components…</blockquote><p>Khi đọc bài viết này bạn có thể sẽ cảm thấy hoá ra trước giờ mình đã áp dụng dependency injection rồi mà không nhận ra, có thể do từng thấy một ông senior ở công ty sử dụng nên bắt trước, hoặc đâu đó ở trên mạng… Còn nếu chưa từng sử dụng thì cũng không sao cả, bạn hoàn toàn có thể áp dụng nó sau khi đọc bài viết này vì nó không có gì khó cả đâu 😊.</p><h3>Definition</h3><blockquote>Dependency injection là tập hợp một nhóm các patterns giúp bạn quản lý các dependencies bằng cách truyền dependencies một cách “công khai&quot; (explicitly )</blockquote><p>Nếu như trong phần một của bài viết, mình đã giới thiệu cho các bạn hai loại dependency là implicit dependency và explicit dependency thì từ định nghĩa các bạn có thể hiểu, Dependency injection là tập hợp một nhóm các patterns giúp bạn tạo ra các <strong>explicit dependencies</strong>. Đó là lý do vì sao mình nói ở bài viết trước rằng một khi bạn hiểu về dependency thì việc hiểu về dependency injection sẽ trở nên vô cùng dễ dàng 😇.</p><p>OK, vậy <em>“nhóm các patterns”</em> mà trong định nghĩa nhắc tới là những patterns nào ?</p><h3>Three types of dependency injection</h3><h4>Constructor injection</h4><blockquote>Là khi bạn truyền các dependencies thông qua hàm khởi tạo của component phụ thuộc.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f54127bf0958cf5c2f8f41c1e1134f0/href">https://medium.com/media/2f54127bf0958cf5c2f8f41c1e1134f0/href</a></iframe><p>Như các bạn có thể thấy ở ví dụ trên, <em>ListMovieViewModel</em> là dependency và được truyền vào thông qua hàm khởi tạo của <em>ListMovieController</em> và chính do vậy <em>ListMovieController</em> không thể được khởi tạo nếu thiếu <em>ListMovieViewModel.</em></p><p>Khi sử dụng Constructor injection, bạn đang nói rằng: “<em>Hey, nếu mày muốn tạo ra class A, mày cần truyền cho nó dependencies X, Y, Z…</em>”</p><h4>When to use constructor injection</h4><p>Một điều đơn giản: hãy sử dụng constructor injection bất cứ khi nào có thể và xem nó là pattern mặc định của dependency injection, nhất là khi các dependencies bạn truyền trong hàm khởi tạo sẽ được lưu trữ và sử dụng xuyên suốt phục vụ cho component phụ thuộc.</p><h4>Property injection</h4><blockquote>Là khi bạn truyền các dependencies sau khi object được khởi tạo thông qua các properties của object đó.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8591b8f02a145aa3c4fac5a7e3f72ee8/href">https://medium.com/media/8591b8f02a145aa3c4fac5a7e3f72ee8/href</a></iframe><h4>When to use property injection</h4><p>Bạn chỉ nên sử dụng property injection khi dependency có một <strong>giá trị mặc định đủ tốt</strong>, trong hầu hết trường hợp sử dụng bạn sẽ sử dụng giá trị mặc định đó, tuy nhiên property injection giúp bạn có thể thay đổi giá trị mặc định đó nếu bạn muốn.<br>Như ở ví dụ trên, khi sử dụng bình thường mình sẽ sử dụng giá trị mặc định của <em>session</em> và có thể chỉ thay nó bằng một <em>mock session</em> khi viết unit test.</p><h4>Method injection</h4><blockquote>Là khi bạn truyền các dependencies sau khi object được khởi tạo thông qua các phương thức của object đó.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47f48f189e862f98508eae4d2aa62c1d/href">https://medium.com/media/47f48f189e862f98508eae4d2aa62c1d/href</a></iframe><h4>When to use method injection</h4><p>Bạn sử dụng method injection khi các dependencies <strong>thay đổi</strong> ở mỗi lần gọi method. Xem xét ví dụ ở trên, mỗi lần mình gọi hàm <em>load(url:completion:)</em> mình sẽ muốn truyền cho nó một url khác, nếu url không đổi bạn nên sử dụng constructor injection. <br>Một lưu ý khi sử dụng method injection là dependency trong method injection không nên được lưu lại trong object để sử dụng cho các method khác, nếu bạn cần lưu trữ dependency, một lần nữa, hãy sử dụng constructor injection.</p><h3>Why dependency injection ?</h3><p>Có một điều dễ nhận thấy là các patterns trong dependency injection luôn truyền các dependencies cho component phụ thuộc bằng một cách nào đó từ bên ngoài vào chứ không khởi tạo dependencies bên trong component phụ thuộc. Điều này có ý nghĩa gì không ?</p><p>Có ! Một số lợi điểm trong quá trình học hỏi và áp dụng dependency injection mình muốn kể ra ở đây:</p><ul><li>Dependency injection hướng tới sự rõ ràng trong cách sử dụng dependency. Khi khởi tạo ViewControllerB ta biết rằng ta cần truyền cho nó dependency gì để nó có thể hoạt động.</li><li>Dependency injection cho phép bạn test các components một cách độc lập. Nó cho phép ta dễ dàng thay thế dependency bằng một mock object trong test mà không cần thay đổi code ở production.</li><li>Dependency injection giúp tăng khả năng maintain và tính mở rộng. Chính việc cho phép thao tác với dependency từ bên ngoài giúp ta có thể truyền các dependency khác nhau để tăng tính mở rộng mà không làm ảnh hưởng tới component phụ thuộc.</li></ul><h3>Dependency Injection (DI) vs. Dependency Inversion Principle (DIP)</h3><p>Cho bạn nào chưa biết thì dependency inversion principle là nguyên tắc cuối trong năm nguyên tắc lập trình <strong>SOLID</strong>.</p><p>Để so sánh hai khái niệm này thì nếu xem DIP là lý thuyết thì DI là thực hành. Nếu ví DIP giống như cái đích, cái mục tiêu mà chúng ta muốn đạt được, thì DI thì giống như một con đường để đi đến cái đích đó.</p><h3>Conclusion</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F26u4lOMA8JKSnL9Uk%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F26u4lOMA8JKSnL9Uk%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExc3Bxam9kNWk1bWxtcmVyeDV3bDZnZHF4NWVzdnJ0cjY2emJiM3RmYSZlcD12MV9naWZzX2dpZklkJmN0PWc%2F26u4lOMA8JKSnL9Uk%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="322" frameborder="0" scrolling="no"><a href="https://medium.com/media/22b4719199411629c39e1ff30ae52b20/href">https://medium.com/media/22b4719199411629c39e1ff30ae52b20/href</a></iframe><p>Phù… Vậy là chúng ta đã cùng tìm hiểu xong về dependency injection. Tất nhiên, sức mạnh của dependency injection không chỉ có thế, những gì mình viết trong bài đều chỉ là những kiến thức cơ bản, các bạn có thể đọc và tìm hiểu thêm về nó nhé.</p><p>Hy vọng các bạn đã học thêm được một chút qua bài viết của mình. Cảm ơn các bạn đã đọc đến đây. Nếu thấy bài viết hữu ích, đừng quên share và claps để ủng hộ mình. Nếu có góp ý, câu hỏi thì hãy để lại ở phần bình luận mình sẽ trả lời nhé. Love you all 😘.</p><p><em>Tham khảo:</em></p><ol><li><em>Dependency Injection Principles, Practices, and Patterns — Mark Seemann &amp; Steven van Deursen.</em></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4efe3c968223" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency Injection Explained: Dependency]]></title>
            <link>https://tungvuduc2805.medium.com/dependency-injection-explained-dependency-2aa411a5258a?source=rss-30f65d7d355a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2aa411a5258a</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[dependencies]]></category>
            <category><![CDATA[ios-development]]></category>
            <dc:creator><![CDATA[Tung Vu Duc ]]></dc:creator>
            <pubDate>Fri, 24 Apr 2020 03:30:52 GMT</pubDate>
            <atom:updated>2020-05-05T15:02:57.621Z</atom:updated>
            <content:encoded><![CDATA[<h4>Phần 1: Dependency là gì ? có ăn được không ?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xv0VQjTMmI3Jp-Z3gqZsUQ.jpeg" /><figcaption>source: photo by pixabay on pexels.com</figcaption></figure><blockquote>Updated: Video cho bài viết này. Các bạn có thể xem tại đây:</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FRo5xquSenjY%3Fstart%3D32%26feature%3Doembed%26start%3D32&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DRo5xquSenjY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FRo5xquSenjY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f743827eebd02dff16e246a195c8e7e/href">https://medium.com/media/6f743827eebd02dff16e246a195c8e7e/href</a></iframe><p>Trước khi đi vào tìm hiểu về dependency injection, ở trong bài viết này mình muốn cùng các bạn tìm hiểu về khái niệm dependency trước. Một khi đã hiểu rõ về dependency thì việc hiểu về dependency injection sẽ trở nên vô cùng dễ dàng thôi.</p><h3>Aware of communication</h3><p>Không giống như anh chàng John Wick trong bộ phim cùng tên một mình san bằng tất cả, đạn bắn bao nhiêu cũng không chết nổi. Trong một ứng dụng (hay một phần mềm nói chung) các modules, các classes, các hàm giao tiếp với nhau để hoạt động. Lý tưởng là khi mỗi component đó <a href="https://en.wikipedia.org/wiki/Single-responsibility_principle">thực hiện và thực hiện tốt duy nhất một nhiệm vụ mà nó được giao phó</a>, rồi kết hợp hay giao tiếp để thực hiện một chức năng nào đó trong requirement.</p><p>Ngày trước mình không hề có ý niệm gì về khái niệm giao tiếp giữa các components với nhau, mình từng nhét mọi thứ vào chung một class khiến cho class đó dài cả ngàn dòng, đoạn code này dính vào đoạn code kia, không thể nào refactor nổi. Hậu quả thì khỏi phải nói, maintain nó khó như chạy trốn John Wick sau khi giết chó của ổng vậy 😰.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FSUBxai0moNW7K%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FSUBxai0moNW7K%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FSUBxai0moNW7K%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="292" frameborder="0" scrolling="no"><a href="https://medium.com/media/b74129b5968913586b01e2c06e9a90c4/href">https://medium.com/media/b74129b5968913586b01e2c06e9a90c4/href</a></iframe><p>Khi các components giao tiếp với nhau chúng tạo ra một khái niệm gọi là dependency.</p><h3>Definition</h3><blockquote>Về cơ bản khi bạn có component A sử dụng component B thì ta nói, component A phụ thuộc (depends) vào component B hay component B là một <strong><em>dependency</em></strong> của component A.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*G5SYtITdn9g85it_vDCWdw.png" /></figure><p><em>“Đơn giản vậy thôi hở ?“</em> — Chuẩn ! chỉ đơn giản như vậy thôi đấy 😆.<br>Component ở đây có thể là một class, một struct hay nói rộng ra thì có thể là một framework, một module…</p><h3>Types of dependency</h3><h4>Implicit Dependency</h4><p>Cái tên cũng đã phần nào thể hiện ý nghĩa của nó. Implicit dependency là kiểu dependency mà khi nhìn vào interface của component phụ thuộc ta không thể thấy được nó. Cùng xem xét ví dụ sau đây:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/813aa3a3add009e618743e8cfd5774f3/href">https://medium.com/media/813aa3a3add009e618743e8cfd5774f3/href</a></iframe><p>Trong ví dụ trên, <em>FeedViewModel</em> là một dependency của <em>FeedViewController</em>, tuy nhiên do được khởi tạo bên trong component phụ thuộc ta không thể thấy <em>FeedViewModel</em> khi nhìn vào interface của <em>FeedViewController</em> mà phải nhìn vào implement của class này.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LeJ36sc_0KIqMeNj7SimgA.png" /><figcaption>interface of FeedViewController</figcaption></figure><h4>Explicit Dependency</h4><p>Ngược lại với implicit dependency, khi nhìn vào interface của component phụ thuộc ta có thể thấy được nó đang có những dependencies nào. Mình sẽ sửa ví dụ ở trên để hô biến implicit thành explicit:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00a02d7fa2f0c331c6df799b5fed568b/href">https://medium.com/media/00a02d7fa2f0c331c6df799b5fed568b/href</a></iframe><p>Và đây là interface của <em>FeedViewController</em> 😊</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lf8P4MkbXEq5-rkKpPQXKA.png" /><figcaption>interface of FeedViewController</figcaption></figure><h3>Meaning of dependency</h3><p><em>Khi ta nói A phụ thuộc vào B hay B là một dependency của A, thì điều đó có ý nghĩa là gì ?</em></p><p>Uhm… nó có nghĩa rằng A không thể hoạt động mà thiếu B. Như các ví dụ ở trên, nếu mình comment out <em>FeedViewModel</em> class thì compiler sẽ báo lỗi ngay</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MwmDXiryi_ihxPuJ5ktB7Q.png" /></figure><p><em>Còn thằng B thì sao ? </em>Chẳng sao cả, do B không phụ thuộc vào A nên B vẫn có thể hoạt động cho dù có tồn tại A hay không.</p><h3>Conclusion</h3><p>Vậy là mình đã cùng các bạn tìm hiểu xong về khái niệm dependency và hai loại dependency, hy vọng qua bài viết này các bạn đã hiểu rõ về nó. Trong phần sau chúng ta sẽ tiếp tục đi vào Dependency Injection để xem nó có gì hay ho nha.</p><p>Cảm ơn các bạn đã đọc 🥰. Đừng quên claps thẳng vào mặt mình và ấn follow để theo dõi các bài viết tiếp theo nhé. Nếu có câu hỏi hoặc bình luận liên quan đến bài viết, hãy để lại comment ở phía dưới, mình sẽ cố gắng trả lời.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2aa411a5258a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design pattern yêu thích của mình: Composite]]></title>
            <link>https://tungvuduc2805.medium.com/design-pattern-y%C3%AAu-th%C3%ADch-c%E1%BB%A7a-m%C3%ACnh-composite-637620cb2fa4?source=rss-30f65d7d355a------2</link>
            <guid isPermaLink="false">https://medium.com/p/637620cb2fa4</guid>
            <category><![CDATA[design-pattern-ios]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[composite-design-pattern]]></category>
            <dc:creator><![CDATA[Tung Vu Duc ]]></dc:creator>
            <pubDate>Wed, 22 Apr 2020 17:39:55 GMT</pubDate>
            <atom:updated>2020-04-23T05:53:36.643Z</atom:updated>
            <content:encoded><![CDATA[<p>Trong bài viết này mình sẽ cùng các bạn tìm hiểu về Composite design pattern và một case study mình từng gặp trong thực tế nha.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zp4_uE5FwvG-LnXgUkYzxw.jpeg" /><figcaption>source: pexels.com</figcaption></figure><p>Là một design pattern thuộc “họ” structural, cũng như những patterns khác cùng “họ” Composite pattern giúp cho lập trình viên mở rộng tính năng của phần mềm mà không cần đụng đến một dòng code nào ở phía client, hay nói cách khác, nó giúp chúng ta thoả mãn <a href="https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle"><strong>open-closed principle</strong></a> trong <a href="https://en.wikipedia.org/wiki/SOLID">SOLID</a>.</p><h3>Definition</h3><blockquote>Composite design pattern là một structural pattern, nó cho phép chúng ta xây dựng một cấu trúc hình cây trong đó mỗi node trên cây đều có chung một Interface. Giúp cho client có thể điều khiển cả cây mà chỉ cần thông qua root node.</blockquote><h3>Structure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iUhM1K1GVClVz6PBZff6SQ.png" /></figure><p>Chìa khoá của Composite là chúng ta cần phải có một Interface/Protocol đủ tốt để làm cầu nối giữa client và các components phía sau. Câu này hơi trừu tượng, mình sẽ giải thích rõ hơn ở phần case study nhé.</p><h3><strong>Case Study</strong></h3><p>Phần này mình sẽ đưa ra một case study mà mình đã từng gặp ở công ty cũ nha.</p><h4>Requirement</h4><p>Lần đó mình phụ trách làm ứng dụng cho một công ty, đại loại là nó đã có một website chuyên viết các bài về du lịch, đặc sản,… giờ họ muốn có một ứng dụng để hiển thị các bài viết đó trên điện thoại. Các Bài viết được chia thành các thể loại khác nhau: mới, yêu thích, phổ biến. Mỗi thể loại sẽ có một màn hình riêng để hiển thị, ngoài ra sẽ có một màn hình <em>tổng hợp</em> hiển thị tất cả các thể loại bài viết. API thì bên khách hàng nó sẽ lo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*TgRk3IEs7IFxJXVIPO4N3A.png" /><figcaption>Prototype of the application.</figcaption></figure><p>OK, requirement đã rõ, giờ sao nà !? Dễ mà nhỉ 😙 mỗi màn hình thì cứ gọi API lấy bài viết về rồi hiển thị lên thôi.</p><h4>Why do bad things happen to good people ?</h4><p>Buổi sáng định mệnh hôm đó, sếp đến và nói với mình rằng do website của khách hàng sử dụng <a href="https://wordpress.com/">wordpress</a> nên nó không custom được API cho màn hình <em>tổng hợp </em>nên màn hình này mình sẽ phải gọi một lúc 3 API để lấy các bài viết thuộc các thể loại tương ứng.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*GBtvAojvb6wFRxCmDdSmaw.jpeg" /></figure><h4>Finding Solution</h4><p>Cái khó là màn hình <em>tổng hợp</em> thôi chứ mấy màn hình kia không có gì. Nên mình sẽ nói về màn hình đó nha.</p><p>Mình bắt đầu với <em>chìa khoá </em>của chúng ta: một Interface “đủ tốt”. Đứng từ phía client, client không cần và cũng không nên biết các bài viết thuộc thể loại nào, client chỉ là thằng yêu cầu “<em>Đưa tao danh sách bài viết để tao sử dụng, tao không quan tâm mày lấy từ đâu</em>”. Từ suy nghĩ đó mình có protocol FeedLoader:</p><pre>protocol FeedLoader {<br>   typealias Result = Swift.Result&lt;[FeedItem], Error&gt;  <br>   func load(completion: @escaping (Result) -&gt; Void)<br>}</pre><p>Client trong có thể là một ViewController, một Presenter, một ViewModel hoặc một Service nằm trong một module nào đó,... Mình sẽ lấy ví dụ client là một ViewController: AllCategoriesViewController</p><pre>class AllCategoriesViewController: UIViewController {  <br>  var loader: FeedLoader?<br>   <br>  func viewDidLoad(){    <br>      super.viewDidLoad()        <br>      loadFeed()  <br>  }    </pre><pre>  private func loadFeed(){    <br>      loader?.load { items in      <br>         // Do your work here    <br>      }  <br>  }  </pre><pre>}</pre><p>Như mình đã nói, client yêu cầu lấy list bài viết và chỉ quan tâm đến kết quả, không quan tâm đến cách làm hay <strong><em>“Tell Don’t Ask”</em></strong> . OK, Giờ đến các implements của FeedLoader:</p><pre>final class NewArticleLoader: FeedLoader {<br>    private let url: URL<br>    private let client: HTTPClient</pre><pre>    init(url: URL, client: HTTPClient) {<br>       self.url = url<br>    }</pre><pre>    func load(completion: @escaping (FeedLoader.Result) -&gt; Void){<br>       client.get(from: url) {<br>          // map data to [FeedItem]<br>          // completion(.success(items))<br>       }<br>    }<br>}</pre><pre>final class FavoriteArticleLoader: FeedLoader {<br>    private let url: URL<br>    private let client: HTTPClient</pre><pre>    init(url: URL, client: HTTPClient) {<br>       self.url = url<br>    }</pre><pre>    func load(completion: @escaping (FeedLoader.Result) -&gt; Void){<br>       client.get(from: url) {<br>          // map data to [FeedItem]<br>          // completion(.success(items))<br>       }<br>    }<br>}</pre><pre>final class TrendingArticleLoader: FeedLoader {<br>    private let url: URL<br>    private let client: HTTPClient</pre><pre>    init(url: URL, client: HTTPClient) {<br>       self.url = url<br>    }</pre><pre>    func load(completion: @escaping (FeedLoader.Result) -&gt; Void){<br>       client.get(from: url) {<br>          // map data to [FeedItem]<br>          // completion(.success(items))<br>       }<br>    }<br>}</pre><p>Nếu đọc đến đây và bạn bắt đầu nghĩ: “<em>ủa rồi Composite pattern của tao đâu ? Bài này viết về nó mà phải hông ta ?!</em>” thì các bạn hãy bình tĩnh, Composite của các bạn tới rồi đây 😇.</p><pre>final class AllCategoriesArticleLoaderComposition: FeedLoader {<br>    private let newArticleLoader: NewArticleLoader<br>    private let favoriteArticleLoader: FavoriteArticleLoader<br>    private let trendingArticleLoader: TrendingArticleLoader<br>    private let group = DispatchGroup()</pre><pre>    init(newArticleLoader: NewArticleLoader,<br>         favoriteArticleLoader: FavoriteArticleLoader,<br>         trendingArticleLoader: TrendingArticleLoader) {<br>         self.newArticleLoader = newArticleLoader<br>         self.favoriteArticleLoader = favoriteArticleLoader<br>         self.trendingArticleLoader = trendingArticleLoader<br>    }</pre><pre>func load(completion: @escaping (FeedLoader.Result) -&gt; Void){<br>       var items: [FeedItem] = []()<br>       [newArticleLoader, favoriteArticleLoader,         trendingArticleLoader].forEach {<br>           group.enter()<br>           $0.load { items in<br>              items.append(items)<br>              group.leave()<br>           }<br>           group.wait(timeout: .distantFuture)<br>       }<br>     ......<br>}</pre><h3>Implementation</h3><pre>let client = HTTPClient(session: URLSession.shared)</pre><pre>let newArticleURL = &quot;https://an-url/new/&quot;<br>let newArticleLoader = NewArticleLoader(url: newArticleURL, client: client)</pre><pre>let favoriteArticleURL = &quot;https://an-url/favorite/&quot;<br>let favoriteArticleLoader = FavoriteArticleLoader(url: favoriteArticleURL, client: client)</pre><pre>let trendingArticleURL = &quot;https://an-url/trending/&quot;<br>let trendingArticleLoader = TrendingArticleLoader(url:   trendingArticleURL, client: client)</pre><pre>let compositionLoader = AllTypesArticleLoaderComposition(newArticleLoader: newArticleLoader,<br>                                 favoriteArticleLoader: favoriteArticleLoader, <br>                                 trendingArticleLoader: trendingArticleLoader)</pre><pre>let viewController = AllCategoriesViewController()<br>viewController.loader = compositionLoader</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*r51Mv0_xYtf79yqA_BcvYw.gif" /></figure><h3>Conclusion</h3><p>Để tóm cái váy lại thì các bạn cùng nhìn vào diagram này để xem chúng ta đã làm những gì nhé:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y7lE08wOT4d-FfUFWef6ew.png" /></figure><p>Bằng việc áp dụng Composite design pattern, <em>compose </em>các components khác nhau, bạn đã làm cho phần mềm <em>flexible</em> hơn rất nhiều, <em>open-closed</em> hơn rất nhiều. Bạn có thể thêm, sửa hoặc xoá chức năng mà không cần thay đổi một dòng code nào ở phía client 🥰.<br>Vậy là bài viết xin phép được dừng tại đây. Hy vọng các bạn đã học được chút gì đó từ bài viết. Đừng quên claps và ấn follow mình để đọc những bài viết tiếp theo nhé. Love you all 🥰!</p><p><em>Tài liệu tham khảo: <br>- </em>Design Patterns: Elements of Reusable Object-Oriented Software (Gang of four)<br>- Tell don’t ask principle: <a href="https://martinfowler.com/bliki/TellDontAsk.html">https://martinfowler.com/bliki/TellDontAsk.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=637620cb2fa4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>