<?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 Nabil Khaja on Medium]]></title>
        <description><![CDATA[Stories by Nabil Khaja on Medium]]></description>
        <link>https://medium.com/@nkhaja?source=rss-bfebe8fda890------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZkD_NHJt_Mk9V65ydy7Yvw.jpeg</url>
            <title>Stories by Nabil Khaja on Medium</title>
            <link>https://medium.com/@nkhaja?source=rss-bfebe8fda890------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 19:34:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nkhaja/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[The Life of a Bitcoin Transaction]]></title>
            <link>https://medium.com/@nkhaja/the-life-of-a-bitcoin-transaction-a27b6723489a?source=rss-bfebe8fda890------2</link>
            <guid isPermaLink="false">https://medium.com/p/a27b6723489a</guid>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[money]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[bitcoin-mining]]></category>
            <dc:creator><![CDATA[Nabil Khaja]]></dc:creator>
            <pubDate>Mon, 25 Apr 2022 20:53:41 GMT</pubDate>
            <atom:updated>2022-04-25T20:53:41.596Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What happens when you attempt to send bitcoin from your address to anyone else?</strong></p><p>Let’s break that down step by step in this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*OEx97l_HIM6PtXroU4RpKA.png" /><figcaption>The Bitcoin Transaction Lifecycle</figcaption></figure><h4><strong>Step 0: Get Bitcoin Wallet Software</strong></h4><p>A bitcoin “wallet” is a keychain for storing credentials that let you submit transactions to the bitcoin network. <a href="https://bitcoin.org/en/choose-your-wallet">Wallet software</a> generates and holds your public-private key pair, which are roughly equivalent to an email address and password. You can share your “address” (derived from the public key) with folks you want to receive transactions from. You NEVER share your private key — it gives permission to send money from your address to others. No private key? Goodbye bitcoins.</p><p>Wallet software also gives you the ability to connect to the bitcoin network to send and receive money.</p><h4><strong>Step 1: Sign Your Transaction</strong></h4><p>Let’s say you need to pay an avant-garde contractor for your recent covid-19 home makeover in bitcoin. You’d start by collecting their public address and designating an amount to send (1 bitcoin…marble ain’t cheap) using your wallet software. This is your “transaction”. Before a transaction can be sent to the bitcoin network however, you need to “sign” it with your private key. The signed transaction is proof that YOU, and not anyone else (like the tinder swindler), are the sender. The output of this process is a “hash” ( a long string of letters and numbers ) that nodes on the bitcoin network can use to validate the authenticity of the sender without knowing the private key itself.</p><p>For an intuition on how this works, think back to your grades school locker, except it has two combinations and two compartments. One combination only you know (for the private compartment where you keep your valuables). The other combination can be shared with anyone to conditionally access the second “public” compartment. The public compartment opens if and only if you first lock it with your secret combination. Then it be opened by others using the public combination. That way, when someone opens the public compartment, they know that it must have been YOU that put the goods in there. Any attempt to open the public compartment when it’s set with a combination other than your private combination will not succeed.</p><h4><strong>Step 2: Broadcast Your Transaction to the Bitcoin Network</strong></h4><p>Since bitcoin is a peer to peer (decentralized) network, there isn’t a singular (centralized) place to send your transaction for broadcasting to everyone else. Instead, your wallet connects to neighboring nodes (other computers that also run bitcoin software) and sends the transaction to them. Each of those nodes in turn send transactions to all of their known nodes and so forth in a process called “flooding”. Every node in the network eventually hears about your transaction through this process. It’s like trying to get a message out through word of mouth, if you tell everyone you know, and they tell everyone they know, eventually everyone knows (including your ex).</p><p>All bitcoin clients (this includes your wallet and other nodes on the network) have a hardcoded url they can use to discover well connected peers. If your node/wallet is a loner because it’s just getting started, it won’t be long before it has friends (unlike when you started at high school). But if you’re picky about who you want to broadcast directly to (paranoid), you can manually add the i.p. addresses of nodes you trust.</p><h4><strong>Step 3: Transaction Validation</strong></h4><p>What do node’s do when they get a transaction? Validation. Each transaction is checked for a valid signature and valid transaction value (Do you actually have 1 bitcoin?) among other things. <strong>Full nodes</strong> will have a copy of the entire blockchain in their hard drives, and will validate your wallet balance by tracking the exchange of bitcoins all the way back to the block that it was mined on (an event that mints brand new bitcoins into the network). <strong>Light nodes</strong> and <strong>miners</strong> on the other hand just check that your transaction makes sense given the information on the most recent block (they delegate the rest of the validation work to a full node…how lazy).</p><p>Validated transactions get transferred into the node’s memory pool (mempool) where unconfirmed transactions live (think: purgatory for bitcoin transactions). Transactions are marked as confirmed only after they are written into a block (i.e. a list of transactions with a proof of work) on the block chain. More on this in the next section.</p><h4>Step 4: Confirming the Transaction on a Mined Block</h4><p>Mining nodes attempt to mine new bitcoin blocks through the “Proof of Work” process. I’ll demonstrate proof of work with a simple analogy:</p><p>I pick a random number within some range (1–1,000,000) and everyone on the network tries to guess the right number as quickly as possible. The more people that join the network, the larger the range gets so that a new block is mined every 10 minutes (on average). The only way to get the right answer is to keep guessing and checking. By the time someone shouts the right answer, they have (statistically speaking) done a lot “work” to find it (Wouldn’t your throat feel sore from shouting through all those numbers?).</p><p>When a lucky miner finally guesses the right value, they mint new bitcoins to their address. They also get to decide which transactions to confirm (include on the block). Each block can support a limited (~500) number of transactions, so senders such as yourself include transaction fees to incentivize their calloused miner hands to pull your transaction from the mempool and into the block.</p><p>The winning miner then rushes to gloat about their block to the network (via the same flooding technique). Nodes validate the proof of work, and then check the block’s transactions for overlap with their mempool. Overlapping transactions are marked as “confirmed” and removed from the pool before the block is transmitted to neighbors. Other miners realize the current PoW has been solved, drop confirmed transactions (they’re just here for the fees), and move onto the next proof of work problem.</p><p>As the number of confirmations against your transaction grow, so does your confidence that your exchange of bitcoin is settled.</p><h4>Conclusion</h4><p>Congratulations! You’ve successfully sent 1 bitcoin 🙂</p><p>Your contractor grins as his wallet updates with the payday. He kindly reminds you that as a good citizen you will owe capital gains tax on this bitcoin transaction. You’re bummed about the tax liability, but thankful that he’s explained abstruse cryptocurrency tax law to you. You write him a Yelp review for his excellent contract work, which also included a free accounting lesson. 5 Stars.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a27b6723489a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Routers, Service Layers, and Generic Networking with Swift]]></title>
            <link>https://medium.com/@nkhaja/routers-service-layers-and-generic-networking-with-swift-f96c1f08dd5?source=rss-bfebe8fda890------2</link>
            <guid isPermaLink="false">https://medium.com/p/f96c1f08dd5</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[alamofire]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[generics]]></category>
            <dc:creator><![CDATA[Nabil Khaja]]></dc:creator>
            <pubDate>Mon, 03 Apr 2017 20:26:26 GMT</pubDate>
            <atom:updated>2017-04-24T21:41:00.542Z</atom:updated>
            <content:encoded><![CDATA[<p>Given a handful of API routes, what’s an effective way to set up your network calls and handle responses?</p><p>In this article I’ll walk you through how I built (some) of the networking architecture for a clone of <a href="https://itunes.apple.com/us/app/whale-q-a/id1140619549?mt=8">Whale iOS</a>, and why doing things this way made life much easier.</p><p><strong>NOTE: The code demonstrated uses the Alamofire and SwiftyJSON libraries.</strong></p><h3>Start With a Router</h3><p>Suppose your app must handle the following routes:</p><ul><li>/login [POST]</li><li>/users [GET, POST]</li><li>/questions [GET, POST]</li><li>/answers [GET, POST]</li></ul><p>Routers are an excellent way to get an HTTP request’s parameters, body, headers, and method constructed in one place. Since we have finite endpoints, we’ll represent each route as an enum.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecb670af4a4bb9721a9369a327d542ae/href">https://medium.com/media/ecb670af4a4bb9721a9369a327d542ae/href</a></iframe><p>Our router conforms to Alamofire’s URLRequestConvertible protocol, which combines critical parts of a network request: Headers, Path, Parameters, Body, and Method, using the asURLRequest() function (see below). The resulting URLRequest is used by Alamofire to contact the desired API endpoint.</p><p>Next we create dynamic variables that switch on self (WhaleRouter). Since WhaleRouter is an enum, each of its variables will automatically populate by switching on one of the cases listed above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22c7a9cca7c597abaa79e7ff431494b6/href">https://medium.com/media/22c7a9cca7c597abaa79e7ff431494b6/href</a></iframe><p>NetworkingConstants is a struct for keeping track of all my string arguments like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/672a2f12642a07d82a55a5cda34a5589/href">https://medium.com/media/672a2f12642a07d82a55a5cda34a5589/href</a></iframe><p>This ensures that if I type anything incorrectly, I need only correct it in one place. It also lets me take advantage of autocomplete, and avoid silly mistakes by hard-coding strings all over my project.</p><p>Once asURLRequestConvertible() is run, all variables are combined into a complete request!</p><h3>Handle Your Network Response in a Service Layer</h3><p>A service layer is where the logic of dealing with responses from the network is handled. Your viewModel or viewController should interface this layer to get updated data as necessary (<a href="https://medium.com/@karthikkeyan/ios-app-architecture-3f1d1400862f">Learn more</a>). When I first wrote this layer, I created the following functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2aa216ddcb5dffb399502d67ea2ce9bd/href">https://medium.com/media/2aa216ddcb5dffb399502d67ea2ce9bd/href</a></iframe><p>I’ll first discuss some features of this code, then show you how it can be vastly improved.</p><p><strong>Breaking down the code:</strong></p><p>Take a look at getAnswers(). We make the Alamofire request on a URL returned by calling an enum from our router. Next we switch on the result. If the network request fails, we propagate the error. If the it’s a success, we get the associated value from result, which is an array of JSON. We pass the JSON to parseAnswers(), which returns an array of Answer using a failable initalizer inside flatmap.</p><p>flatmap performs the same function as map , with the addition of filtering out any nil results, and flatting the fields inside a JSON array (<a href="https://www.natashatherobot.com/swift-2-flatmap/">more on flatmap</a>). Failable initializers are a type of init(), that can return nil. These are useful for initializing objects based on JSON because we can choose to abort initialization if values are missing. Below is an example of how I use the failable initializer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be5dd545a6198eb8aa5d133496343cd8/href">https://medium.com/media/be5dd545a6198eb8aa5d133496343cd8/href</a></iframe><p>Finally we pass our result into the completion handler, which the receiving viewModel/Controller can switch on to retrieve the data (array of Answer).</p><p><strong>But so much repetition!</strong></p><p>In addition to Answer, I must retrieve collections of Question, and User for this project. I ended up writing code the following to perform those tasks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9e05fa71cc4be4b8c90409496a39920/href">https://medium.com/media/d9e05fa71cc4be4b8c90409496a39920/href</a></iframe><p>By the time I wrote getQuestions() and prepared to write getUsers(), I was frustrated. This is redundant code. Notice that each pair of functions is virtually identical, with the exception of the type being returned. It was at this moment that the beauty of networking with generics struck me.</p><h3><strong>Shrink Your Service Layer with Generics!</strong></h3><p>I went back over the previous snippet of code, and replaced specific types with Generic parameters. The result? I whittled my code for returning collections data (arrays of anything) to one pair of functions — that could be reused for any project!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb89639f2b957bb970fb716370fbeaa1/href">https://medium.com/media/eb89639f2b957bb970fb716370fbeaa1/href</a></iframe><p>Now I can call getData() in any viewModel/Controller, specify a route, and get back an array of the desired type.</p><p>Note that I made the generic parameter (and all Types I want to call this function for) conform to the protocol Failable , which looks like this:</p><pre>protocol Failable {</pre><pre>init?(json: JSON)</pre><pre>}</pre><p>T:Failable is necessary for the compiler to know that init?() can be called on the generic type T . Instead of being ANY type — not all types have failable initializers — T is now understood be the subset of all types that do.</p><p>However, parseData() alone does not know which of Answer, Question, or User to initalize when we call U.init. To notify the compiler we need to explicitly state the type of the desired result in our callback. I need to write the following code in my AnswerViewController, where I will call getData() to update the controller with new answers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bd8a0a5e6a4cbf929f937efaa0ac82a/href">https://medium.com/media/2bd8a0a5e6a4cbf929f937efaa0ac82a/href</a></iframe><h3><strong>Try it Yourself!</strong></h3><p>Take a look at any networking code you’ve written before and see if you can refactor it using the architecture tips here!</p><h3>But What About Pagination?</h3><p>Stay tuned! I’ll cover how I took the code above a step further to allow pagination in followup article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f96c1f08dd5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memoization and Decorators with Python]]></title>
            <link>https://medium.com/@nkhaja/memoization-and-decorators-with-python-32f607439f84?source=rss-bfebe8fda890------2</link>
            <guid isPermaLink="false">https://medium.com/p/32f607439f84</guid>
            <category><![CDATA[decorators]]></category>
            <category><![CDATA[memoization]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Nabil Khaja]]></dc:creator>
            <pubDate>Wed, 22 Mar 2017 01:19:10 GMT</pubDate>
            <atom:updated>2017-03-24T23:01:31.016Z</atom:updated>
            <content:encoded><![CDATA[<p>Recursion offers programmers a convenient way to break larger problems into manageable pieces. Consider the iterative versus recursive solutions for a fibonacci sum.</p><pre># iterative<br>def fib_iterative(n):<br>      if (n == 0):<br>              return 0<br>      elif (n == 1):<br>              return 1<br>      elif (n &gt;1 ):<br>              fn = 0<br>              fn1 = 1<br>              fn2 = 2<br>              for i in range(3, n):<br>                      fn = fn1+fn2<br>                      fn1 = fn2<br>                      fn2 = fn<br>              return fn</pre><pre># recursive<br>def fib(n):<br>    if n == 0:return 0<br>    if n == 1:return 1<br>    else: return fib(n-1) + fib(n-2)</pre><p>Recursive solutions are often easier to read and write for branching problems. Tree traversals, graph traversals, and mathematical series are (often) dealt with more intuitively using recursion.</p><p>Though it affords convenience, the computational time cost of recursion on branching problems grows exponentially with larger values of n.</p><p>Lets take a look at the call stack for fib(6)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*3eiROF2Osi6-3YlHYYyjRw.png" /></figure><p>We do roughly twice as many operations at each successive level of the tree. Giving us a time complexity O(2^n).</p><p>If we take a closer look at our tree, you’ll notice that we’re repeating work. fib(2) is calculated five times, fib(3) is calculated three times and so on. Though this isn’t a problem for small values of <em>n</em>,<em> </em>imagine the amount of repeated work in calculating fib(1000).<strong> Once we revise our recursive solution, try running the same problem (say fib of 20) for both versions and notice the remarkable difference in the time to completion.</strong></p><p>Surely there’s a good way to prevent repeated work, and keep our elegant solution?</p><h3>Memoization: You can have your Cake and Eat it Too!</h3><p>With memoization, we can “memoize” (remember, store) the result of problems that we’ve dealt with before, and return a stored result instead of repeating calculations.</p><p>For example, once fib(2) is calculated, we can store the result and use it the next four times fib(2) is encountered.</p><p>This reduces our run-time from O(2^n) to O(n) because we’re calculating each of fib(0)…fib(n) only once.</p><p>One way to accomplish this is using a dictionary.</p><pre>__fib_cache = {}</pre><pre>def fib_memo(n):<br>    if n in __fib_cache:<br>        return __fib_cache[n]<br>    <br>    else:<br>      __fib_cache[n] = n if n &lt; 2 else fib_memo(n-2) + fib_memo(n-1)<br>        return __fib_cache[n]</pre><p>And voila! We’ve successfully memoized a recursive function!</p><p>However we can take things one step further and abstract memoization for any recursive function!</p><h3>Decorators : Functions using functions to perform other Functions</h3><p>Decorators are known as “Higher order functions” : functions that take other functions as parameters. Here we will use a decorator to generalize memoization.</p><p>Here is a decorated solution:</p><pre>def memoize(func):<br>    cache = func.cache = {}</pre><pre>    @functools.wraps(func)<br>    def memoized_func(*args, **kwargs):<br>        key = str(args) + str(kwargs)<br>        if key not in cache:<br>            cache[key] = func(*args, **kwargs)<br>        return cache[key]</pre><pre>    return memoized_func</pre><pre>@memoize<br>def fibonacci(n):<br>    if n == 0:return 0<br>    if n == 1:return 1<br>    else: return fib(n-1) + fib(n-2)<br></pre><p>Lets break it down line by line.</p><p>Our decorator is a function that takes another function as an argument, we declare it as such on line 1.</p><p>Next we declare a dictionary func.cache = {}, which is declared as a property offunc. Here we will store each unique call made by func.</p><p>We’ll come back to @functools.wraps.</p><p>def memoized_func(*args, **kwargs): — Inside the decorator we define a new, memoized function based on the func we passed in, and it takes in the same parameters are func. We call this new version memoized_func.</p><p>*args is a keyword indicating that memoizer takes an arbitrary number of arguments e.g.def memoize(one two three) or def memoize(just_one) are both valid. Similarly *kwargs represents an arbitrary number of keyword arguments (parameters defined at the function call) e.g. def memoize(one = 1, two = 2, three = 3) . Note : You can use these specialized parameters in any function.</p><p>The following line declares a key for our func.cache based on the parameters given. If we have seen this combination of parameters before, we pull the result from func.cache , otherwise create a new key using the original func as it was defined (e.g. using fib), and assign it’s value to the result e.g. ( store the result of fib(2)).</p><p>The last line inside memoized_func() returns the result of a single call to func with the given parameters.</p><p>The final line returns memoized_func(), which represents a modified version of our original function with added (decorated) features, that is, storing the result of each new call.</p><p>Finally we mark our original function with @memoize . The ‘@’ notation tells the compiler to pass the function immediately below it into a higher order function called memoized_func — which in our case returns a memoized version of fibonacci(). This version of the function will immediately return results we’ve calculated before, otherwise it will call the original fib() function to determine what that number should be.</p><h3>What is @functools.wraps?</h3><p>@functools.wraps is yet another decorator that is built into python. It allows decoratormemoize to store information related the memorized function’s docstring, or function name so that information can be accessed later. If we were to ask python fib.__name__ or fib.__doc__ (these are built in properties to functions), without @functools.wraps we it would return the name and docstring for memoized_fib and not fib itself. For debugging purposes, it’s helpful to have access to the name and docstring of the original function being called, not the decorating function, as the same decorator could be applied to a multitude of functions.</p><h3>Try it yourself!</h3><p>Next time you come across a recursive function, think about whether you can improve its performance with memoization, and then abstract that memoization to other functions by adding a decorator!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32f607439f84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Protocol Oriented Programming: A Swift Solution to OOP Headaches]]></title>
            <link>https://medium.com/ios-seminar/protocol-oriented-programming-a-swift-solution-to-oop-headaches-e05d9c5d29a1?source=rss-bfebe8fda890------2</link>
            <guid isPermaLink="false">https://medium.com/p/e05d9c5d29a1</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[protocol-oriented]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Nabil Khaja]]></dc:creator>
            <pubDate>Sun, 19 Mar 2017 23:11:28 GMT</pubDate>
            <atom:updated>2017-04-24T21:37:27.650Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why is OOP so Popular?</h3><p>Object Oriented Programming (OOP) was the classic strategy to write modular code for decades, and with good reason.</p><ol><li><strong>Reusability: </strong>Well-written objects are stand-alone entities that can be plugged into other programs. If I implement an optimized tree, I can use it in any part of an existing project, or in a brand new one, without writing more code.</li><li><strong>Skip the details</strong>: Another programmer doesn’t need to know your object’s implementation. If I see a “Sort” function, I can use without worrying what the code looks like.</li><li><strong>Error-Proofing</strong>: We can hide access to functions or variables in a class, which prevents other developers, that are less familiar with our code, from create bugs. Others see only what they need to see.</li><li><strong>Make Big Projects Manageable: </strong>Big<strong> </strong>projects get complicated. OOP lets us break a large problem into sub problems — each of which are handled by different objects. If Nabil, Julia, and Alex are making a <a href="http://www.pacxon4u.com/space-invaders/">space invaders</a> game. Nabil can build an object to represent Aliens, Julia can build a GameBoard object that keeps track of my score, number of lives, and when the game starts/finishes, and Alex can make objects representing my tank and its missiles. In end, we compose these objects to build a functioning game.</li><li><strong>Updating Code: </strong>With modular code we can write easily add to, update, or remove specific components as time goes on. <strong>e.g. </strong>In a building made of bricks, you can swap out a cracked brick with a new one instead of replacing entire sections of the building.</li></ol><h3>Out With the Old</h3><p>Though very handy, OOP comes with its fair share of issues:</p><ol><li><strong>“GOD” objects, Massive View Controller</strong>: To maintain modularity programmers use the one class, one purpose principal. However bloated viewControllers and models are common by-products of popular swift design patterns (MVC, MVVM). Passing around chunky objects slows your code, and makes modularity difficult as you build out. If an object holds too much of the functionality you need, new code you write will end up depending on it too.</li><li><strong>Multiple Ownership: </strong>Lets suppose you and a fellow engineer (Nick), are working on separate ViewControllers that reference the same <strong><em>BankAccount</em></strong> object. If you add credit in <strong><em>firstViewController</em></strong> while Nick removes credit in <strong><em>secondViewController</em></strong>, both of you will end up with an unexpected result. Classes are passed by reference, so changing the values in one area of your project will cause changes to that object’s values in every other place. This makes it difficult to test the isolated effect of your functions on a given object.</li><li><strong>The Subclassing Problem:</strong> A Problem so big is deserves its own section</li></ol><h3>The Subclassing Problem and Why You Can’t Have the Cheeseburger you Want</h3><p>Your stomach grumbles, so you decide to check out the old “OOP burgers” joint, where they’re famous for their cheeseburger. The cheeseburger comes with Pickles, Tomatoes, Onions, and Mushrooms. But you’re allergic to Mushrooms! So you ask the waiter to substitute the mushrooms for Kale — you LOVE Kale. The waiter shakes his head and says it’s impossible. He tells you the only way you can have Kale is to get a CheeseBurger with all its standard ingredients, with the kale will get placed on top of everything else…Bummer.</p><p>OOP driven inheritance often gives subclasses more baggage than we desire. Lets first take a look at how inheritance can be used effectively, then take a look at how this can lead us into problems. Finally I’ll introduce you to Protocol Oriented Programming: A “Swifty” way to achieve everything OOP offers, while skipping many of its issues.</p><p>Here’s an example of a typical inheritance pattern:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3389fff80626d3863f9b2b00ca8eb3c/href">https://medium.com/media/c3389fff80626d3863f9b2b00ca8eb3c/href</a></iframe><p>This is effective use of inheritance because a SportsCar will utilize everything in Vehicle, plus some extra features that should only be in sports vehicles. But hey, we’re in the age the electric vehicle, so lets create a subclass for that too!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57acb7d9a9b0c975ff993430be36fad9/href">https://medium.com/media/57acb7d9a9b0c975ff993430be36fad9/href</a></iframe><p>This is an example of poor inheritance.</p><p>We get extraneous features, fillGas and gasTank that are irrelevant in an ElectricVehicle class because</p><ol><li>Electric vehicles don’t use these components by design. Having them in an electric vehicle class is unintuitive.</li><li>For a developer using your electric vehicle object, it’s really confusing to see functions that modify obsolete features — Why are they here? Its unnecessary bloating.</li></ol><p>Now lets say I want to add a superCharging feature to ElectricVehicle. This feature will get inherited (along with gasTank), by every class that subclasses ElectricVehicle. But not everything that needs inheritance from ElectricVehicle uses superCharging! Suppose 8/10 electric vehicles use supercharging — our choices are to either implement supercharging in 8 subclasses of ElectricVehicle or bloat two subclasses with code for supercharging that will not get used.</p><p>This problem only gets worse as we continue down subclass down the chain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZBy1cMNKlZOYR_AHRVNadQ.jpeg" /><figcaption>Every function and field in ElectricVehicle is dumped into each of these three subclasses</figcaption></figure><p>In bigger projects, we get massive inheritance structures that go several layers deep:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*pljS68QSe16eb_y4EQs61A.png" /></figure><p>These structures are prone to causing architectural headaches. For example, What if we wanted to add a penguin class to the following structure?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*ziWdISgNakU3t2HyKkPpPg.png" /><figcaption>Where does penguin go?</figcaption></figure><p>Penguins don’t fly. So we’d have to create a two new classes “Flying Birds” and “Flightless Birds” and reorganize all of our birds under these classes. Wait, what about birds that can swim? The headache goes on…</p><p>How do we prevent the subclassing problem without knowing all the classes we are going to add ahead of time?</p><h3>Enter Protocol Oriented Programming</h3><p>Swift is a language designed to give power to value types. The standard library is designed with just 4 classes, and 95 instances of structs and enums.</p><p>Protocol Oriented Programming (POP) is an architecture encourages developers to leverage the functionality packed into value types: Use structs, enums, and protocols in place of additional classes.</p><p>Why is this helpful?</p><p>Lets go back to our Vehicle problem.</p><p>We have features that need to be shared between electric and gas vehicles (such as the ability to start, stop, park), and others that belong exclusively to one group (filling gas, charging batteries).</p><p>Lets build protocols for each of these feature sets!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9289d6eee83d23b64848ead8e086f7a/href">https://medium.com/media/e9289d6eee83d23b64848ead8e086f7a/href</a></iframe><p>Now we can put functions exclusively where needed, while getting the added flexibility of conforming very disparate classes to the same protocol. Before the fillable() functionality was confined to the Vehicle class and classes that inherited from it. But if I wanted to create an unrelated type now, let’s say a Bucket struct, I can conform that to the fillable protocol as well!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be8405ae3b3525595e6b74e87ddc81c9/href">https://medium.com/media/be8405ae3b3525595e6b74e87ddc81c9/href</a></iframe><p>Another bonus is that we can use Structs in place of classes. Previously we used classes in order to take advantage of inheritance, but that is no longer necessary because we get the desired functionality through protocols.</p><p>So we’ve solved one problem, but it appears we’ve created another. When conforming to a protocol in swift, each function from that protocol must be implemented to satisfy the compiler. How do we get around this without repeating code?</p><h3>Protocol Extensions to the Rescue!</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aaccd7804434839aa9ffa86750f0a0f1/href">https://medium.com/media/aaccd7804434839aa9ffa86750f0a0f1/href</a></iframe><p>Using a protocol extension, I can indicate a class or set of classes for which functions of this protocol will have a default implementation. Now in any ElectricVehicle class, or any of its subclasses, I can call recharge() without implementing it again. However, if I want to change how recharge() behaves in one of my new classes, I can override this implementation inside the file of the new object.</p><p>Alternatively I can have multiple structs adhere to the protocol extension:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6076d63bb8b2e22eb7cce800725a3aa1/href">https://medium.com/media/6076d63bb8b2e22eb7cce800725a3aa1/href</a></iframe><p>Or even create a new protocol that composes several others:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06b194a93b50f26c966decf27a999e81/href">https://medium.com/media/06b194a93b50f26c966decf27a999e81/href</a></iframe><h3>Protocol Oriented Programming and UIKit</h3><p>Because swift relies heavily on its interactions with UIKit, which is built entirely with classes, we still need to deal with Objects when using POP.</p><p>To learn more about this I highly suggest you check out <strong>Andrew Mastuchak</strong>’s <a href="https://realm.io/news/andy-matuschak-controlling-complexity/">talk</a> on using value oriented programming in swift, where he discusses the benefits of having thick logic layer composed of value types, that interacts with thin action (User Interface) layer composed of classes.</p><p>To learn more about using POP to vastly improve your interactions with UIKit, I highly suggest you check out <strong>Natasha The Robot</strong>’s Realm <a href="http://To learn more about using POP to vastly improve your interactions with UIKit, I highly suggest you check out Natasha The Robot’s Realm talk on practical POP">talk</a><strong> </strong>on practical POP.</p><h3><strong>TLDR; The Benefits of Using POP</strong></h3><p>To Summarize:</p><ol><li><strong>Abstracting code</strong> into Protocols creates reusable code that you can add and remove without worrying about restructuring your inheritance</li><li><strong>Single Ownership:</strong> Structs are passed by value. The copy of values that you manipulate in a struct will not be affected by activity happening elsewhere in you code. Headaches with threading (Multiple Read/Write problems) and multiple ownership become a thing of the past</li><li>Completely unrelated types can share overlapping functionality</li><li><strong>Clear labels</strong>. Looking at a class declaration and the protocols it conforms to, I can quickly gather what a particular class/struct can accomplish.</li></ol><h3>Resources</h3><ul><li><strong>Inheritance is Bad: Code Reuse Part 1</strong>: <a href="http://blogs.perl.org/users/sid_burn/2014/03/inheritance-is-bad-code-reuse-part-1.html">http://blogs.perl.org/users/sid_burn/2014/03/inheritance-is-bad-code-reuse-part-1.html</a></li><li><strong>If You’re Subclassing, You’re Doing it Wrong</strong>: <a href="https://krakendev.io/blog/subclassing-can-suck-and-heres-why">https://krakendev.io/blog/subclassing-can-suck-and-heres-why</a></li><li><strong>Practical POP</strong>: <a href="https://realm.io/news/appbuilders-natasha-muraschev-practical-protocol-oriented-programming/">https://realm.io/news/appbuilders-natasha-muraschev-practical-protocol-oriented-programming/</a></li><li><strong>WWDC</strong> — Protocol Oriented Programming in Swift: <a href="https://www.youtube.com/watch?v=g2LwFZatfTI">https://www.youtube.com/watch?v=g2LwFZatfTI</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e05d9c5d29a1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ios-seminar/protocol-oriented-programming-a-swift-solution-to-oop-headaches-e05d9c5d29a1">Protocol Oriented Programming: A Swift Solution to OOP Headaches</a> was originally published in <a href="https://medium.com/ios-seminar">iOS Seminar</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>