<?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 Guido Marucci Blas on Medium]]></title>
        <description><![CDATA[Stories by Guido Marucci Blas on Medium]]></description>
        <link>https://medium.com/@guidomb?source=rss-2bc7f2f10e9e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sgEpk0TveZMulu5XL9_eOw.jpeg</url>
            <title>Stories by Guido Marucci Blas on Medium</title>
            <link>https://medium.com/@guidomb?source=rss-2bc7f2f10e9e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 05:38:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@guidomb/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[How to represent code invariants]]></title>
            <link>https://medium.com/exit-0/how-to-represent-code-invariants-b0c7d85b2739?source=rss-2bc7f2f10e9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0c7d85b2739</guid>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Guido Marucci Blas]]></dc:creator>
            <pubDate>Fri, 13 Apr 2018 03:45:53 GMT</pubDate>
            <atom:updated>2018-04-13T03:45:53.852Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This post was originally published in my personal blog. You can check it out </em><a href="http://guidomb.blog/swift/2018/04/09/how-to-represent-code-invariants.html"><em>there</em></a><em>.</em></p><p>I wanted to write a bit about how we represent code invariants, specifically when those invariants cannot be easily expressed or enforced by the language, in this case the Swift programming language. When we talk about invariants <a href="https://en.wikipedia.org/wiki/Invariant_(computer_science)">Wikipedia’s definition</a> explains it quite well:</p><blockquote>In <a href="https://en.wikipedia.org/wiki/Computer_science">computer science</a>, an <strong>invariant</strong> is a condition that can be relied upon to be true during execution of a program, or during some portion of it. It is a <a href="https://en.wikipedia.org/wiki/Logical_assertion">logical assertion</a> that is held to always be true during a certain phase of execution. For example, a <a href="https://en.wikipedia.org/wiki/Loop_invariant">loop invariant</a> is a condition that is true at the beginning and end of every execution of a loop.</blockquote><p>Basically something that we know it’s always true and won’t change. Otherwise somebody made a serious mistake and our program would probably crash. Now that we have defined some terminology lets jump right down to the code.</p><pre>public struct RangeMapper {<br><br>    let title: SpreadSheetRange<br>    let description: SpreadSheetRange<br>    let attributes: SpreadSheetRange<br><br>    public init(title: SpreadSheetRange, description: SpreadSheetRange, attributes: SpreadSheetRange) {<br>        self.title = title<br>        self.description = description<br>        self.attributes = attributes<br>    }<br><br>    var ranges: [SpreadSheetRange] {<br>        return [title, description, attributes]<br>    }<br><br>}</pre><p>RangeMapper is a type that represents a set of SpreadSheetRanges that have a particular semantic associated with it. A SpreadSheetRange is a simple type that basically wraps a String and when created it verifies that the given string follows certain rules. In particular it should be a valid cells range identifier expressed in the <a href="https://developers.google.com/sheets/api/guides/concepts#a1_notation">A1 notation</a>. This notation is the one you may use to refer to a range of cells in a Google spread sheet, e.g: Sheet1!A1:D4. The following is a possible implementation of that type without the initializer&#39;s implementation because it is a little bit cumbersome:</p><pre>public enum SpreadSheetRange: CustomStringConvertible, Equatable {<br><br>    public enum CellRange: CustomStringConvertible, Equatable {<br><br>        case allCellsInRows(fromRow: UInt, toRow: UInt)<br>        case allCellsInColumn(columnName: String)<br>        case allCellsInColumnFromRow(columnName: String, fromRow: UInt)<br>        case range(from: String, to: String)<br><br>        public var description: String {<br>            switch self {<br>            case .allCellsInRows(let fromRow, let toRow):<br>                return &quot;\(fromRow):\(toRow)&quot;<br>            case .allCellsInColumn(let columnName):<br>                return &quot;\(columnName):\(columnName)&quot;<br>            case .allCellsInColumnFromRow(let columnName, let fromRow):<br>                return &quot;\(columnName)\(fromRow):\(columnName)&quot;<br>            case .range(let from, let to):<br>                return &quot;\(from):\(to)&quot;<br>            }<br>        }<br><br>        init?(from string: String) {<br>            // Somewhat long implementation that verifies all possible valid<br>            // A1 notation cases.<br>        }<br><br>    }<br><br>    case allCellsInSheet(sheetName: String)<br>    case cellRange(sheetName: String?, cellRange: CellRange)<br><br>    public var description: String {<br>        switch self {<br>        case .allCellsInSheet(let sheetName):<br>            return sheetName<br>        case .cellRange(let sheetName?, let cellRange):<br>            return &quot;\(sheetName)!\(cellRange)&quot;<br>        case .cellRange(.none, let cellRange):<br>            return cellRange.description<br>        }<br>    }<br><br>    public init?(from string: String) {<br>		// Implementation<br>    }<br><br>}</pre><p>The reason I’m talking about spread sheets and cell ranges is because I’m writing a program that needs to extract data from several Google spread sheets and do some magic with it. In one of those spread sheets there is structured data and that data could be represented with a struct like the following one:</p><pre>struct Ability {<br><br>    struct Attribute {<br><br>        let name: String<br>        let description: String<br>        let value: Int<br><br>    }<br><br>    let title: String<br>    let description: String<br>    let attributes: [Attribute]<br><br>}</pre><p>This structured data is spread throw out several spread sheets so I need to fetch from all of this spread sheets the cell ranges that contain this structured data. The spread sheet API has a method called <a href="https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchGet">batchGet</a> to fetch in one API call several cell ranges. It is important to note that a particular cell range could be translated to several Ability properties, meaning that there is not one to one relation between cell ranges and Ability properties.</p><p>That is why the RangeMapper type exists, to define the cell range for each Ability&#39;s property. We can then define an array of RangeMapper that need to be fetched and translate that to a list of ranges to pass to the batchGet method.</p><pre>let mappers: [RangeMapper] = //....<br>let cellRanges:[SpreadSheetRange] = mappers.flatMap { $0.ranges }</pre><p>It is out of the scope of this blog post to explain how the fetching and parsing logic works but believe than inside the code that parses the response from batchGet in order to get [Ability] as a result I needed to reference the amount of SpreadSheetRanges needed to parse an Ability value.</p><p>This is the invariant that I know holds true as long as I need 3 ranges to extract the data needed to create an Ability value. I could add a comment explaining what&#39;s the reason behind the magic number 3. I could then extract it into a constant and forget about it but this is the sort of trap I&#39;ve fallen down so many times before. What happens if the requirements change? Lets say that somebody decides to add new data and I need more ranges to extract it in order to successfully parse an Ability value, then I would need to update that magic number, which if extracted into a constant would only need to update it one place and if I have proper unit tests any issue should arise. The truth is that real world software development is a messy process and some of this measures could fail or not be implemented at all. Also I do have an OCD with things that I know could be automated, so this gave an excuse to think about how to reflect invariants that cannot be easily expressed with the tools we have and can evolve naturally as other parts of the system changes.</p><h4>Option 1: Use a constant</h4><p>The first options is the simplest one, which is adding the rangesCount static property. This has the disadvantage of remembering to keep in sync the rangesCount static property with the ranges computed property. We also need to remember to keep in sync the actual instance variables of type SpreadSheetRange with ranges array. Both issues could be mitigated by having unit tests.</p><pre>public struct RangeMapper {<br><br>    static func let rangesCount = 3<br><br>    let title: SpreadSheetRange<br>    let description: SpreadSheetRange<br>    let attributes: SpreadSheetRange<br><br>    public init(title: SpreadSheetRange, description: SpreadSheetRange, attributes: SpreadSheetRange) {<br>        self.title = title<br>        self.description = description<br>        self.attributes = attributes<br>    }<br><br>    var ranges: [SpreadSheetRange] {<br>        return [title, description, attributes]<br>    }<br><br>}</pre><h4>Option 2: Use key paths</h4><p>The second option is to only have one place where the actual ranges are assembles, in this case in a static property called ranges. Because this is a static property we need to use KeyPaths if we want to have an array to which we can ask the amount of elements it has. In this case the only think we need to keep in sync is the list of key path with the instance variables of type SpreadSheetRange. I consider option 2 to be superior to option 1 because it reduces the amount of things to keep in sync without adding too much complexity.</p><pre>public struct RangeMapper {<br><br>    static var ranges: [KeyPath&lt;RangeMapper, SpreadSheetRange&gt;] {<br>        return [<br>            \RangeMapper.title,<br>            \RangeMapper.description,<br>            \RangeMapper.attributes<br>        ]<br>    }<br><br>    let title: SpreadSheetRange<br>    let description: SpreadSheetRange<br>    let attributes: SpreadSheetRange<br><br>    public init(title: SpreadSheetRange, description: SpreadSheetRange, attributes: SpreadSheetRange) {<br>        self.title = title<br>        self.description = description<br>        self.attributes = attributes<br>    }<br><br>    var ranges: [SpreadSheetRange] {<br>        return RangeMapper.ranges.map { self[keyPath: $0] }<br>    }<br><br>}</pre><h4>Option 3: Use Sourcery</h4><p>The third option is to use <a href="https://github.com/krzysztofzablocki/Sourcery">Sourcery</a> to automatically generate all the code to avoid having to keep state in sync. I consider this to be the superior solution to all previous options at the expense of having to introduce a new tool as part of the build process.</p><p>For those who don’t know what Sourcery is, basically allows you to generate code based on templates that can introspect your source code. In this case we are defining an extension for every type that conforms to AutoRangeMappable, a protocol we use to mark the types that we want to extend. For each of those types we define an extension that implements the solution in Option 1 by iterating over all instance variable of type SpreadSheetRange.</p><pre>{% for type in types.implementing.AutoRangeMappable %}<br><br>extension {{ type.name }} {<br><br>  static let rangesCount = {{ type.instanceVariables.count }}<br><br>  public var ranges: [RangeMapper] {<br>    return [<br>      {% for variable in type.instanceVariables %}{% if variable.type.name == &quot;SpreadSheetRange&quot; %} {{ variable.name }}{% if not forloop.last %},{% endif %}{% endif %}<br>      {% endfor %}<br>    ]<br>  }<br><br>}<br>{% endfor %}</pre><p>We only need to conform to AutoRangeMappable.</p><pre>public struct RangeMapper: AutoRangeMappable {<br><br>    let title: SpreadSheetRange<br>    let description: SpreadSheetRange<br>    let attributes: SpreadSheetRange<br><br>    public init(title: SpreadSheetRange, description: SpreadSheetRange, attributes: SpreadSheetRange) {<br>        self.title = title<br>        self.description = description<br>        self.attributes = attributes<br>    }<br><br>}</pre><p>Then Sourcery will generate the following extension based on the previous template.</p><pre>extension RangeMapper {<br><br>    static let rangesCount = 3<br><br>    var ranges: [SpreadSheetRange] {<br>        return [<br>            title,<br>            description,<br>            attributes<br>        ]<br>    }<br><br>}</pre><p>If we want to add or remove an instance variable from RangeMapper all we have to do is run Sourcery and our extension will be automatically updated. You can add Sourcery as a build script and forget about it!</p><h4>To sum up</h4><p>The idea of this blog post is to show a particular case where there are invariants that cannot be easily enforced by the language without having some sort of manual sync process and show possible solutions. I’d love to know other cases where you faced a similar situation and see how you resolved it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0c7d85b2739" width="1" height="1" alt=""><hr><p><a href="https://medium.com/exit-0/how-to-represent-code-invariants-b0c7d85b2739">How to represent code invariants</a> was originally published in <a href="https://medium.com/exit-0">exit(0);</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Democratizing Computing Power]]></title>
            <link>https://medium.com/wolox/democratizing-computing-power-e60cf88d8c0b?source=rss-2bc7f2f10e9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e60cf88d8c0b</guid>
            <category><![CDATA[hackathons]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Guido Marucci Blas]]></dc:creator>
            <pubDate>Tue, 04 Jul 2017 21:50:08 GMT</pubDate>
            <atom:updated>2017-07-04T21:50:08.463Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7TPjmocvtWMlPtA2gpeXKA.png" /></figure><h4>How to apply the principles of the sharing economy to computing power resources in less than 48 hours.</h4><p>A couple of weeks ago we held our annual hackathon at Wolox. A two-day non-stop event where multifunctional teams are expected to implement a prototype for a product idea. At the end of the hackathon, each team must deliver a 3-minute pitch in front of a panel of judges. The teams are evaluated based on different criteria such as pitch delivery, UX, business model and prototype quality.</p><p>A month prior to the hackathon, woloxers are encouraged to submit ideas. In order to be accepted an idea must meet certain criteria or technologies, e.g: virtual reality, augmented reality, machine learning or blockchain. Then there is a period where the selected ideas are published and Woloxers are able to join the teams (or ideas). Up to 6 members per idea.</p><p>I decided to submit an idea that was in the back of my head for while but I never had the chance to really research. Over the last few months, I’ve been interested in doing something with <a href="https://en.wikipedia.org/wiki/Blockchain">blockchain</a> technology. I’d been reading up on machine learning for a class I was preparing on neural networks and that was when it clicked.</p><p>Neural network algorithms usually need a cluster of GPUs in order to train their models much faster than a regular computer would do. Having to maintain your own cluster is expensive and complex and getting a cloud-based cluster on services like AWS is also expensive, compared to a cluster of regular EC2 instances. Getting access to such technology for someone that wants to do research or bootstrap a startup idea could be a deal breaker when you consider the actual cost of hardware or cloud services.</p><p>Thanks to penetration of smartphones in the market most people carry a <a href="https://en.wikipedia.org/wiki/Graphics_processing_unit">GPU</a> with them in their pockets. Those slick animations or cool 3D games you play on your phone are powered by the GPU. But when your phone’s screen is turned off the GPU is doing absolutely nothing. What if we could still use all those resources that are idle even when you don’t use your phone?</p><p>This is how <strong>GPUse</strong> was born.</p><h4>How does this work?</h4><p>GPUse is a decentralized network of smartphones that executes tasks that require a GPU in exchange for money, in this case, Bitcoin. Users that want to contribute their phone’s GPU to the network can do so by installing GPUse’s mobile app. The app lets you configure a time frame to start accepting work, most likely around the time you go to sleep. Then it detects if the phone is fully charged, power connected with a WiFi connection, and from there it begins receiving job requests from the network. When a job is processed the network transfers Bitcoins to the phone’s owner based on the amount of time it took to process the job.</p><h4><strong>In a nutshell</strong></h4><p><strong>The users get paid for renting their phone’s GPU while they are not using it. Think of it as the Uber for unused phone’s processing power</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*VSoPoJClWr47SDgngfZzAA.gif" /><figcaption>This is how GPUse can help Ana (upper left) buy a new bike while also helping John (right) train his machine learning models</figcaption></figure><p>Users that want to process information that requires GPU can distribute the workload over the network and pay far less for the same “net” computing power they can get in a cluster on a service like EC2. (By net computing power I mean the total sum of all the theoretical power from all the GPU in the network). The idea is that although the GPUs available in a service like AWS are way more powerful than the GPU in an average smartphone, the size of GPUse network is theoretically bigger than Amazon’s. You compensate the power of one AWS GPU by using a lot of phones that have less powerful GPUs.</p><p>After almost 30 hours of no sleep and hacking, we managed to build a proof-of-concept. We made an iOS app that connects to a server that distributes work. To simplify what we mean by work we made a web app that lets users upload a video and a filter (implemented as an OpenGL (ES) <a href="https://en.wikipedia.org/wiki/Shader">shader</a>). The server in charge of distributing work gives each frame to a different phone which then applies the filter and returns the resulting frame. Once all frames have been processed the resulting video is assembled and returned to the user that submitted the job. Finally, Bitcoin transactions are performed between the user and each phone that processed frames.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*96-Qw9IFgAHvbyyTcA1H2A.png" /></figure><p>Although this is just a prototype, it is clear that GPUse has great potential. Besides being a great experience to work as a team, and get to know other woloxers, we got 2nd place!</p><p>In the following months, we plan to explore this idea further and evaluate the viability to transform this into a usable product. If you want to know more about GPUse or want to ask any question drop a comment below or Tweet at me <a href="http://twitter.com/guidomb">@guidomb</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e60cf88d8c0b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wolox/democratizing-computing-power-e60cf88d8c0b">Democratizing Computing Power</a> was originally published in <a href="https://medium.com/wolox">Wolox</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Message forwarding in Swift]]></title>
            <link>https://medium.com/exit-0/message-forwarding-in-swift-8223dd31e009?source=rss-2bc7f2f10e9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8223dd31e009</guid>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Guido Marucci Blas]]></dc:creator>
            <pubDate>Sat, 03 Jun 2017 16:45:05 GMT</pubDate>
            <atom:updated>2017-06-03T16:45:05.235Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the features I really liked about Ruby that is also present in Objective-C is the ability to forward messages.</p><p>In Ruby you can use the Forwardable module</p><pre>class LineItem<br>  extend Forwardable<br> <br>  def_delegators :@product, :sku, :name, :description, :price<br> <br>  attr_reader :product<br> <br>  def initialize(product)<br>    @product = product<br>  end<br>end</pre><p>In Objective-C you can do something like</p><pre>- (id)negotiate {<br>    if ([someOtherObject respondsTo:@selector(negotiate)]) {<br>	      return [someOtherObject negotiate];<br>    } else {<br>    	  return self;<br>    }<br>}</pre><blockquote>If you want to know more about message forwarding in Objective-C you can read <a href="https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtForwarding.html">Apple’s documentation</a></blockquote><p>This is one of those features that you rarely use but sometimes they help you avoid lots of boilerplate. In the case of Objective-C it leverages its run-time in order to dispatch messages dynamically. Something that cannot be done with pure Swift objects unless you made them inherit from NSObject.</p><p>Today I found myself in a situation when writing Swift code were message forwarding was a good solution to avoid some clutter and made me think about how could I accomplish something similar using pure Swift.</p><p>While working on <a href="https://github.com/guidomb/Portal">Portal</a>, a library that implements the <a href="https://guide.elm-lang.org/architecture/">Elm’s architecture</a> in Swift, I needed to implement the following protocol.</p><pre>public protocol ApplicationRenderer {<br>    <br>    associatedtype MessageType<br>    associatedtype RouteType: Route<br>    associatedtype NavigatorType: Equatable<br>    <br>    typealias ViewType = View&lt;RouteType, MessageType, NavigatorType&gt;<br>    typealias ActionType = Action&lt;RouteType, MessageType&gt;<br>    <br>    var mailbox: Mailbox&lt;ActionType&gt; { get }<br>    <br>    func render(view: ViewType, completion: @escaping () -&gt; Void)<br>    <br>    func present(view: ViewType, completion: @escaping () -&gt; Void)<br>    <br>    func presentModal(view: ViewType, completion: @escaping () -&gt; Void)<br>    <br>    func dismissCurrentNavigator(completion: @escaping () -&gt; Void)<br>    <br>    func rewindCurrentNavigator(completion: @escaping () -&gt; Void)<br>    <br>}</pre><p>The implementation that I was working on was the one responsible of rendering Portal’s view using UIKit. The conforming class is called <a href="https://github.com/guidomb/Portal/blob/d49495b517a78c50e4bd6eee62e9226f259d9208/Portal/UIKit/UIKitApplicationRenderer.swift">UIKitApplicationRenderer</a>. The tricky thing about implementing this protocol is that because of how UIKit works, all of its methods must be executed on the main thread. But the caller could already be running on the main thread or it may be running on a different thread.</p><p>My first attempt implementing this protocol looked something like this</p><pre>func present(view: ViewType, completion: @escaping () -&gt; Void) {<br>    	DispatchQueue.main.async { <br>	// code that presented the view<br>	}<br>}</pre><p>The first thing that I wanted to change was to avoid dispatching work to the main dispatch queue if the method was already being called on the main thread. So I added the following helper method</p><pre>fileprivate extension UIKitApplicationRenderer {<br>    <br>    fileprivate func executeInMainThread(_ code: @escaping @escaping () -&gt; Void) {<br>        if Thread.isMainThread {<br>            code()<br>        } else {<br>            DispatchQueue.main.async { code() }<br>        }<br>    }<br><br>}</pre><p>Then I made every method from the protocol call executeInMainThread . Every method looked something like</p><pre>func present(view: ViewType, completion: @escaping () -&gt; Void) {<br>    	executeInMainThread { <br>	// code that presented the view<br>	}<br>}</pre><p>I could have call it a day and move to the next task. But I didn’t like how the code looked like. By having to use a closure to implement the actual logic on each method I was using self all over the place. I didn’t like that. That is when I thought that it would be nice to be able to forward methods.</p><p>What I ended up doing was creating a new class, <a href="https://github.com/guidomb/Portal/blob/d49495b517a78c50e4bd6eee62e9226f259d9208/Portal/UIKit/UIKitApplicationRenderer.swift#L112">MainThreadUIKitApplicationRenderer</a> that implemented the ApplicationRenderer protocol assuming that all of its method will be called on the main thread.</p><p>The next thing was updating executeInMainThread to make it simpler to pass a block of code to execute that would only contain one method call by making the closure parameter @autoclosure. This would have the benefit of avoiding to have to wrap each method invocation with a closure.</p><blockquote>If you want to know more about @autoclosure and some cool ways of using it, check <a href="https://www.swiftbysundell.com/posts/using-autoclosure-when-designing-swift-apis">this</a> blog post.</blockquote><p>Finally all I needed to do was to add a forwardee property in UKitApplicationRenderer that would hold a reference to an object of type MainThreadUIKitApplicationRenderer to which all methods would be forwarded after making sure that the method invocation would be executed on the main thread. UIKitApplicationRenderer ended up looking something like</p><pre>public func render(view: ViewType, completion: @escaping () -&gt; Void) {<br>        executeInMainThread(self.forwardee.render(view: view, completion: completion))<br>    }<br>    <br>    public func present(view: ViewType, completion: @escaping () -&gt; Void) {<br>        executeInMainThread(self.forwardee.present(view: view, completion: completion))<br>    }<br>    <br>    public func presentModal(view: ViewType, completion: @escaping () -&gt; Void) {<br>        executeInMainThread(self.forwardee.presentModal(view: view, completion: completion))<br>    }<br>    <br>    public func dismissCurrentNavigator(completion: @escaping () -&gt; Void) {<br>        executeInMainThread(self.forwardee.dismissCurrentNavigator(completion: completion))<br>    }<br>    <br>    public func rewindCurrentNavigator(completion: @escaping () -&gt; Void) {<br>        executeInMainThread(self.forwardee.rewindCurrentNavigator(completion: completion))<br>    }</pre><p>Which I think reads better. Obviously compared to Objective-C or Ruby you still have to manually forward each method but that is something that may be solved by using some meta-programming with <a href="https://github.com/krzysztofzablocki/Sourcery">Sourcery</a>. I imagine that such solution would require defining a Forwardable protocol that could look something like</p><pre>protocol Forwardable {<br><br>	associatedtype ForwardeeType<br><br>	var forwardee: ForwardeeType { get }<br><br>}</pre><p>Then Sourcery could check all classes that conform to Forwardable and by using <a href="https://cdn.rawgit.com/krzysztofzablocki/Sourcery/master/docs/writing-templates.html">Sourcery source annotations</a> you could tell it which is the protocol that you want to conform to and Sourcery could then generate an extension with all the boilerplate necessary to forward each method. I leave that as an exercise for the reader.</p><blockquote>There is a similar example in Sourcery documentation to implement decorators using metaprogrammin. Check the example <a href="https://cdn.rawgit.com/krzysztofzablocki/Sourcery/master/docs/decorator.html">here</a>.</blockquote><p>Do you find this useful? Did you find yourself in a similar situation? What did you do then? Let me know by dropping a comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8223dd31e009" width="1" height="1" alt=""><hr><p><a href="https://medium.com/exit-0/message-forwarding-in-swift-8223dd31e009">Message forwarding in Swift</a> was originally published in <a href="https://medium.com/exit-0">exit(0);</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tips for better refactoring in Swift]]></title>
            <link>https://medium.com/exit-0/tips-for-better-refactoring-in-swift-4a43c08961cd?source=rss-2bc7f2f10e9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a43c08961cd</guid>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Guido Marucci Blas]]></dc:creator>
            <pubDate>Wed, 31 May 2017 14:32:34 GMT</pubDate>
            <atom:updated>2017-05-31T17:31:14.211Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the things I like the most about the Swift programming language is its type system. I think it has a good balance between “<em>main stream / industrial</em>” languages and more academic ones. Which makes it really approachable for new developers but also gives the more advanced ones a nice set of tools to be more productive.</p><p>What I also like is something that could be called <em>“typed-driven development”</em> (if such thing exists). Which basically boils down to define your types and function signatures and then trying to make every piece fit together until the compiler is happy. I found that by doing this, it makes implementing the actual logic quite straight forward.</p><p>Also having a type system and static checks come in really handy when you have to refactor code. The compiler becomes your first line of defense by pointing out all places that need you attention. Pieces that no longer fit together and need to be fixed.</p><p>Unfortunately not everything is as good as it could be. The Swift programming language is still very young and under heavy development. The compiler is not as mature as other compilers from languages that are ten or twenty years old. Nowadays it’s rare to see a compiler crash but not so long ago compiler crashes were a real issue that could throw away all productivity benefits Apple’s new language said it had.</p><p>Currently the mayor pain point regarding the compiler is diagnosis. Once you reach a fair amount of non-trivial code, very strange error messages will appear when you make a syntax error. Specially if you use lots of generics and type inference.</p><p>After a while of getting mad at the compiler and spending hours to understand what is the actual cause of the error (which usually requires trying to isolate the issue by reproducing the problem with the least amount of code possible), you learn how to read this cryptic and misleading error messages and know where to look at. You get a sort of intuition. Which is really hard to transfer to other team members.</p><h4>My last refactoring adventure</h4><p>Yesterday I found myself in a similar situation while I was refactoring some code in <a href="http://github.com/guidomb/Portal">Portal</a>. I wanted to delete a class which implemented a certain protocol and I also wanted to change the method signatures in such protocol.</p><p>My first attempt was to delete the class, change the method signatures and make some class in the library implement the modified protocol. The idea was that the compiler would tell me all the places that stopped working and needed my attention. Which worked for the most part until I reached to a point of not being able to fix some errors pointed by the compiler.</p><p>The errors made no sense at all. Probably some bug in the compiler or a bad diagnosis. But after spending hours trying to fix it, I gave up. I discarded all my changes, shutdown my laptop and went home.</p><p>Today I decided to tackle the problem with a different approach. The first thing I did was to copy-paste the protocol I wanted to modify and made a second version of it called ApplicationRenderer2. Then I updated the method signatures. Everything compiled. I was just adding a new type.</p><p>Then I made a class in the library implement this new protocol. This required a little bit of work because some of the logic that was in the class that I intended to delete needed to be copy-pasted into this class. After half an hour the project compiled again.</p><p>Next step was replacing every dependency on ApplicationRenderer to ApplicationRenderer2. Which yielded lots of compiler error that where pretty simple to fix.</p><p>Finally I deleted the aforementioned class, hit build and checked that everything worked as expected. The last step was deleting ApplicationRenderer and renaming ApplicationRenderer2 to ApplicationRenderer. The whole process took two hours.</p><h4>Conclusion</h4><p>Thanks to only making <em>additive</em> changes and then only adding a <em>destructive</em> change at the end of the refactoring process made me accomplish my refactoring task much more effectively. This is a strategy I intend to use more in my future refactoring endeavors. At least until Swift gets better diagnosis. Give it a try and let me know what you think.</p><blockquote>If you are curious about the actual change that I made you can check commit <a href="https://github.com/guidomb/Portal/commit/757a2a6f4be997c50f5155e3b63bc894abfc3ec4">757a2a6f4be997c50f5155e3b63bc894abfc3ec4</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a43c08961cd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/exit-0/tips-for-better-refactoring-in-swift-4a43c08961cd">Tips for better refactoring in Swift</a> was originally published in <a href="https://medium.com/exit-0">exit(0);</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Big brother, privacy issues and the quest of the Kurzgesagt]]></title>
            <link>https://medium.com/exit-0/big-brother-privacy-issues-and-the-quest-of-the-kurzgesagt-d90a6b37c635?source=rss-2bc7f2f10e9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d90a6b37c635</guid>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Guido Marucci Blas]]></dc:creator>
            <pubDate>Thu, 11 May 2017 16:38:07 GMT</pubDate>
            <atom:updated>2017-05-12T13:56:03.225Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*wHwDrJv01pYN1EuGUtqf6g.jpeg" /></figure><p>I wanted to share a weird experience that happened to me last night. I was at the office at the end of the day when a couple of my coworkers decided to go hang out at the apartment of one of them. Who happened to live right next to the office. I still had some work that I had to finish. I told them that it would only take one hour.</p><p>After I finished my work I joined them. When I arrived they were watching <a href="https://vimeo.com/149851847">this music video</a> and they were talking about how cool the video was and the awesome illustrations and animations it has. This remind me of a YouTube channel that publishes cool videos also with awesome animations explaining different things, generally scientific stuff, in less than a couple of minutes. The problem was that I couldn’t remember the channel’s name. All I remembered was that it had a weird name and kind of looked like German but I wasn’t sure.</p><p>The funny thing was that a couple of weeks ago I was also thinking about this channel but again I couldn’t remember the name. I also remembered that it was quite a while since the last time I saw a video from that channel.</p><p>I didn’t have my computer with me so I opened the YouTube app on my phone and started to scroll down the Home screen thinking that a video from this channel would eventually appear. After a couple of minutes I couldn’t find any video from this channel. I then tried looking on the Subscriptions tabs, again with no luck. I thought it was weird. I was sure that I saw a video from this channel a couple of moths ago. Maybe there was a bug on the YouTube app or maybe I hit the unsubscribe button by mistake.</p><p>I was very frustrated. At this point I wanted to find the channel just not to feel defeated by the YouTube app. I grabbed my coworker’s laptop, opened Google and typed <strong>best animated videos scientific knowledge</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SjvjM3vngNi13rxYSAAIVg.png" /><figcaption>Google search result</figcaption></figure><p>I clicked on <a href="https://www.geekwrapped.com/posts/youtube-science-rockstars-shows">The 50 Best YouTube Science Channels | GeekWrapped</a> and then I finally found it. The name of the channel was <a href="https://www.youtube.com/channel/UCsXVk37bltHxD1rDPwtNM8Q">Kurzgesagt — In a Nutshell</a>. I felt relieved knowing that I defeated evil YouTube on the quest of finding <strong>Kurzgesagt</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fu2A8WD7r2RCUA4wiARPMw.png" /><figcaption>The 50 best YouTube science channels screenshot</figcaption></figure><p>First of all let me tell you that If you reached this far I’m quite surprised. I am either a decent writer or you really like to procrastinate. You might be wondering what’s all the fuss about finding a YouTube channel you couldn’t remember the name. This is where the “<em>cool</em>” part begins.</p><p>I went back home for dinner with my girlfriend. I was eating when I noticed that I’ve got a new email. I’m quite of a zero inbox freak so I couldn’t avoid doing a quick check on the Mail app. I opened the app and there it was, an email from YouTube with the subject <strong>Kurzgesagt — In a Nutshell: “The Last Light Before Eternal Darkness — White Dwarfs &amp; Black Dwarfs” and more videos</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*9ugHx7oW_kEilmETOg5m2A.png" /><figcaption>Email from YouTube</figcaption></figure><p>I thought WTF YouTube. How could you send me an email about the latest Kurzgesagt videos after moths of not sending me any videos from them. Even after I spent a few minutes on the YouTube app searching for this channel without having any luck. Why now? I felt like big brother was watching me.</p><p>My girlfriend, who was already upset because I was checking my email at dinner saw that I was looking at my phone like something terrible had happened and asked me what was the big deal. I told her about what happened earlier that night and what a big coincidence was that I’ve got this email from YouTube.</p><p>I told her that I was thinking that Google / YouTube knew that I was looking for <strong>Kurzgesagt</strong> but I didn’t know how. I’ve never typed anything on my phone and didn’t visit the channel’s page in my phone after finding it on my coworker’s laptop. Remember I used my coworker’s laptop to search for the channel and I didn’t login into any service in that computer. So how could they know!!??</p><p>It could all be a coincidence but the conspiracy theorist in me refused to believe it. That is when my girlfriend said <em>“well, Google does know your current location and also knows your coworker’s location”</em>. That was actually true and the engineer in me was desperate to know how Google could know that I was looking for or might be interested in the <strong>Kurzgesagt</strong> channel. Here are the facts:</p><ol><li>Google knew my last location because I use Google on my computer and I gave it access to my location. The office is right next to my coworker’s apartment so the distance difference could be inside the accepted location error range.</li><li>I use quite a few Google apps on my phone and most of them have access to my location while I use them.</li><li>Google has access to my phone’s microphone. I explicitly have to press the mic button for Google to be able to record audio but technically they could turn my mic on without me noticing it. I choose to discard this option for now just because is too creepy and I don’t have strong evidence. Also it would require quite a sophisticated natural language processing to be able to infer that I was looking for the <strong>Kurzgesagt</strong> channel. I don’t think the tech is there yet.</li><li>They know when I opened the YouTube app and they know I scrolled quite a few pages both on the Home and Subscriptions screens. It is reasonable for them to infer that I was looking for something and because I didn’t watch any video nor I visit any of the channels’ page I failed to find what I was looking for.</li><li>Google has all this same data about my coworker&#39;s behavior because we both use Google’s products.</li><li>Google could infer that I was hanging out with my coworkers because all of our GPS and interactions with Google products through our phones and laptops tell it we were in the same physical location.</li></ol><p>With all this information Google could infer that I might be interested in watching videos from <strong>Kurzgesagt</strong> because one of my coworkers visit the channel’s page on his computer while I was with him.</p><p>Again it could also be big coincidence. I cannot prove this but I am sure that Google has access to all this data, the computing power and the IA technology to be able to infer this and send me such email. It kind of freaks me out a little bit. I mean, I am software engineer. I know how this works and how such algorithms could be implemented. I know companies like Google probably do this things (and they probably do more creepy stuff) but when you start thinking about it and when you notice it in your daily life I couldn’t help feeling a little violated.</p><p>I’ll probably forget about it later this week but I think most people don’t realize about this sort of things. I think it’s something that should be discussed more often. The problem is that I don’t know what companies like Google know about me. We also know that governments and companies don’t hold the high moral grounds and have systematically violated people’s privacy rights in the name of profitability or <em>“for the sake of protecting their citizens”</em>.</p><p>The world we are living in it’s getting more complex every day. The line to separate what’s wrong or right, what is a product feature or a violation of people’s privacy it’s becoming more blurry. All I know is that we should be talking more about this and that as technical people how know more about this stuff and are the ones implementing this things we should start questioning the implications of our work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d90a6b37c635" width="1" height="1" alt=""><hr><p><a href="https://medium.com/exit-0/big-brother-privacy-issues-and-the-quest-of-the-kurzgesagt-d90a6b37c635">Big brother, privacy issues and the quest of the Kurzgesagt</a> was originally published in <a href="https://medium.com/exit-0">exit(0);</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Usage Driven Development]]></title>
            <link>https://medium.com/exit-0/usage-driven-development-a25cc5c50cd0?source=rss-2bc7f2f10e9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a25cc5c50cd0</guid>
            <dc:creator><![CDATA[Guido Marucci Blas]]></dc:creator>
            <pubDate>Thu, 13 Apr 2017 20:05:56 GMT</pubDate>
            <atom:updated>2017-04-13T21:17:54.651Z</atom:updated>
            <content:encoded><![CDATA[<h4>A brief story of the tools I wish I had</h4><p>Recently at <a href="http://wolox.co/">Wolox</a> I’ve been working on a Swift library to help us develop applications more rapidly but also having a solid architecture that produces maintainable code. You’ll probably hear more about this in a future post.</p><p>Like most software projects, this one started as a rough idea that was rambling inside my head for a long time which eventually manifested as a prototype developed over a weekend. After a couple of days hacking, I had a first version of the library that was able to demonstrate its potential and kind of worked for basic iOS applications. So I decided to start refactoring the code, clean it up and start adding missing core features.</p><p>Soon I realized that I was starting to build a relatively complex code base that I knew would have to go over several iterations and refactor cycles until the APIs were polished enough to be able to be used by the widely range of application we build for our clients at Wolox. Although I was able to move fast and add feature after feature, I started to fear that I would hit a wall because I was (and still am) not writing any tests (yet).</p><p>Being a guy who always preached about <a href="https://en.wikipedia.org/wiki/Test-driven_development">TDD</a> and <a href="https://en.wikipedia.org/wiki/Behavior-driven_development">BDD</a>, this was a big issue for me. But I’ve also learned the hard way about committing too early to writing tests for rapidly-changing and unstable code. Tests are also code that has to be maintained and when you are designing a new API that works for you but that also needs to work for a variety of other cases that you cannot even imagine, the maintenance burden can slow you down really hard. That is why I decided that I was going to commit on testing after I was confident that the APIs were stable enough and no mayor changes were going to be needed in the foreseeable future.</p><p>Strong BDD advocates would tell me that I am crazy. That I should be driving the design of my API by writing test that would make me discover how those APIs should look like. Although I agree with such approach, I found that discovering the library’s API was much more effective by writing a real application. Just start working on a new app and write the interface you wish you had and then implement it. My <a href="http://blog.cleancoder.com/uncle-bob/2014/12/17/TheCyclesOfTDD.html">red-green-refactor</a> cycle became:</p><ol><li>Scaffold the new app feature, discover the API by watching all the compiler errors for types or function that don’t exist yet.</li><li>Implement those missing types or functions and make the project compile.</li><li>Once the feature is working see if you can refactor the code, generalize it or clean it. Make sure that the feature is still working.</li></ol><p>Applying this same approach in dynamic languages like Javascript or Ruby can be way harder and BDD in those language make more sense. You have to compensate not having a type-system and a compiler that tells you what you have broken after a refactor cycle. This is not the case for Swift. Sure, there are invariants that cannot be expressed in the type-system but in my experience so far those cases can be easily spotted by running the application and doing a quick check.</p><p>I know that once the code base reaches certain size and complexity this approach will no longer be valid but it helped me move faster at the beginning. That is why I am preparing for the next phase and the reason I am writing this blog post. Once I decide that the APIs are stable enough and more people starts depending on my library I need to start having strong code coverage, at least for the most important pieces and execution paths. This is were I would like to have better support from my tooling.</p><p>The following are a couple of tools I wish I had</p><p>A text editor / IDE plugin or chat bot that tells you which pieces should be tested, ordered from the highest to lowest priority. The priority is calculated based on the <strong>source file churn</strong> combined with <strong>runtime execution information</strong> of which code paths or functions are executed more often.</p><blockquote>Runtime information might be hard to collect without having significant performance impact. Maybe by instrumenting LLVM byte code by inserting functions call to a stats collector library every time there is a code jump or an execution branch, e.g., function calls, function returns, if statements. I am not sure if LLVM exposes a plugin mechanism that would make such extension relatively easy to implement</blockquote><p>Files with low churn that contain code that is executed more frequently means such code is stable and probably critical or that atleast is shared by most feature flows.</p><p>Files with high churn that contain code that is executed more frequently in (<em>in development builds</em>) means such code is actively being worked on and there for it might be wiser to test it once the API has been stabilized and the use case validated.</p><p>Crash reports is another good source of information to take into account and decide where and when we should put our attention.</p><p>It is extremely important that in order for such tool to be useful it must be integrated with your IDE and <strong>it should provide information in real time or when the user decides to “augment” her editing experience</strong>. Contextual information could be provided by the IDE’s UI when the user holds the course after a couple of seconds over a block of code. More frequent execution paths would be highlighted with a stronger color (by changing highlighted area alpha’s property) than less frequent ones. Execution paths that contain lines that are part of a crash report’s stack frame can be highlighted in red.</p><p>If the application is using an architecture like the <a href="https://guide.elm-lang.org/architecture/">Elm’s architecture</a> or something like <a href="http://redux.js.org/">Redux</a> then when a crash is detected the current state and the last <em>n</em> messages are attached to the crash report. The execution path that processes the messages and the state that generated the crash are highlighted by the IDE in real time when the crash occurs or when the user decides to debug a specific crash report.</p><p>Going one step further, each message that is processed by the application’s update function could be sent to a cloud service that processes the message in order to analyze and gather metrics from the code execution path. This provides real time runtime execution information without affecting performance and consuming user’s CPU because replicating the message is off-loaded to a background queue and the actual cost of instrumentation is paid by the backend server. This strategy increases data consumption and surely there are a lot of things that I haven’t though but should be technically possible now that Swift can run on Linux.</p><p>If someone wants to work in something like this or if such tools already exist please let me know. In the mean time I think I’ll have to settle with intuition and some basic code coverage reporting.</p><p>I think that a lot can be done by making developers more productive. People think that in a near feature AI would take over developers jobs and machines will start writing code by themselves. I think such future is still pretty far away. What I do think is that the progress in computing power and AI could be used to develop better and smarter tooling which provides contextual real time information to help developers make better decision. What do you think?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a25cc5c50cd0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/exit-0/usage-driven-development-a25cc5c50cd0">Usage Driven Development</a> was originally published in <a href="https://medium.com/exit-0">exit(0);</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The dawn of the REST API — Part 2]]></title>
            <link>https://medium.com/wolox/beware-of-backward-compatibility-9fd3fe8961ba?source=rss-2bc7f2f10e9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fd3fe8961ba</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Guido Marucci Blas]]></dc:creator>
            <pubDate>Thu, 16 Feb 2017 18:20:59 GMT</pubDate>
            <atom:updated>2017-02-16T18:26:07.360Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*492QYozfJW94QnpuuzLLdQ.png" /></figure><h4>Beware of backward compatibility</h4><p>In <a href="https://medium.com/wolox-driving-innovation/the-dawn-of-the-rest-api-part-1-558081889ed6">part 1 </a>of this post, we covered how we work here at Wolox and the different stages of the development process where parallelizing tasks is highly recommended. In part 2 we will review the various drawbacks of having different teams working in parallel and the cost of maintaining a REST API.</p><p>Generally speaking, the parallel development process works quite well, however, there is still room for improvement. For instance, sometimes the backend team starts working on endpoints that the mobile team is not using at that given moment. When the mobile teams start working on the screen that requires those endpoints they realize that some changes need to be made to the endpoint to improve performance, load time or user experience in general.</p><p>This also works the other way around. For example, the mobile team defined the perfect endpoint specification for the use cases they were working on but then the backend team realizes that in order to provide the JSON and the endpoints the mobile team wants they have to sacrifice performance (by doing extra joins in a table or making the JSON payload too big).</p><p>The problem gets worse when you get to the point of having to re-architect part of your application because one endpoint needs to be super fast leading you to start to denormalize tables. This usually translates into a more complicated write or updating patterns were you’ll probably need to trigger background jobs to update all the denormalized entities. This means more error logic and ensuring that in the case a is a server down, background jobs are not lost. If these are not monitored closely they can escalate very quickly and seriously impact your delivery date.</p><p>Another headache in the process is backward compatibility of the API. If you haven’t shipped your first public version this problem is not as significant of an issue as there aren’t any users using the application. However, it is still a problem for the different teams. When you have a QA department that is testing different versions of the mobile apps, suddenly features that were supposed to work stop working. This usually happens because the backend team introduces breaking changes publishing them with the staging server while different versions of the mobile apps in the queue for QA depend on the previous version of the staging server.</p><p>This problem can be solved by maintaining different versions of the API or by having several staging servers. Note, this can make the development process more tedious and increments development costs by having to allocate more server resources. What ends up happening is either the backend breaking change is rolled back from the staging server or all pull requests for the mobile applications that depend on the old version of the server get updated to support the new API specification.</p><p>The moment you made your app public with active users you cannot allow breaking changes of the API to break running client apps. If your user base is still small you can force users to update to the latest version but we recommend deploying a mechanism to do this in advance. If you cannot afford to do this then you must support different versions of your API until the majority of your users have updated to the latest version in which case you can remove the old version.</p><p>This is not an easy task. You server logic becomes more complicated because you have to contemplate every running version of the API. You have more code, which means more source of bugs and depending on the life span of API version you have more documentation to maintain. All this translates to more developer hours, less time to introduce new features and more overall costs.</p><p>Also, you have to keep in mind that the more software you build the more software you have to maintain. Having your own backend servers comes with maintenance. The amount of time that you expend maintaining those servers will vary on how unique the web service your are building is. Chances are that if you are using Heroku to deploy a small web service that does CRUD operations on top of a Postgres database and has some business logic, then you won’t spend much time on server maintenance. In the case that you have to provision your own hardware (whether it is virtual or bare metal), and you have more complex backend services, you will have to spend more time doing maintenance work.</p><p>Either way, sooner or later you will have to optimize the service configuration, check that your process doesn’t have any memory leaks, that your hard disk doesn’t run out of space, that your database has the right indexes configured, and that the majority of the hot queries run on memory. To make sure everything is working as expected you will need to have to configure monitoring services, configure CDN for your static files, monitor the average response times of your endpoints, find out why a particular JSON response is taking too long to be serialized or why your sidekiq process has consumed all the available database connections.</p><p>Once your backend starts to grow and you don’t use services like Heroku, which lets you deploy with a git push, that is when then you have to worry about tooling. If you want to iterate faster you have to deploy as fast and as many times as possible. That is what the whole continuous integration thing is about. Deploying a new version of your services should be as simple as committing new changes to your git repository. The same goes for rollback, reverting a change should be as easy as deploying one.</p><p>As you can see developing a backend service is not just about coding. There are a lot of operational issues that one must consider. There are times where it is important to have a backend that does a lot of business logic and times where it is not as crucial. If you can do most of the work in the client and make your servers as dumb as possible then scaling your app to handle more users will be simpler. Of course, rich clients have their own drawbacks, like having to code every business logic multiple times when using native mobile technologies or having to go through a review process every time you want to deploy new changes. But there are ways to mitigate or at least minimize those problems.</p><p>If your apps make a lot of API calls just to store and retrieve data and sometimes trigger some background processing job like an image or sending emails it may be time to reconsider having your own custom backend service. The good thing about not having a backend service is if your app starts doing really well and you get more traffic day after day than scalability is not going to be an issue for you or at least you don’t have to worry about provisioning more servers or sharding your database.</p><p>To add more issues to the mix, when you have more teams, you have more people and more people means more coordination. Which at the end of the day means more time and money. If you are a startup trying to get your first MVP out in the market, chances are you are running on a tight budget. Being able to build the same product with fewer people gives more room to breathe in case you need to pivot.</p><p>All these pain points led me to the conclusion that maybe creating a custom REST API to power mobile apps is not the best solution. Don’t get me wrong REST APIs are great, and if you want the community to be able to build other products on top of your service, they are even better.</p><p>Great APIs require excellent documentation, clear backward compatibility, and deprecation policies. I never get tired of the reference <a href="https://developer.github.com/v3/">GitHub API</a> as one of the most well- designed APIs. Like anything else in life, decisions come with trade-offs and there is no rule of thumb or a magical solution but if you are a startup running on a tight budget with a potentially high viral mobile only product then using BaaS may be the best fit for you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fd3fe8961ba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wolox/beware-of-backward-compatibility-9fd3fe8961ba">The dawn of the REST API — Part 2</a> was originally published in <a href="https://medium.com/wolox">Wolox</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A short guide for IoT startups]]></title>
            <link>https://medium.com/exit-0/a-short-guide-for-iot-startups-a96e13485fc9?source=rss-2bc7f2f10e9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a96e13485fc9</guid>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[hardware]]></category>
            <dc:creator><![CDATA[Guido Marucci Blas]]></dc:creator>
            <pubDate>Tue, 31 Jan 2017 08:00:00 GMT</pubDate>
            <atom:updated>2017-02-01T18:42:03.220Z</atom:updated>
            <content:encoded><![CDATA[<p>I was asked to give a talk targeted to investor that didn’t have experience investing in IoT startups. Although I’m far from being an expert on the subject I think I have some notes I can share after 3 years of working on a hardware startup.</p><p>Most of the following applies to a <em>subset</em> of hardware startups, nowadays called <strong>IoT</strong> or <em>internet of things</em>. Which in most cases referrers to consumer electronic devices that are either connected to the internet or to some sort of network of devices. Things like smart light bulbs, smart lighters or connected devices to grow plants and vegetables. Although there are processes and advice that applies to IoT startups and also more “<em>old-school</em>” hardware startups. Is not the same to build a smart light bulb as having to build an autonomous robot that can navigate an unknown location.</p><h4>Software startups v.s. IoT startups</h4><p>Although most of the processes and methodologies involved in developing a product on a software startups also apply to IoT startups, there are some differences that need to be noticed.</p><p>I think that is important for someone that is entering the world of hardware startups for the first time to know the different stages involved in developing a hardware product and the different risks that they may face during this process.</p><p><em>I recently found another blog post that also talks about the process of building a hardware product. After reading this one take a look at </em><a href="https://backchannel.com/how-to-build-a-hard-tech-startup-4028d22f2c91#.khrghbt85"><em>this</em></a><em> other one.</em></p><h4>Hardware startup product stages</h4><p>Most hardware startups and in particular IoT startups go through a set of stages when they develop a product. Each stage has different goals and it only makes sense to move forward to the next stage once all or most of the hypothesis for that stage have been validated. This stages usually are:</p><ul><li>Idea</li><li>Proof of concept</li><li>Prototyping</li><li>D.F.M. or design for manufacture</li><li>Production</li></ul><h4>Idea</h4><p>This stage consists mostly of working on your idea, defining the value proposition and your main hypothesis. By the end of this stage you should have a clear idea of what problem you are trying to solve and a rough idea of how you will solve that problem. It is recommended to work on some design concepts, at least at a very high level of how the product would look like and it is useful to have a 3D render of the product. This helps a lot to communicate and visualize your product in order to talk with potential angel investor or to recruit some co-founder or first employees. It is also a good idea to create a landing page and start getting some feedback from potential users.</p><h4>Proof of concept</h4><p>This stage allow you to validate that a rough concept can be made and that the technology is mature enough, at least to demonstrate your product’s core functionality. At this stage engineers usually use development boards and prototyping tools like <a href="https://www.arduino.cc/">Arduino</a>, <a href="https://www.raspberrypi.org/">Raspberry PI</a> or integrated circuit boards that already come with things like a micro-controller, <a href="https://en.wikipedia.org/wiki/Inertial_measurement_unit">IMU sensors</a>, Bluetooth or WiFi chips. Aesthetics and cost is generally not a concern at this stage.</p><p>By the end of this stage you can look for seed investment to be able to go through the next stage. Hopefully you have a working proof of concept that can demonstrate your product’s core value proposition and with a strong pitch you can convince investor to bet on your startup.</p><p><em>Sometimes it happens that the technology is available but the product cannot be launched because it either fails to satisfy other constrains like size, battery life or production cost is too high. Being able to reach this stage does not mean that all risks have been mitigated. Usually is the other way around, the most risk adverse part is yet to come.</em></p><h4>Prototyping</h4><p>After validating that the product’s core functionality can be built you move to the prototyping stage. This stage may consiste of several iterations of the product where you take into consideration production costs, the product’s form factor, aesthetics, materials, etc.</p><p>Generally speaking this stage involves the design and manufacture of custom <a href="https://en.wikipedia.org/wiki/Printed_circuit_board">PCB</a> and a case where that PCB will be held. Engineers usually produce 5 to 20 pieces of each design variation or prototype to test its performance, robustness, different materials and the general user experience. It its recommended at this stage to test the different prototypes with “real” users to try to get as much feedback as possible.</p><p>This is a critical a stage for an IoT startup because at this stage is when you lock down how the final product will look like, how it will behave and its core features. That is why is so important not to move forward until you have validated that the prototype you have built has a real value proposition that users are willing to pay for. Also at this stage you will have a pretty good estimate of the final production cost. Although that will be refined in the next stage, at this moment you can estimate how much money you will need for the following stages and you can commit to a retail price.</p><h4>D.F.M. or design for manufacture</h4><p>Here is where you start preparing the design to be able to be manufactured at medium or large scale. This process usually involves talking with factories to know if they are capable of building your product in a cost effective way. This stage may require minor tweaks in the design or changing some components or materials in order to make the manufacturing processes easier. Here is where you also learn if your product will require certain certifications in order to be sold in your target market.</p><p>It is recommended to hire an external consultant with experience on manufacturing if this is the first time your team is going through this process. Making sure this stage is well executed is critical for the success of the product. A lot of hardware startups underestimate this stage thinking that going to production from the prototyping stage is just a matter of making more units. It is not. The manufacturing process required to build 20 units is completely different from building 100, 1,000 or 10,000.</p><p>Finally, here is when you can lock down the final production costs and know for sure what your retail price and revenue will be. This is the safest stage to start taking pre-orders either by accepting them through your web page or by launching a crowdfunding campaign in sites like <a href="https://www.kickstarter.com/">Kickstarter</a> or <a href="https://www.indiegogo.com/">Indiegogo</a>. Take into account that in order to move to the next stage you will need to be at a point of having to call the factories and tell them to start building your product which will require more cash upfront. Some startups raise another investment round here, something between a seed and series A round. Another options is to launch a crowdfunding campaign then, if the campaign is successful, you may still want to raise a round but in this case (depending of how successful the campaign was) you will stand on a different position.</p><h4>Production</h4><p>This stage varies in complexity depending on the amount of units that will be produced. Different orders of magnitude usually require different production techniques. In general at this stage you have to coordinate with the factory or factories. Once this stage has been reached you cannot make any changes to the product except maybe some minor tweaks here and there to make the production process smoother or to avoid any possible performance problems. Things like replacing non-critical electronic components, minor layout changes on the P.C.B. or shaving a couples of millimeters from the case’s mold.</p><p>Once you are sure everything is ready you will need to commit on tooling. This is why this stage requires quite a lot of cash upfront. In general, most IoT product have some sort of <a href="https://en.wikipedia.org/wiki/Injection_moulding">injection molding</a> case. Which means that a factory will need to produce a mold first. This process varies depending on the complexity of the case, the technique used and the materials but it usually takes 3 to 4 weeks. Once the mold is ready a pre-production run is made, around 150 units. This gives you the chance to fix minor issues, shave some rough edges and do some intensive end-to-end testing.</p><p>Some startups use this period and the pre-production units with beta tester who usually are your evangelizer, first users that are really engaged with your product. Getting feedback at this stage is also really important because you can polish some processes like unboxing for example. Check that all the installation instructions are clear. If you provide some sort of software like a mobile application, you can check that the first user flow goes as smooth as possible, that users are able to connect with your device and know how to use it.</p><h4>How much money do you need to reach M.V.P?</h4><p>Another key difference between pure software startups and IoT startups is the amount of cash they need and the time it takes to reach M.V.P. Each of the previous stage requires a significant amount of money and iteration times are way longer than on a pure software product.</p><h4>Cash and time per stage</h4><ul><li><strong>Idea:</strong> This could take <strong>1 to 2 months</strong> and maybe around <strong>5k USD</strong> if you need to hire a free lancer to do some sketches, 3D renders or a landing page.</li><li><strong>Proof of concept:</strong> Around <strong>15k USD</strong> and <strong>1 to 3 months</strong>.</li><li><strong>Prototyping:</strong> Assuming 3 prototypes iterations with custom P.C.B. and some sort of casing using <a href="https://en.wikipedia.org/wiki/Numerical_control">CNC</a> or 3D printing. Around <strong>150k USD</strong> and <strong>6 to 8 months</strong>.</li><li><strong>D.F.M.:</strong> Around <strong>3 months</strong> and <strong>60k to 90k USD</strong></li><li><strong>Production:</strong> Depending on the amount of units, but lets say a first production run of 500 to 1000 units. Around <strong>60k USD</strong> and <strong>2 months</strong>.</li></ul><p>For what I observed so far and IoT startups usually takes <strong>at least 18 months</strong> to go from idea to production, assuming all stages are executed correctly and there any mayor problems. Again this varies a lot depending on the complexity of the product but <strong>2 years</strong> and <strong>350k to 500k USD</strong> investment seems to be the bare minimum.</p><h4>What about risks?</h4><p>An IoT startups is subject to the same risks most startups face, being the most important building the wrong product and running out of money. But if you come from a pure software startup background there are some things that you should probably consider.</p><h4>Certifications, patents and taxes</h4><p>Most probably if your product requires some sort of wireless connectivity like Bluetooth or WiFi most likely you will have to certify your antenna design. If your product doesn’t have the required certifications you won’t be able to sell it in some markets. This regulations depend on each market, selling a product in Europe may require different certifications than in the U.S. Another option instead of having to go through the certification process is to use pre-certified modules. For example there are modules that you can include in your custom circuit that already include a Bluetooth chip and an antenna. This modules have already been certified by the Bluetooth consortium. This may increase your unit cost but frees you of having to certify your product. Which certifications are needed depends on the specific of your product but take into account that they take time and money. Is usually safe to add <strong>3 weeks</strong> and <strong>5k to 15k USD</strong>.</p><p>Another thing to consider is patents, which also applies to pure software startups. This could add another <strong>12k to 20k USD</strong> to your budget. Same as with certifications, they change depending on where you want to sell your product. There are agreements between countries, for example in the case of the EU you only apply for a patent that is valid on all members of the EU.</p><p>Also when building a hardware product, chances are that you would require different components or parts that you may not find in the country you are doing the R&amp;D. Depending on the regulations of the country you are based on, importing this components may incur in import feeds that could significantly increase your development costs. Not to mention the bureaucracy and delays.</p><h4>Cash flow</h4><p>Running out of cash is something that all startups have to be concerned of but this problem accelerates with hardware startups due to the amount of cash needed for product development. You not only have to pay for engineers salaries and external consultants fees but you have to pay for tools, materials and everything needed to build your prototypes. Not to mention the required tooling once you are in the production stage.</p><p>The risk of running out of cash increases when you are about to make your first production run. Factories usually don’t give you credit, you have to pay them up front both for the tooling costs and the production cost per unit. You pay for product that you will be able to sell and cash in at least 3 months in advanced. Other things can add up quickly, like import / export fees, storage and shipping fees.</p><p>After you build a relation with your factory they may give you credit and some times they do it the first time you work with them if they like your product or see some strategic value of working with you.</p><h4>Design and manufacturing issues</h4><p>A couple of things regarding product design that shouldn’t be overlooked:</p><ul><li>Products that have mechanic and moving parts are usually harder to build and add more risk to the manufacturing process.</li><li>Things like shock-proof and water-proof is not something to take lightly. If your product needs be to water-proof and this is the first time that you are working on a product like this, hire an external consultant at least to review your design and help you with manufacturing. There are quite a few cases of startups failing at this promises adding significant delays or even having to recall product that didn’t work in the environment there were supposed to.</li></ul><h4>Fulfillment of physical goods</h4><p>Again, another area that most people that come from a pure software startup background don’t know is dealing with an actual physical product.</p><p>Building a product is just one of the many things you need to do. After the product is built, you need to sell it. This is where you need to think which are your distribution channels. Again, this changes depending on the product but if you are selling a consumer electronic type of product you probably want to be on the shelf of most well known retailers. Getting access to big retail chains is not easy. They usually get products that sell well and are proven. They tend to place big orders and expect them to be fulfilled on time. They even put huge penalties for each day you fail to deliver. You’d better be prepared and have all your processes fine-tuned before going for the retailers like Walmart, Target or Best Buy, if your target market is the U.S.</p><p>That is why startups usually start by first taking pre-orders on their site or through a crowdfunding campaign, then they move to online orders only and they start working on distribution deals. Take into account that if your product needs to be sold on local shops, going shop by shop across a whole country for usually low volume orders could be close to impossible for startups with low budget and a small team. That is why selling your product to distributors alleviates this problem because they take bigger orders and they deal with managing stock and getting the product to their network of retailers. Remember that managing product stock costs money, you have to store your product somewhere and the logistics behind distribution it not easy.</p><p>The downside of retailers and distributors is that they take a significant share of the retail price, usually between <strong>40% and 60% of the retail price.</strong> Selling your product through your website gives you higher margins and chances are that at the beginning you won’t be taken a lot of orders. You can deal with shipping yourself and once it gets out-of-hand you can hire a service that helps you with order fulfillment. Some factories even have deals with fulfillment centers (in the U.S.) and they can ship the product directly to them. No need of having to maintain stock.</p><h4>Intellectual property</h4><p>Intellectual property is a concern specially when dealing with Chinese factories. There are tons of cases of factories coping and selling the product they are making for their customer. After all they know how to make it. Sad news is that there isn’t much you can do about it and to be honest is not worth it.</p><p>Chinese factories won’t sign you and <a href="https://en.wikipedia.org/wiki/Non-disclosure_agreement">NDA</a> or a non-compete, unless your are Apple. Instead of wasting a lot of money on lawyers and patents the smart thing to do is building a company around a product that does not depend on the revenue that it gets by selling the hardware only. Also hardware is getting cheaper and cheaper and production costs are decreasing year after year. Chances are that your product will get commoditized eventually.</p><p>That is why it is recommended to use the hardware as a vehicle to unlock certain features and develop other revenue streams. For example if your hardware cannot do much without a companion mobile application, then factories will need to build their own copy cat of your app. Sometimes the technology behind the product is not that cutting edge or innovative but the way it is applied and how is marketed it is. Building a strong brand and providing extra features or value to the hardware through a software component is the safest way to protect you from being copied.</p><h4>Revenue streams</h4><p>One of the most critical parts of a hardware startup to ensure its survival is to know your revenue streams and your costs. Getting the right retail price is really important and is a decision that should be taken with actual information. Pricing is not trivial and users may be willing to pay more o less depending on factors such as how they perceive your brand, the type of product you are selling or the value you are providing.</p><p>A good rule of thumb to set a base retail price for your product is to <strong>multiply the unit cost by 4</strong>. This includes actual production cost which you can infer from the <a href="https://en.wikipedia.org/wiki/Bill_of_materials">BoM or bill of materials</a> plus shipping and packaging costs. This rule gives you enough margin to pay for distributors, retailers, payment processing feeds and some refunds.</p><p>As mentioned before when we talked about intellectual property, it is important that you build other sources of revenue. Even old-school traditional hardware companies are adding services, usually through software and in many cases startups don’t make money by selling hardware. They use hardware as way to enable their business and the real money comes from software. It is even a common practice for startups to sell their hardware at a price just to meet the costs or even under the production costs because that is way to improve adoption and increase the entrance barrier for competition. This of course is possible if the hardware enables them to activate other sources of revenue.</p><h4>Conclusion</h4><p>I know, this looks a little bit scary but let me tell you that going through this process is really fun. As an entrepreneur you will need to learn how to wear a lot of new hats. As a investor entering the hardware world for the first time, is good to know the difference between building a hardware and a software product and set the right expectations.</p><p>The hardware community is awesome and there is a lot of material out there. Most founders that have gone through this process would love to share their experience and help newcomers. Don’t be afraid of asking.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a96e13485fc9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/exit-0/a-short-guide-for-iot-startups-a96e13485fc9">A short guide for IoT startups</a> was originally published in <a href="https://medium.com/exit-0">exit(0);</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Avoiding bugs and improving documentation through the type system]]></title>
            <link>https://medium.com/exit-0/avoiding-bugs-and-improving-documentation-through-the-type-system-61d2695aceb6?source=rss-2bc7f2f10e9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/61d2695aceb6</guid>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Guido Marucci Blas]]></dc:creator>
            <pubDate>Fri, 06 Jan 2017 20:32:28 GMT</pubDate>
            <atom:updated>2017-01-06T21:33:58.599Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to avoiding bugs and improve documentation by using the type system</h3><p><em>Always try to reduce functions and methods domain. Improve documentation by using narrower types which enforce pre-conditions. Give the compiler more information. Watch </em><a href="https://www.youtube.com/watch?v=DU7Je1rdXk0"><em>this</em></a><em> video.</em></p><p>Today I was reviewing a pull request and I found the following piece of code that was added</p><pre>public final class UserSessionService {<br><br>	public init(withTimeout timeout: NSTimeInterval) {<br>		// Initialization logic<br>	}<br><br>}</pre><p>Although the code was working fine and followed all of our best practices I felt that there was something there that could still be improved. The first thing that triggered this thought was actually a “cosmetic” issue. I thought, what if the parameter’s label, instead of being <strong>withTimeout</strong> is changed to with. That change would imply that creating a new instance of <strong>UserSerssionService</strong> would change from</p><pre>let userSessionService = UserSessionService(withTimeout: 10)</pre><p>to</p><pre>let userSessionService = UserSessionService(with: 10)</pre><p>Clearly not a good idea. Although it is less verbose, it makes understanding what is actually happening way harder. What does it mean to create a user session service <strong>“with 10”</strong>. The original solution at least clarifies that the given number is a timeout. It reads as, “create a user session service with timeout 10”. But the problem with it is that is not much clearer than that. A timeout for what? My next thought was to suggest changing the initializer to</p><pre>public init(withRequestTimeout requestTimeout: NSTimeInterval)</pre><p>Which clarifies that timeout is related to the requests this service makes. <strong>UserSessionService</strong> exposes methods to login and sign up. The thing with this solution is that it’s worse than the original one regarding the length of the label. Obviously not a big deal, but this is what was bothering me in the first place.</p><p>If you read <a href="https://swift.org/documentation/api-design-guidelines/#naming">Swift’s API design guidelines</a> didn’t help much either. Except from some tips like</p><blockquote>func move(from start: Point, to end: Point)</blockquote><blockquote>Choose parameter names to serve documentation. Even though parameter names do not appear at a function or method’s point of use, they play an important explanatory role.</blockquote><p>and</p><blockquote>func move(from start: Point, to end: Point)</blockquote><p>I realized that the problem was actually with type of the parameter, <strong>requestTimeout</strong>. If the type had a more descriptive name the method signature could read better and be less verbose. For example</p><pre>typealias RequestTimeout = NSTimeInterval<br><br>/// Return a `UserSessionRepository` that limits login and sign up<br>/// requests to the given `requestTimeout`.<br>public init(with requestTimeout: RequestTimeout)</pre><p>This “felt” better but it had the same issue as not being clear enough when used. Which led me to change the type alias to a concrete type.</p><pre>struct RequestTimeout {<br><br>	let value: NSTimeInterval<br>	<br>	init(_ value: NSTimeInterval) {<br>		self.value = value<br>	}<br><br>}<br><br>public final class UserSessionService {<br><br>	public init(with timeout: RequestTimeout) {<br>		// initialization logic<br>	}<br><br>}</pre><p>Which implies the following change when creating a new user session service</p><pre>let userSessionService = UserSessionService(with: RequestTimeout(10))</pre><p>Although the amount of “verbosity” remains almost the same, this solution felt superior. I’ve realized that by introducing a type I was improving readability and documentation and also making sure that whoever created a new instance of <strong>UserSessionService</strong> got a compiler error if the appropriate type wasn’t used. Having a more “narrower” type helps you catch error earlier. For example when a parameter is not a literal value in the code but something that is passed to you. Sure, in this case you could create a <strong>RequestTimeout</strong> with any given <strong>NSTimeInterval</strong> (which is just a type alias to Double). But having to do that explicitly makes you think twice about what you are doing and makes it more clear in code reviews in order for reviewers to double check if the type promotion is correct.</p><p>It didn’t end there. Then I thought, “wait, I can create a <strong>RequestTimeout</strong> given any number, clearly -45.345 is not a valid <strong>RequestTimeout</strong>”. The easiest way to solve this is by using <a href="https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html">fail-able initializers</a>.</p><pre>struct RequestTimeout {<br><br>	let value: Double<br>	<br>	init?(_ value: Double) {<br>		guard value &gt; 0 else { return nil }<br>		<br>		self.value = value<br>	}<br><br>}</pre><p>Now we need to safely unwrap the option.</p><pre>if let requestTimeout = RequestTimeout(10) {<br>  let userSessionService = UserSessionService(with: requestTimeout)<br>}</pre><p>Depending on how you are creating the <strong>RequestTimeout</strong> object and where that initialization takes place, using <em>if-let</em> syntax may not be necessary. For example, lets say to you only need to create the user session service once and you do it in the application’s delegate.</p><pre>class AppDelegate: UIResponder, UIApplicationDelegate {<br><br>  let userSessionService = UserSessionService(with: RequestTimeout(10)!)<br>	<br>  // The rest of the UIApplicationDelegate methods<br><br>}</pre><p>In such case I think that explicitly unwrapping the <strong>RequestTimeout</strong> value is OK because worst case scenario you’ll get a crash the moment you open the application. If you have at least one test, that error will get caught really early. Not as good as a compiler error but good enough.</p><p>I was about to move on but I decided to show all this to my co-workers to get their opinion. All of them agreed with this but one pointed out that it could be improved a little bit by communicating the time unit used for the request timeout. Because <strong>RequestTimeout(10)</strong> does not saying anything about whether the request timeout is in minutes, seconds, milliseconds or whatever. Because the request timeout is in seconds I changed the its initializer to</p><pre>struct RequestTimeout {<br><br>	let value: Double<br>	<br>	init?(seconds value: Double) {<br>		guard value &gt; 0 else { return nil }<br>		<br>		self.value = value<br>	}<br><br>}</pre><p>which reads like</p><pre>if let requestTimeout = RequestTimeout(seconds: 10) {<br>  let userSessionService = UserSessionService(with: requestTimeout)<br>}</pre><h4>Conclusion</h4><p>I think that providing documentation through the type system is the best way of designing code. Being able to empower the compiler by giving it more information helps you catch future bugs. I came to this conclusion by trying to improve a minor style issue which as a matter of fact it was pretty subjective (an probably only fueled by my <a href="https://en.wikipedia.org/wiki/Obsessive%E2%80%93compulsive_disorder">OCD</a> with code). That led to further challenging my assumptions and the end result was better code.</p><p>After all this review process and once I had the solution I felt comfortable with, I decided to look about this on the internet and found the following video explaining this same concept from <a href="https://medium.com/twitter.com/chriseidhof">Chris Eidhof</a> and <a href="https://twitter.com/floriankugler">Florian Kugler</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FDU7Je1rdXk0%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DDU7Je1rdXk0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FDU7Je1rdXk0%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7307cb43f1c09c7a7093fedcf80206f/href">https://medium.com/media/c7307cb43f1c09c7a7093fedcf80206f/href</a></iframe><p>Also found this Twitter thread by <a href="https://twitter.com/olebegemann">Ole Begemann</a></p><h3>Ole Begemann on Twitter</h3><p>If you can live with only supporting iOS 10+/macOS 10.12+, you should use Measurement&amp;lt;UnitAngle&amp;gt; for this. https://t.co/kGekcMejjM</p><h3>Ole Begemann on Twitter</h3><p>The same goes for other quantities. Your animation API has a duration parameter? Don&#39;t use TimeInterval, use Measurement&amp;lt;UnitDuration&amp;gt;.</p><p>and a his <a href="https://oleb.net/blog/2016/07/measurements-and-units/">blog post</a> about the Foundation’s Measurement type.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61d2695aceb6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/exit-0/avoiding-bugs-and-improving-documentation-through-the-type-system-61d2695aceb6">Avoiding bugs and improving documentation through the type system</a> was originally published in <a href="https://medium.com/exit-0">exit(0);</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The dawn of the REST API — Part 1]]></title>
            <link>https://medium.com/wolox/the-dawn-of-the-rest-api-part-1-558081889ed6?source=rss-2bc7f2f10e9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/558081889ed6</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Guido Marucci Blas]]></dc:creator>
            <pubDate>Thu, 22 Dec 2016 19:23:10 GMT</pubDate>
            <atom:updated>2016-12-22T20:03:34.073Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zisv67PLvmRhi1kA-T9Uxg.png" /></figure><h3>The dawn of the REST API — Part 1</h3><p>After being involved in the development of several mobile application products for clients and partners, I started to notice common patterns emerge during the process. One in particular was the friction between the mobile (Android &amp; iOS) and back-end teams.</p><p>This is Part 1 of a series of posts describing why it may not make sense for your project to develop a custom back-end, analyze the different alternatives, their benefits, and drawbacks. But first, you need to understand the process required to develop a typical mobile application.</p><h4>The development process</h4><p>At <a href="http://www.wolox.com.ar/">Wolox</a>, most mobile projects consist of Android, iOS and back-end teams. The back-end team is in charge of developing the back-end web services that support the mobile applications. These usually consists of a Ruby On Rails REST API using JSON as the representation format. The default tech stack consists of RoR, PostgreSQL, Amazon S3 and Sidekiq. For deployment, we typically use Heroku, <a href="https://medium.com/wolox-driving-innovation/how-to-set-up-your-own-prerender-environment-with-aws-ec2-a14451f857bf#.c7q79xxzd">Amazon EC2</a> and lately we have been using <a href="https://medium.com/wolox-driving-innovation/elasticbeanstalk-elk-stack-ef92f4e295c1#.2c1ejoit7">Amazon Elastic Beanstalk</a>.</p><p>With many of our clients being entrepreneurs who are looking to develop their first MVP, time to market and cost effective solutions are key drivers of the product. For us, this usually translates to a small team that generates a lot of value sprint after sprint, moving really fast (and trying to break as little as possible).</p><p>An important characteristic of these type of projects is that the majority of them are mobile only, reducing the web version of the product to a minimal landing page that communicates the key points of the product and links to the app store of your platforms of choice.</p><p>The development process varies depending on the client’s needs. Generally, they consist of a period of product building together with our UX team. This space is used to understand the main problem the product is trying to solve. From there we are able to iterate different solutions, gathering input from other departments (e.g engineering and design), until we feel our solution is worth implementing. The end result of this process consists of a set of wireframes describing the application’s flow.</p><p>After the product building phase, various processes begin in parallel. The design team starts working on the final design of the application: designing the logo, picking the color pallet and transforming the low-resolution wireframes into beautiful application screens.</p><p>At the same time, to accelerate the development process, mobile teams kick-off the new project and start prototyping a working version of the application flow provided by the UX team.</p><p>Although the design is not ready yet, we can start working on the functional requirements and minimize technical risk. This also allows us to show working versions of the application to our client so they can begin testing it internally (or with users) to validate that the current application flow is the right one.</p><p>To avoid being locked down by an endpoint that has yet to be designed we use services such as <a href="https://apiary.io/">Apiary</a> to implement a mocked version of the endpoint. This allows us to iterate faster on the endpoints and gives the mobile team the possibility of designing the endpoint as they see fit.</p><p>The kick- off of various teams in parallel allows you to be more productive on all fronts. By exhibiting a faster more continuous progress, we are able to minimize locks between teams. Additionally, each team may have several internal iterations of their work before presenting it to others. Yes, teams usually introduce other teams feedback as soon as possible however, they avoid committing to a design (either code or visual assets) until it has been approved by the client and in some cases tested with users.</p><p>By doing this we minimize breaking changes during the development process and other delays caused by having to re-implement a screen. This may be due to the design solution having problems or unable to be implemented in the required time. In order for this process to work, sprints and validation cycles have to be short and the client and users should check deliverables on a week by week basis.</p><p>Do you want to know more about our development process and the different approaches we take to be more productive, reduce cost, prototype and deliver faster? Stay tuned for part 2!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=558081889ed6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wolox/the-dawn-of-the-rest-api-part-1-558081889ed6">The dawn of the REST API — Part 1</a> was originally published in <a href="https://medium.com/wolox">Wolox</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>