<?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[Math Camp Engineering - Medium]]></title>
        <description><![CDATA[The engineering blog at Math Camp - Medium]]></description>
        <link>https://medium.com/math-camp-engineering?source=rss----7d82b16c25cf---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Math Camp Engineering - Medium</title>
            <link>https://medium.com/math-camp-engineering?source=rss----7d82b16c25cf---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 13:44:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/math-camp-engineering" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Systems we built and decisions we made]]></title>
            <link>https://medium.com/math-camp-engineering/systems-we-built-and-decisions-we-made-a31e8626b411?source=rss----7d82b16c25cf---4</link>
            <guid isPermaLink="false">https://medium.com/p/a31e8626b411</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[stackshare]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Revant]]></dc:creator>
            <pubDate>Thu, 14 Jul 2016 17:01:02 GMT</pubDate>
            <atom:updated>2016-07-14T17:01:02.243Z</atom:updated>
            <content:encoded><![CDATA[<p>Co-authored by: <a href="https://medium.com/u/881098433566">Revant</a>, <a href="https://medium.com/u/164b57f2f323">Brandon Kase</a>, <a href="https://medium.com/u/6bf81144c4b2">Benjamin Garrett</a>, <a href="https://medium.com/u/72bd5082d8aa">Christina Lee</a>, and <a href="https://medium.com/u/9e7b38618460">Alison Kohl</a></p><p>Acquisitions are a great opportunity for new beginnings, but they also offer amazing opportunities for reflection. In wrapping up our operations at Math Camp, the engineering team had the opportunity to look back, project by project, at the problems and solutions of each iteration of our engineering pursuits. While we spent a lot of time on day to day maintenance, we also encountered instances of novel breakthroughs, scrappy patches, and usages of new technology that few other companies have had the chance to test in the wild. In considering our legacy, we wanted to not only open source the code for some of these projects, but also walk through the decision making that led us to each solution. A lot of our decisions were made to optimize for quick iteration and maintainability, and as you read through this post, you’ll find technologies marked as <strong>Chosen </strong>or <strong>Built </strong>to explain the thought behind each. We hope that these solutions and the methods we used to arrive at them may be helpful in future engineering pursuits.</p><p>Best,</p><p>The Math Camp Team</p><p>We have broken down the post into the following sections: <br><strong>Client: </strong>Languages &amp; Build, Data flow, Drawing data, Fetching data, Sending data, and Storing data<br><strong>Server: </strong>Serving architecture, Language &amp; Repo, Auth, Experimentation, Notifications, Storage, and Processing data</p><p>We also have a list of the libraries we are open-sourcing <a href="https://github.com/mathcamp/list">here</a> in case you just want to look at the code.</p><h3>Client</h3><h4>Languages &amp; Build</h4><ul><li><a href="https://developer.apple.com/swift/"><strong>Swift</strong></a><strong> (Chosen)</strong>: We started using Swift in July 2014, a month after it was announced. We really enjoyed using Swift, but there were definitely some difficulties along the way. Getting good at writing Swift takes about 6 months, dealing with Swift language updates was difficult, and prior to Swift 2, compile times were about 10x slower than Objective-C. Additionally, many times we ran into incorrect code that successfully compiled, correct code that did not compile, and even correct code that segfaulted the compiler. However we did make good use of the modern features of the language: Protocol-oriented programming for code reuse, Sum types (and the included Optional), and Zero types to name a few.<br><em>TL;DR: Working with a new language had its inherent challenges and cost us time in refactors for version changes and slow compilations, but working in a modern language made us better and faster developers and allowed us to write clean and efficient code not otherwise possible in Obj-C. We were very happy with this decision and would make the same choice again today.</em></li><li><a href="https://medium.com/math-camp-engineering/kotlin-3e963864db9e"><strong>Kotlin on Android</strong></a><strong> (Chosen): </strong>Kotlin is a terse, Swift-like, functional programming language on the JVM platform with high Java interoperability. <a href="https://kotlinlang.org/">Kotlin</a> is unique in that its standard library and runtime are extremely small in bytes, yet very powerful. Most is eliminated at compile time (in contrast to Scala), so it can feasibly be used in memory “constrained” environments like Android. We wrote a ton of dependency-free extensions and operators in a <a href="https://github.com/mathcamp/cheatsheet">library we call Cheatsheet</a>.<br><em>TL;DR: We’re really glad we made this decision, but build times suffered early on. This is being fixed in Kotlin going forward, so may not be applicable.</em></li><li><a href="https://buckbuild.com/"><strong>Buck </strong></a><strong>with Kotlin (Chosen): </strong>When we were writing a lot of <a href="https://kotlinlang.org/">Kotlin</a>, Gradle builds were very slow (although this may have improved since then). Hacking Kotlin into Buck gave us a 5x speedup in builds.<br><em>TL;DR: Build times vastly improved, but setup took several days and a lot of intricate tooling.</em></li><li><a href="https://www.typescriptlang.org/"><strong>TypeScript</strong></a><strong> (Chosen): </strong>When writing our React Native app, we wanted to have some type safety to statically catch errors. We chose to use TypeScript, which compiles to plain JavaScript but allows for some type errors to be surfaced in the IDE. Early versions of TypeScript were moderately useful, but left a lot to be desired. As of the last update (1.8), the technology took a huge step forward and offered much better type mismatch alerts.<br><em>TL;DR: TypeScript helped us write correct code and the language continues to improve, but we wish we had spent more time investigating </em><a href="https://flowtype.org/"><em>Flow</em></a><em> before choosing TypeScript.</em></li></ul><h4>Data flow</h4><p>We used streams, futures, and observables instead of async tasks, callbacks and async queue dispatches. <a href="https://medium.com/@bkase/eea7b871e0ac">This post explains in detail our thought process behind these decisions.</a></p><ul><li><strong>Streams</strong> (<a href="https://github.com/ReactiveX/RxJava">RxJava</a>/<a href="https://github.com/ReactiveX/RxSwift">RxSwift</a>) <strong>(Chosen)</strong>: From the README: “[Rx] extends the <a href="http://en.wikipedia.org/wiki/Observer_pattern">observer pattern</a> to support sequences of data/events and adds operators that allow you to compose sequences together declaratively while abstracting away concerns about things like low-level threading, synchronization, thread-safety and concurrent data structures.”<br><em>TL;DR: We were overall very happy with this choice. However, there is longer ramp-up than first party async concurrency primitives, and if you don’t understand what’s going on under the hood, you can get bitten by unexpected behavior.</em></li><li><strong>One way data flow: </strong>In both our iOS and Android apps, we introduced UI architectures that were based on unidirectional cyclic data flow. The reasons for this were numerous, but key among them was the desire to easily incorporate data from local state, user input, and server updates without complicated merge logic. Designing our system with these Cycle.js inspired components also allowed for us to offload complicated logic from activities and viewcontrollers into more easily testable and composable components. Both the iOS and Android implementations of unidirectional data flow paradigms relied extensively on Rx, which meant the learning curve was high for any team members not previously familiar with Observables. <em>Also see: Cyklic and Dogtag<br>TL;DR: Adopting unidirectional UI architectures made for code that was easily modifiable and very transparent to reason about and test, but is likely not feasible at scale unless engineers have significant time to become comfortable with drastically different paradigms.</em></li></ul><h4>Drawing data</h4><ul><li><a href="https://realm.io/news/kau-lee-kase-reduxing-ui-borrowing-from-web/"><strong>Cyklic</strong></a><strong> (Built): </strong>Cyklic brings ideas that are starting to become popular on the web to native Android. Cyklic is a <a href="https://en.wikipedia.org/wiki/Functional_reactive_programming">discrete functional reactive</a> UI component framework inspired by <a href="http://cycle.js.org/">Cycle.js</a> (similar to the <a href="http://guide.elm-lang.org/architecture/">elm architecture</a>). Using these architectures leads to (mostly) pure application logic. Pure code is simpler and easier to reason over. Adopting this framework helped us find edge cases and gave us the nice “if it compiles, it works” property for our UI components.</li><li><a href="https://github.com/christinalee/Dogtag"><strong>Dogtag</strong> <strong>(Built):</strong></a><strong> </strong>Dogtag builds off the work done in Cyklic to bring unidirectional circular data flow to UI components in iOS. It demonstrates a method of organizing data that allows you to offload complicated logic from ViewControllers into a model and view model layer. The main responsibility of ViewControllers becomes binding view variables (the alpha value of a button for example) to their corresponding element in the UI.</li><li><a href="https://facebook.github.io/react-native/"><strong>React Native</strong></a><strong> (Chosen): </strong>React Native enables you to build native mobile apps using JavaScript. One of the biggest advantages of this is that you can send down JavaScript code for components from the server. This enabled us to ship code and fix bugs without going through the app release cycle. Unlike most React Native users, our app is not React Native with a little bit of native code — it’s a native app with a little bit of React Native code. We built a few screens of our app in React Native and also created a React-Bridge so that the JavaScript code could interact with native app components. We used React Native for instant over-the-air updates for minor UI tweaks and bug fixes so we didn’t have to wait for App Store approval. Overall we were happy with these benefits, but it had downsides. For example, React didn’t perform well for long lists of things (no view cell reuse yet) and debugging some issues was a bit tricky.</li></ul><h4>Fetching data</h4><ul><li><a href="https://medium.com/@revant8888/fb56eb3505b1"><strong>Server controlled onboarding pipeline (Built)</strong></a><strong>: </strong>For fast iteration of onboarding, we built an instruction pipeline which would be sent from the server and processed by the client. Instead of sending down the items and writing the business logic on the clients, we decided on a set of instructions that each of the clients would implement and wrote the business logic on the server, which parsed everything and sent down instructions to be processed sequentially, just like CPU instructions.<br><em>This worked out great for us and enabled us to test multiple different onboardings with ease.</em></li><li><strong>Adaptive image download (Built): </strong>We recorded the length of time it took to download and display every image or video that the user sees. This allowed the app to get a sense of the user’s overall experience — does it feel fast or slow? Are they seeing loading indicators or not? If the moving average of media display times reached a certain level, then the app would start downloading lower resolution media. Once the user was in faster network again, the moving average would drop enough that the client would switch back to full resolution. This system made the app dramatically more usable in varying network environments.</li><li><strong>Mobile config (Built): </strong>We built a server-controlled config, which the client would fetch on app load. It was a local key-value configuration which could be overridden from the server. It enabled us to change how the app behaved without pushing an app update. This also enabled us to run experiments and change the look and feel of the app on a per user basis — for example, we built the app so that the client could get a font, size, and color for a particular text element. For those of you who want to use mobile config, firebase just released<a href="https://firebase.google.com/docs/remote-config/"> something</a> very similar to it.</li><li><a href="http://square.github.io/retrofit/"><strong>Retrofit</strong></a><strong> &amp; </strong><a href="https://github.com/Alamofire/Alamofire"><strong>Alamofire</strong></a><strong> (Chosen): </strong>We used Retrofit for our REST client code on Android and Alamofire on iOS. We chose these mostly because of the strong community around these libraries and Retrofit specifically because our server APIs were RESTful. We had no problems using these libraries.</li><li><strong>Image caching (Chosen): </strong>In a mobile app, if you don’t nail your cache code, your users will suffer. Excessive networking causes both battery and data-plan drain. We can help ensure a clean correct implementation by combining caches. Choosing the right image fetching and caching library is tricky. There are plenty of them out there, but somehow none of them are completely satisfactory (or were when we looked). <br>On <em>Android</em>,<a href="http://square.github.io/picasso/"> Picasso</a> has a nice API and is very simple to use. However, it uses the standard HTTP cache and HTTP cache headers, so the caching layer isn’t very flexible. We decided to use<a href="https://developer.android.com/training/volley/index.html"> Volley</a> by Google as it was easier to play around with the caching layer. If you don’t have to do that, we would recommend Picasso.<br>On iOS, we used<a href="https://github.com/WeltN24/Carlos"> Carlos</a>, a composable caching library. Consider what it means to be a cache. You need to be able to (1) associate a key with a value and (2) get some value given a key if such a value exists. That’s basically it. Caches tend to appear in layers. In a CPU, memory reads check L1, then L2, then L3, then RAM. When we want to load an image, we first check RAM, then disk, and finally network. Given two caches A and B, A `on-top-of` B means first check A, fallthrough to B, then write back to A. Now we can define a monoid for caches. Monoids imply easy composition. Easy composition means reasoning about our code becomes easy. Carlos is nice because you can reuse the same network cache logic across not just images, but other binary assets and JSON data. It is also very easy to decouple what would be complex performance logic from the actual caching logic.</li></ul><h4>Sending data</h4><ul><li><strong>Upload pipeline (Built): </strong>A major part of our app was uploading photos and videos that users shared. At times users would share tens of photos every session and we wanted to make sure all of them got uploaded. We put all the media to be uploaded in a queue and split the upload process into atomic stages: ready for upload, formatted locally, generated cloud storage URL, uploaded to cloud storage, and finalized on our server. Our upload pipeline was a state machine backed by disk, so even if the app was killed in the background, we could finish the upload later. If a particular stage failed, we would put it back in the upload queue. Recently, Android launched a<a href="https://developer.android.com/reference/android/app/job/JobScheduler.html"> job scheduler</a> which should make implementing this easier (on Android), but we didn’t get a chance to test it.</li><li><strong>Offline sync (Built): </strong>We wanted our app to be usable on poor and non-existent networks. First of all, you need to make sure you prefetch often enough. The data needs to be in the app even if at the time you open it there is no network. Our prefetching system ended up becoming a variant of our Carlos caching system (see above). Secondly, if you swipe a photo, you should not see it again. Ever. We built a system that ensured certain requests would eventually complete successfully. So we didn’t just hit the network for these requests, but we also stored the information persistently on the client so that, for example, we would know not to show you the same photo twice.</li></ul><h4><strong>Storing data</strong></h4><ul><li><a href="https://github.com/mathcamp/fiberglass"><strong>Fiberglass (Built)</strong></a><strong>: </strong>Lightweight shared preferences in Kotlin. Delegated properties in Kotlin not only allow you to execute arbitrary code when a field is accessed, but also package up the code for reuse. You can also reuse the same delegate for different properties. We used this extensively instead of Android’s SharedPreferences. Take a look at<a href="https://github.com/mathcamp/fiberglass"> </a>the readme for more details.</li><li><a href="https://github.com/mathcamp/lightbase"><strong>Lightbase (Built)</strong></a><strong>: </strong>We built a Swift wrapper around SQLite to be able to store and load structured data from disk easily. We had tried some of the other databases around, but they either had complicated usage patterns or caused crashes.</li><li><a href="https://github.com/mathcamp/storedobject"><strong>StoredObject (Built)</strong></a><strong>: </strong>Similar to Lightbase, we also wrote stored object for android. It uses SQLite as the backend but allows you to have an arbitrary schema. This made storing and loading objects from disk very straightforward without having to deal with any SQL boilerplate. We also have an<a href="https://github.com/mathcamp/rxstoredobject"> rx version</a> of it.</li></ul><h3>Server</h3><h4>Serving architecture</h4><ul><li><strong>App Engine (Chosen): </strong>We used to use AWS EC2 VMs with our database on RDS and Dynamo and wrote some libraries for it (<a href="https://github.com/mathcamp/flywheel">flywheel</a>, <a href="https://github.com/mathcamp/pypicloud">pypicloud</a>, <a href="https://github.com/mathcamp/dql">dql</a>, <a href="https://github.com/mathcamp/steward">steward</a>), but we realized we were spending too much time just maintaining our web servers. We wanted to move to a solution where we didn’t need to do any of this and were deciding between containers and App Engine. Two years ago, containers didn’t really have a good hosted platform (like Google Container Engine), and even though they were somewhat simpler, it still would have been a lot of work to manage. App Engine, with its recent additions (modules, versions, and queues) and its awesome hosted and fully managed <a href="https://cloud.google.com/appengine/docs/go/datastore/">cloud datastore</a>, was the winner. <em>We’ve been very happy with App Engine, as we’ve had to spend minimal time maintaining and scaling our server stack. You can also stream App Engine logs and datastore entities to </em><a href="https://cloud.google.com/bigquery/"><em>BigQuery</em></a><em>, which makes doing analysis quick and easy.</em></li><li><strong>Go-restful (Chosen):</strong> We decided to go with <a href="https://github.com/emicklei/go-restful">go-restful</a> which uses the standard Go net/http server but adds nice routing on top, specifically the ability to define REST services and generate Swagger documentation from them.</li><li><strong>Swagger (now known as the Open API Initiative) (Chosen): </strong>Swagger is a system that understands REST APIs. Our server framework outputs information about our REST APIs in the Swagger specification format. We use <a href="https://github.com/swagger-api/swagger-ui">Swagger-UI</a> to visualize and test our APIs. We even use it as a dashboard where non-engineers can poke our backend. <br><em>TL;DR It was a bit cumbersome to get Swagger setup for the first time, but after that it worked great for us and was heavily used.</em></li><li><strong>Paging (Chosen/Built): </strong>When sending a large (or infinite) list of data to a client (and since the client can only view part of it at a time), the right thing to do is to break up the list into chunks (or pages) and send the pages one at a time to the client instead. This way the client doesn’t have to wait for a ton of data before being able to view it, and the datastore doesn’t have to return too many items at once. We implemented a paging solution on AppEngine similar to the design of the <a href="https://developers.facebook.com/docs/graph-api/using-graph-api/#paging">Facebook Paging API</a>. When you receive a page of data, you receive in JSON: The list of data along with `next` and `prev` urls to get the next and previous page respectively. The URLs themselves use the query parameters: “limit”, “since”, and “until.” “Limit” is the max amount of items to return in this page. “Since” and “until” refer to the beginning and end of the range of data that we would like to get (both are optional, default is now). Usually `since` and `until` are timestamps — however, our system can also alphabetically sort by some parameter of your data and provide that information to since and until.</li></ul><h4><strong>Language &amp; Repo</strong></h4><ul><li><strong>Go (Chosen): </strong>Once we had decided on App Engine, we had to choose one of the languages compatible with it. We decided on Go because it has goroutines, compiles and executes quickly, is easy to learn, has great tooling, and is great for IO intensive work. Goroutines make it straightforward to write concurrent IO calls, which is usually the bottleneck for web servers. We wrote a small forkjoin type library for Go called <a href="https://github.com/revantk/concrunner">concrunner</a>, which enables running a fixed number of concurrent requests and combines the errors and results from them. However, the lack of generics (or something with a similar amount of typesafe abstraction) is an issue at times.</li><li><strong>Repo structure (Chosen): </strong>For Go, repo structure implies package structure. We used a monolithic repo for both the client and the server code. Inside our server codebase, we had the following directories: api, controllers, io, and models. <em>api</em> contained all the routing and rest service definitions. <em>controllers</em> contains all the business logic as functions which can be tested — for example, the usercontroller package would have a method like CreateNewUser(ctx, name) -&gt; (id, error). <em>io</em> contained code for performing io on one particular model — for example, userio had methods for accessing the user object from the db/memcache. <em>models </em>contained the model definitions (structs in Go) for each type, and also contains any transformations which don’t require io. After we had used Go for a while we realized that it is extremely useful to also nest packages under controllers, io, and models so that, for example, `models.UserId` becomes `user.Id`.<br><em>TL;DR: This worked great for us. It was very clear for developers when they were hitting the db and when it was just a local call. It also made it easy to organize and test code.</em></li></ul><h4><strong>Auth</strong></h4><ul><li><strong>JWT(Chosen): </strong>We decided to go with JWT (JSON web token) for authentication. JWT is great because you can just decrypt the access token to confirm the identity of the user instead of verifying by looking up in the database. For those who don’t know what this is, it allows you to base64 encode and sign a JSON object (which contains the userid and any other metadata) using a secret key. You can then send this string down as an access token to the client on first login. Consecutive requests send that token and you can get the userid from it without hitting the database.</li><li><strong>Magic Link (Built): </strong>We wanted to reduce friction for people signing up from invites for our app Roll. We built Magic Link so that if a user clicks on an invite link and installs the app, they would automatically be signed in. Since we were using phone numbers for login and for sending the invite, we signed in the invited user using a special link. The invite link sent to a phone number contained a code which would get sent to the server after app install and would act as a verification token. For passing on the code between the link click and app install, you could use an install tracking analytics tool. (Google Analytics also has this.)<br><em>TL;DR: It was magical when it worked for people but sometimes people wanted to change their phone numbers so we added a confirmation step before automatically signing them in.</em></li><li><a href="https://github.com/mathcamp/phone"><strong>Phone (Built)</strong></a><strong>: </strong>Since we used phone numbers for authentication we built a phone parsing library for go. It figures out the country and whether the given number is valid for that country. Another neat thing about it is that all the country definitions are given inside country-phones.json, a file which can be used on the client for phone number formatting as well.</li></ul><h4><strong>Experimentation</strong></h4><ul><li><a href="https://github.com/mathcamp/yatz"><strong>Yatz (Built)</strong></a><strong>: </strong>We built our own A/B testing framework for App Engine in Go on top of logs and BigQuery inspired by <a href="http://www.alangpierce.com/blog/2014/07/07/bigbingo-khan-academys-new-bigquery-backed-a-b-testing-framework/">BigBingo</a>. Yatz allowed us to do A/B testing without making any extra network requests. It can be broken down into three parts: Managing experiments, logging events, and analyzing the events. The experiments and variants were stored in an active_experiments file that got pushed to our servers. An event along with all the user’s experiment variants was logged with standard App Engine logs. These logs were streamed to BigQuery, an optional feature of App Engine. We then wrote scripts which made it easy to analyze this data using BigQuery. A nice feature of Yatz: Choosing a variant involves merely hashing an id, and reporting events is just logging. Therefore, experimentation with Yatz adds essentially zero overhead (no I/O necessary).</li><li><strong>Feature gating (Built): </strong>Rather than littering our codebase with version checks (if version &gt;= 1.0.3), we used feature checks (if ctx supports tagging feature). That way, when you go back to look at the code again, you understand the intent of the branch. Under the hood, it is implemented using app versions, but by abstracting the version checks out of the application logic, our code became a lot cleaner.</li></ul><h4><strong>Notifications</strong></h4><ul><li><a href="https://medium.com/@revant8888/ebd5bb7b8a1b"><strong>Notification Engine (Built):</strong></a><strong> </strong>Sending the right amount of notifications at the right time was very important to us, as well as the ability to tweak and test those things. We built a system which made batching and scheduling notifications super easy. Sending notifications like “Alice and 5 others liked your photos (5 minutes ago)” requires very minimal effort. Take a look at <a href="https://medium.com/@revant8888/ebd5bb7b8a1b#.rxu30nw2h">this blog post</a> to learn more.</li><li><strong>Google Cloud Messaging (Chosen): </strong>We used GCM to send notifications to both iOS and Android. You can send notifications using the same REST calls and don’t have to deal with APNS sockets. App Engine doesn’t allow persistent socket connections, so sending notifications to iOS devices via GCM was much faster as well.</li></ul><h4><strong>Storage</strong></h4><ul><li><strong>Google Datastore (Chosen): </strong>We wanted a flexible, scalable, and hosted database. We used to host our own database, but managing it and scaling it became a full-time job and we wanted to move away from that. After looking into some of the hosted databases, we decided to go with the Google Cloud Datastore. It’s a NoSQL database which supports transactions and indexes, which was exactly what we wanted. It was one of the things which made us choose App Engine as our serving architecture. It is flexible and allows you to add fields to your structured objects even after they have lived in production. It’s scalable and scales automatically. Since it’s distributed, it’s fast (~10ms query times), and it also supports limited transactions when you want them.</li><li><strong>Storing data in keys (Chosen): </strong>Cloud Datastore keys are just arbitrary strings (just like any NoSQL database). Instead of just using uuids for keys we stored data in the keys themselves. This enabled us to enforce uniqueness for the stored objects and also meant less database calls. An example of this is our Edge structure which is used to store any relationship in a social graph. An edge has a source, a target and a type. Our edge key was just a concatenation of all those 3 things “src:type:tgt”. This way we didn’t have to check for an existing edge before storing a new one and also made all edge queries fast as you only needed to fetch the keys.</li><li><strong>Using key only queries in datastore (Choice): </strong>Key only queries in datastore are free and so is memcache access. We used both these things to bring our datastore costs down. #1 We stored data in keys (look above), #2 We stored objects in memcache, #3 we would do key only queries and then fetch the data if we wanted to from the memcache.</li></ul><h4><strong>Processing data</strong></h4><ul><li><strong>Data migration (Built): </strong>Sometimes you have to change things in all objects of some type that you have stored. When there aren’t many objects, it is fast enough to just serially iterate through all of them and apply transformations. However, this becomes unusable as the number of objects grow. We built a simple migration tool on top of AppEngine which allows changing these objects in parallel in Go. It streams over all the keys, batches them and schedules each batch on an AppEngine queue. Each batch fetches the objects for those keys, deserializes them into their Go struct types, runs a transformation, and returns storable objects. This system is a bit tied into our codebase so we haven’t open sourced it yet but hope to do so soon.</li><li><strong>Distributed ForkJoin for AppEngine (Built): </strong>We built a distributed forkjoin using memcache in AppEngine for running batch jobs and combining the results of those jobs across machines. The way we structured it, the last job would know it is the last one and could do whatever it wanted with the combined result. We plan to open source this soon.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a31e8626b411" width="1" height="1" alt=""><hr><p><a href="https://medium.com/math-camp-engineering/systems-we-built-and-decisions-we-made-a31e8626b411">Systems we built and decisions we made</a> was originally published in <a href="https://medium.com/math-camp-engineering">Math Camp Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Declarative onboarding instruction pipeline]]></title>
            <link>https://medium.com/math-camp-engineering/server-controlled-declarative-onboarding-pipeline-fb56eb3505b1?source=rss----7d82b16c25cf---4</link>
            <guid isPermaLink="false">https://medium.com/p/fb56eb3505b1</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[onboarding]]></category>
            <category><![CDATA[user-onboarding]]></category>
            <dc:creator><![CDATA[Revant]]></dc:creator>
            <pubDate>Thu, 14 Jul 2016 16:46:02 GMT</pubDate>
            <atom:updated>2016-07-15T05:19:46.957Z</atom:updated>
            <content:encoded><![CDATA[<p>Onboarding is one of the most important things for any product. It is the first thing a user sees and is essentially the make or break moment for the product. If your onboarding is clear and concise the user will start using your product and if its even the tiniest bit confusing the user will probably never use your product again. It’s also really hard to get right in one go. You have to iterate on it, test it with users, make changes and do the whole process again and again.</p><p>When we started working on onboarding, we talked about it, debated on different versions, made cool illustrations and finally thought we had the perfect one. We then gave it to a few users and everything failed. Users didn’t know what each screen did, they found some things very frustrating and at the end of it didn’t really understand much about the product. We did it the second time and again the same thing happened. At this point engineering was getting frustrated making all these complicated screen transitions but product was rightly wanting to keep iterating on it. It often led to bugs and the code quickly started going down the drain. Enter: declarative onboarding pipeline.</p><p>We realized that instead of writing complicated business logic on the client, we should just have the client implement a set of instructions and send a sequence of those instructions from the server. This way we could make changes to the onboarding without having to refactor any client code and even better, since it was declarative, product could make the changes to onboarding themselves. We essentially implemented an instruction state machine on the client which would process instructions one by one.</p><p>Onboarding on the server now looks like:</p><pre>[]Instruction{<br>   &amp;Branch{<br>      Fn: func(ufs State) bool<strong> </strong>{<br>         return<strong> </strong>ufs.SelectFriendsManually<br>      },<br>      Yes: []Instruction{<strong>ShowScreen</strong>(ScreenNuxFindFriends, <strong>&quot;&quot;</strong>)},<br>      No:  []Instruction{},<br>   },<br>   <strong>ShowPhotos</strong>(5), //Show the 5 newest photos for the user<br>}</pre><p>The functions in bold are instructions that the client will implement and the State is a combination of the user state and stuff the client sent. This included permissions the user had given and any client actions the user had taken so far. Notice how all the logic for onboarding is defined right here including any branching. This way anyone can change the ordering of things or add new branches without needing to write any complicated code. The server would then process this and send down a list of sequential actions to do.</p><p>The JSON request &amp; response to the client would look like:</p><pre>Request: <br>{&quot;client_state&quot;: {&quot;contact_perm&quot;: false, &quot;notif_perm&quot;: true}}</pre><pre>Response: <br>[{&quot;instruction&quot;: &quot;ShowScreen&quot;, &quot;name&quot;: &quot;ScreenNuxFindFriends&quot;}, <br>{&quot;instruction&quot;: &quot;ShowPhoto&quot;, &quot;url&quot;: &quot;https://...&quot;},<br>{&quot;instruction&quot;: &quot;ShowPhoto&quot;, &quot;url&quot;: &quot;https://...&quot;}<br>..<br>]</pre><p>The client code becomes just like a virtual machine ie. fetch instructions, decode them and execute them. This client only has to implement the instructions ShowScreen and ShowPhoto. Once the state machine is implemented, adding a new instruction is a breeze and changing onboarding is not a problem anymore. This also allowed us to experiment with different variants for different users and test the best one without complicating any code.</p><p>In short, making this design decision changed onboarding from spaghetti code to one of the most elegant pieces of code in our codebase. It made changing onboarding super easy and hence we could do the whole cycle of change, test, reiterate much faster. It also enabled us to have the same onboarding on Android and iOS without changing code twice!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb56eb3505b1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/math-camp-engineering/server-controlled-declarative-onboarding-pipeline-fb56eb3505b1">Declarative onboarding instruction pipeline</a> was originally published in <a href="https://medium.com/math-camp-engineering">Math Camp Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Notification Engine]]></title>
            <link>https://medium.com/math-camp-engineering/notification-engine-ebd5bb7b8a1b?source=rss----7d82b16c25cf---4</link>
            <guid isPermaLink="false">https://medium.com/p/ebd5bb7b8a1b</guid>
            <category><![CDATA[push-notification]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[app-engine]]></category>
            <dc:creator><![CDATA[Revant]]></dc:creator>
            <pubDate>Thu, 14 Jul 2016 16:31:02 GMT</pubDate>
            <atom:updated>2016-07-14T16:31:02.106Z</atom:updated>
            <content:encoded><![CDATA[<p>We built a system to aggregate and send notifications with a time component. This makes is super easy to send notifications like “Alice and 5 others liked 5 of your photos” and do things like o<em>nly send one notification every 24 hours and combine all like notifs for 5 minutes before sending. </em>Sending the right amount of notifications to a user at the right times helps us deliver higher engagement without annoying them.</p><h4>The Problem</h4><p>Notifications are useful and can be a key driver for engagement, but they can also get annoying really fast. Most products either send every notification (eg. <a href="https://www.youtube.com/watch?v=zGl796352RI">Instagram</a>) or chose to skip entire categories of notifications. Turns out its a lot of work to smartly deal with aggregation of notifications. It leads to a lot of complexity and is hard to change. Our product <em>Shorts </em>is a high frequency sharing app so we wanted to be able to aggregate notifications but still send them as soon as possible (for realtime feedback) and we wanted the ability to test multiple variations of it. Thus we designed a system to handle it.</p><h4>Design</h4><p>We achieved simplicity by decoupling the time and aggregation aspects of notifications. For developers this boils down to firing events in the app whenever some action happens eg. when user A <em>likes</em> user B’s (receiver) photo, the application fires a notif event of type <em>like</em> to the notification engine. They can then define the aggregation for <em>like </em>notifs separately.</p><p>In the application code it looks like:</p><pre>notifengine.NewEngineEvent(ctx, notifengine.EventAtom {<br>    For: &quot;receiver&quot;,<br>    EventType: &quot;like&quot;,<br>    From: &quot;me&quot;,<br>})</pre><p>For the aggregation part, each notification type has to define 2 methods:</p><pre>// This method takes in the previous state and the new event and outputs the time to schedule this type of notificaton<br><em>eta(State, Event) -&gt; time </em></pre><pre><em>// This method takes in a list of events and creates a push notification with text combining all of those events. eg. &quot;Alice and 5 others liked your photos&quot;<br>aggregate([]Event) -&gt; []PushNotif</em></pre><pre>State {<br>   LastSentTime<br>   CurrentEta<br>}</pre><pre>Event {<br>   For // (Could be a userid or a phone number)<br>   Type //eg. like<br>   From // (Optional from userid)<br>   About // (id of the item this notif is about, eg. photo id)<br>   CreatedAt <br>   Extra // (any extra information associated with this event)<br>}</pre><pre>PushNotif {<br>   Message // Message to be sent<br>   Args //key value pairs to send along with the notif<br>   SendTo // Send to this userid or phone number<br>   ForOs // To restrict it to only ios or only android<br>}   </pre><h4>Implementation</h4><p>The notif engine is implemented using a message queue . Our app is built on app engine so we use the built in <a href="https://cloud.google.com/appengine/docs/go/taskqueue/push/">push queue</a> but it can be used with any message queue which supports scheduling a task in the future. We use 3 queues for this: <em>processor</em>, <em>aggregator</em> and <em>sender</em>. When the app fires an event for a receiver eg. “Send like event to user B”, it gets put on the <em>processor</em> queue. The engine then processes this event, calculates the eta and then schedules this event type for the given receiver on the <em>aggregator</em> queue. This then gets executed at the given time and calls the <em>aggregate</em> method which outputs notification payloads which get put on the <em>sender </em>queue. Consumers of the sender queue are responsible for maintaining connections with apple and google.</p><h4>Other advantages</h4><p>Designing the engine in this way also allows us to do other things with notifications:</p><ol><li><strong>Easy cancellation of notifications</strong>: When the user opens the app, we can just fire a cancel event which prevents the accumulated notifications from sending.</li><li><strong>Notification permissions: </strong>We can handle notification permissions in the engine as well. If the user wants to switch off certain notifications, we can do that without complicating our app code.</li><li><strong>Not sending notifications at night:</strong> Since the time aggregation is separate, we can easily modify the <em>eta </em>method to not send notifications to users at night, again without over complicating app code or the notif aggregation part.</li><li><strong>Notification activity feed: </strong>Since each notification event is stored, we can use the same data source for generating the users notification feed.</li><li><strong>Giving users control: </strong>The user can dictate how frequently they want certain notifications and this just requires modifying just the eta method.</li></ol><h4>Conclusion</h4><p>The app landscape has matured and users want refined experiences. For a lot of apps, notifications play a very important role and having a great notifications experience is paramount for user engagement. By designing systems like these, small teams can rapidly iterate and provide awesome user experiences without repeating effort.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebd5bb7b8a1b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/math-camp-engineering/notification-engine-ebd5bb7b8a1b">Notification Engine</a> was originally published in <a href="https://medium.com/math-camp-engineering">Math Camp Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concurrency Categorization]]></title>
            <link>https://medium.com/math-camp-engineering/concurrency-categorization-eea7b871e0ac?source=rss----7d82b16c25cf---4</link>
            <guid isPermaLink="false">https://medium.com/p/eea7b871e0ac</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Brandon Kase]]></dc:creator>
            <pubDate>Thu, 14 Jul 2016 16:31:02 GMT</pubDate>
            <atom:updated>2016-07-22T02:00:06.961Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Comparing primitives for native mobile applications</strong></h4><p>These days, when writing native mobile applications, there is an expectation that your app should be responsive despite needing to perform massive amounts of slow I/O and other operations. We must offload the slow work from the main thread.</p><p>There are many ways to offload work from the main thread across the Android and iOS platforms. If you agree with my assumptions that I’ll outline below, I believe that at its core, there are six dimensions to consider when evaluating a method for performing and handling asynchronous work:</p><ul><li>Is it referentially transparent?</li><li>How is the result returned?</li><li>Is it composable?</li><li>Is the execution context coupled or decoupled?</li><li>Local or non-local scoping?</li><li>How difficult is it to learn?</li></ul><p>The assumptions:</p><ul><li>Performance overhead of the primitives themselves is negligible: A lot of concurrent work you do involves I/O or expensive computation (otherwise why not just do it on main thread). For UI related events, you might need to use lightweight callbacks.</li><li>You are writing application-level code (some and perhaps all of these properties also apply in other environments but may require different reasoning for you to be convinced)</li><li>You want a <em>general purpose</em> primitive that can be used in a variety of situations</li></ul><p>I’ll talk about how to think about these categories, and then go through various primitives that I have seen across both iOS and Android and comment on where this particular primitive falls in each of the dimensions.</p><h3><strong>Referential Transparency</strong></h3><p>Visible side-effects make code harder to reason over. Google it. Containing no or invisible side-effects (such as memoization) is known as referential transparency. A referentially transparent expression is one that can be replaced by its result without changing the behavior of the program. In this context: Can you replace an expression containing your concurrency primitive with its result. Aka does your concurrency primitive do side-effects when being created or used? Eventually, it must perform side-effects for the concurrency to actually be concurrent. However, the act of starting the concurrent work is decoupled from the work logic. Usually dealing with the primitives that just perform side-effects does make <em>writing</em> the code easier, but reasoning over that code is hard.</p><h3><strong>Output One Datum or Many Data or Side-effect Data (Unit)</strong></h3><p>Do you output data or not? If you don’t output any data (aka you return Unit — Java’s void or Swift’s Void) the data you’re outputting is implicit and therefore a side-effect.</p><p>Do you output one and only one piece of data? vs. Do you output at least one piece of data (but possibly more)?</p><p>If you have many pieces of data, the choice is easy. You want a primitive that can output many pieces of data. Anecdotally, trying to achieve outputting many pieces of data with a primitive that only supports returning one and only one piece of data is error-prone and hard to reason about — I believe this was due to needing long-living mutable state (in the temporal sense).</p><p>If you have one piece of data, on the one hand the types provide more precise documentation (since you can only output one piece of data). However, if your primitive is composable you lose this composability without an extra layer of translation.</p><h3><strong>Composability</strong></h3><p>Composability in the context of programming means that there exists some way to combine two or more entities of some type to create something of that same type. Composability is important for clean, maintainable, and flexible code because we don’t have to understand the details to understand some part of a program. Composition is the essence of abstraction.</p><p>For motivation: Most of the time, when you run into the number <strong>2</strong>, you don’t care that this was constructed from <strong>(1 + 1)</strong> and you don’t have to. Moreover, <strong>2</strong> means the same thing if it were constructed via <strong>1 + 1 </strong>or <strong>2 x 1</strong>.</p><p><strong>(+)</strong> over the integers and <strong>(x)</strong> over the integers takes two integers and returns an integer. Thus both are composable operators (moreover they are monoids — Google it).</p><p>In the same vein as not needing to care about the provenance of certain operations on integers, we also don’t need to care about subtasks in a larger task most of the time. It would be nice to be able to call <strong>AsyncGetData() -&gt; F&lt;Data&gt;</strong> and not care that under-the hood the function first checks disk asynchronously and then when that finishes hits the network, etc. This is known as sequential composition, since we are sequencing two computations one after another.</p><p>We also have parallel composition — if I can asynchronously get a name, and separately I’ve defined how to asynchronously get an age, I should be able to have one entity that can asynchronously get both a name and an age.</p><p>I’m not aware of an argument against composability.</p><h3><strong>Execution context</strong></h3><p>An execution context describes how work is executed when it actually runs. Examples of execution contexts include: Always execute on the main thread, execute on some free thread in a thread pool and spawn a new thread if all are busy, or execute on this same thread.</p><p>The execution context is either coupled to the site at which the concurrent work is declared or decoupled and can be provided at a later point (obviously before the work is actually executed).</p><p>A decoupled execution context means you can reuse more code since you can change the execution context in multiple places. More code becomes trivially testable since you can provide synchronous execution contexts. Coupling execution context with work description provides none of these benefits.</p><h3><strong>Scoping</strong></h3><p>Mutable state makes code harder to reason over. Non-local mutable state is even worse. This is software engineering 101: Use functions, avoid globals. Some concurrency primitives are inherently unscoped — in other words, concurrent work can be manipulated and listened to from anywhere in your program. This is a global. This is not good.</p><h3><strong>Learning Difficulty</strong></h3><p>This is a bit subjective — some primitives are harder to learn than others. Given the time constraints of your project, you may choose to use an easier-to-learn primitive that may not fit your needs as well in order to onboard your team faster.</p><h3><strong>In General</strong></h3><h4>Callback</h4><p>Data is provided to you via the parameter of some function you pass in.</p><ul><li><em>Effectful: </em>The callback you provide will be called when the work is done, but just passing the callback implies your async work has started.</li><li><em>Many Data: </em>If your callback is called at all, it is precisely the parameter of the callback that gets the data.</li><li><em>Sort of Composable: </em>Functions compose, and you could create some operator that takes two callbacks and sequences their execution, or runs both callbacks in parallel. However: Unlike other primitives, the actual asynchronous work doesn’t return some data structure that you can easily manipulate. Composition is not clean.</li><li><em>Coupled Execution Context:</em> The caller cannot choose on which execution context your work will execute.</li><li><em>Locally Scoped</em>: You cannot poke a callback without having reference to it.</li><li><em>Easy to Learn: </em>A callback is just a function.</li></ul><h3><strong>On Android</strong></h3><h4>AsyncTask (or “Thread” etc)</h4><ul><li><em>Referentially Transparent: </em>You must `execute()` or `run()` the AsyncTask or thread explicitly</li><li><em>Side-effect Data:</em> Threads and AsyncTasks don’t return any result when they complete. There is no exposed reference to some data structure that represents the data that will be produced.</li><li><em>Not Composable: </em>You cannot combine two AsyncTasks to produce a new AsyncTask. You cannot combine two Threads to produce a new thread.</li><li><em>Coupled Execution Context: </em>Execution context is the Thread. In an AsyncTask, the background work is done in a background thread, the foreground work is done in a UI thread.</li><li><em>Locally Scoped: </em>You cannot easily poke a thread or an async task without an instance of the AsyncTask or Thread object (mostly).</li><li><em>Easy to Learn: </em>Good documentation, simple.</li></ul><h4>Java Future</h4><ul><li><em>Effectful: </em>The mere existence of a future implies it is running</li><li><em>One Datum: </em>a Future returns exactly one piece of information when the work completes or it will throw an exception.</li><li><em>Not Composable: </em>You cannot combine two Java Futures to produce a new Java Future.</li><li><em>Coupled Execution Context: </em>The Java Future is the result of adding some piece of work to an Executor, the executor determines the execution context. Therefore, the existence of a Future is coupled to the execution context. Also: Getting data out of a Java Future requires potentially blocking some execution context.</li><li><em>Locally Scoped: </em>You cannot poke a future from afar.</li><li><em>Easyish to Learn: </em>A Future is just an asynchronous value.</li></ul><h4>EventBus (like Guava’s; greenrobot/EventBus; Otto)</h4><ul><li><em>Effectful: </em>The bus can produce messages — in order to listen you must attach callbacks.</li><li><em>Many Data: </em>The bus can fire many times.</li><li><em>Not Composable:</em> You cannot easily combine two or more buses to make a new bus.</li><li><em>Usually Decoupled Execution Context:</em> A good event bus library lets you supply some executor or handler that is in charge of scheduling the work. However, the scheduling is tied to the bus, not an atom of work.</li><li><em>Locally Scoped: </em>You cannot poke an eventbus without a reference to it, unless you purposefully make it globally accessible.</li><li><em>Easy to Learn: </em>Simply a bus to send and receive events</li></ul><h4>ListenableFuture (Guava)</h4><ul><li><em>Effectful: </em>The mere existence of a future implies it is running.</li><li><em>One Datum: </em>a ListenableFuture returns exactly one piece of information when the work completes or fails with an exception.</li><li><em>Composable: </em>Transform (flatmap), AllAsList (sequence), etc. allow for the composition of ListenableFutures.</li><li><em>Coupled Execution Context:</em> The existence of a future implies it has already started in some context. See Java Future.</li><li><em>Locally Scoped:</em> You cannot poke it with a reference to the object</li><li><em>Easy-ish to Learn: </em>Slightly more features than a Java Future, but uses common functional programming idioms like `map`.</li></ul><h4>RxJava (reactive streams)</h4><ul><li><em>Referentially Transparent:</em> Doesn’t start until you start it.</li><li><em>Many Data: </em>An Rx Stream can fire many times before finishing.</li><li><em>Composable: </em>Rx Streams compose in many many ways in sequence and in parallel and with interleaving.</li><li><em>Decoupled Execution Context:</em> Execution contexts of the work and of listeners can be independently changed and chained on async work.</li><li><em>Locally Scoped:</em> You cannot poke a react stream without a reference to it.</li><li><em>Hard to Learn: </em>There are many operators to learn, and you must understand how the streams work in order to avoid overflowing buffers.</li></ul><h3><strong>On iOS</strong></h3><h4>Dispatch_async work</h4><ul><li><em>Effectful: </em>When work is dispatched, it will eventually run.</li><li><em>Side-effect Data: </em>Dispatched work does not return a value explicitly.</li><li><em>Not Composable: </em>If you’ve dispatched work twice, you cannot combine them into one thing.</li><li><em>Coupled execution context: </em>The execution context is precisely the dispatch queue you chose when you queue work.</li><li><em>Locally Scoped:</em> You can prod work only if you have a reference to the work itself.</li><li><em>Easy to learn: </em>Give the dispatch_async a block, and it will run.</li></ul><h4>NSOperation</h4><ul><li><em>Referentially Transparent:</em> An NSOperation must explicitly be started (usually with the help of an NSOperationQueue).</li><li><em>Side-effect Data:</em> NSOperations don’t return values, so in order to get information you must perform side-effects.</li><li><em>Not Composable</em>: You can add dependencies to NSOperations, but you must do so through NSOperationQueue side-effects.</li><li><em>Decoupled Execution Context</em>: The execution context depends on the NSOperationQueue you add the work to.</li><li><em>Locally Scoped:</em> You need an NSOperation in order to poke it.</li><li><em>Hardish to Learn: </em>NSOperation and NSOperationQueue have a lot of power, but that power comes with more learning necessary to understand its use.</li></ul><h4>NSNotifications</h4><ul><li><em>Effectful:</em> When a notification is scheduled, the listeners will eventually be called. It is not referentially transparent.</li><li><em>Side-Effect Data:</em> Notification handlers do not return a value when they are done.</li><li><em>Not Composable: </em>Two notifications cannot be combined.</li><li><em>Coupled Execution Context:</em> NSNotificationCenter will call your work on the same dispatch queue that you sent the notification on.</li><li><em>Globally Scoped:</em> You can listen to an NSNotification from anywhere.</li><li><em>Easy to Learn: </em>It’s just an event bus that is implicitly instantiated in the global scope.</li></ul><h4>Futures (via BrightFutures)</h4><ul><li>Exactly like ListenableFutures except the Error parameter is also generic to allow for more type-safety (and you can use zero case enums to forbid errors statically).</li></ul><h4>RxSwift (similarly ReactiveCocoa)</h4><ul><li>Exactly like RxJava.</li></ul><h3><strong>The Dream</strong></h3><p>For some reason, there doesn’t exist a simple one-datum concurrency primitive on iOS or Android that is referentially transparent, composable, has a decoupled execution context, and is locally scoped. You shouldn’t have to use Rx for tasks that logically need to complete once. Scala has a few implementations of such a primitive: `Task`, but both the iOS and Android communities should get on this!</p><h3><strong>In Summary</strong></h3><p>These six categories define a concurrency primitive: Referential transparency, returned data, composability, the coupling of execution context, scoping, and learning difficulty.</p><p>My advice: Avoid side-effects, avoid global state, decouple execution context, prefer composable primitives. Choosing fire once or fire many should depend on the problem you are trying to solve. Choosing an easy or hard to learn primitive should depend on how much time you are willing to invest in learning before getting work done. Obviously, make sure you pick the right tool for the right job.</p><p>This post should give you some idea of how to categorize your concurrency primitives if I did not cover it myself, and should help you analyze other concurrency options for your platform. Your choice of concurrency primitive matters: In a modern application, you will be using this primitive all over your codebase — utilizing the right concurrency primitive will let you and your team achieve both a maintainable and performant application.</p><p><em>Originally published at </em><a href="http://hkr.me/concurrency.html"><em>hkr.me</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eea7b871e0ac" width="1" height="1" alt=""><hr><p><a href="https://medium.com/math-camp-engineering/concurrency-categorization-eea7b871e0ac">Concurrency Categorization</a> was originally published in <a href="https://medium.com/math-camp-engineering">Math Camp Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin, the somewhat obscure modern Android-friendly programming language]]></title>
            <link>https://medium.com/math-camp-engineering/kotlin-3e963864db9e?source=rss----7d82b16c25cf---4</link>
            <guid isPermaLink="false">https://medium.com/p/3e963864db9e</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Brandon Kase]]></dc:creator>
            <pubDate>Tue, 15 Mar 2016 20:21:33 GMT</pubDate>
            <atom:updated>2016-03-17T08:36:59.864Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://developer.apple.com/swift/">Swift</a> is a terse functional programming language with high Objective-C interoperability used for iOS development.</p><p>Swift is better than Objective-C.</p><p>You already know this.</p><p>But you probably don’t know what Kotlin is.</p><p><a href="https://kotlinlang.org/">Kotlin</a> is Swift for Android. [1]</p><p>You’re not using Objective-C anymore, so why are you using Java?</p><p>We built <a href="http://tryroll.com/">Roll for Android</a> in <a href="https://kotlinlang.org/">Kotlin</a>.</p><h3>What is Kotlin? Really.</h3><p>Kotlin is a terse swift-like functional programming language on the JVM platform with high Java interoperability. Kotlin is unique in that its standard library and runtime are extremely small in bytes, yet very powerful. Most is eliminated at compile time (in contrast to <a href="http://www.scala-lang.org/">Scala</a>), so it can feasibly be used in memory “constrained” environments like Android (not embedded systems, but smartphones):</p><pre>val immutableVariable = &quot;a string&quot; </pre><pre>// a function <br>fun inc(x: Int): Int { <br>  return x+1<br>} </pre><pre>// anonymous function bound to a variable <br>val inc: (Int) -&gt; Int = { it + 1 }</pre><h3>Why Kotlin and not “X”?</h3><p>We wanted to iterate on a lot of the software structure we came up with for our <a href="http://tryroll.com/">Swift iOS app</a>, and for a bunch of pieces we needed a powerful type-system. So rather than just stick with Java — it’s way too verbose — we started looking at alternatives. We wanted a strong static type system, yet the obvious choice, Scala, has too much overhead for Android. Kotlin really stood out for us. <a href="https://docs.google.com/document/d/1ReS3ep-hjxWA8kZi0YqDbEhCqTt29hG8P44aA9W0DM8/edit?hl=en&amp;forcehl=1">This document by Jake Wharton at Square</a> made the decision easier. So we took the risk.</p><h3>Great Features</h3><ul><li><a href="https://kotlinlang.org/docs/reference/null-safety.html">Null type safety!</a></li></ul><p>In Kotlin, just like in Swift, optional values are tracked through the type-system. You will not have null pointer exceptions in your Kotlin code:</p><pre>val x: String? = tryToGetString()<br>// x is not a String (it could be null)<br> <br>if (x != null) { <br>  // x is smart-casted to a String here! <br>}</pre><ul><li><a href="https://kotlinlang.org/docs/reference/inline-functions.html">Lambdas can be inlined!</a></li></ul><p>An under appreciated feature of Kotlin (if you’re targeting Android for example) is the zero overhead higher order functions on collections.</p><p>In Kotlin these standard library functions are inlined and desugared to for-loops.</p><p>Thus, you can write expressive Scala-like code but without all the anonymous inner class overhead (which while negligible on servers, is <a href="http://developer.android.com/training/articles/memory.html">an issue in Dalvik</a> and possibly Android’s new runtime ART [no evidence], so Android devices will be affected):</p><pre>val strs = listOf(&quot;this&quot;, &quot;is&quot;, &quot;a&quot;, &quot;bunch&quot;, &quot;of&quot;, &quot;words&quot;)</pre><pre>val charCount = strs.map{ it.length }.fold(0, { a, b -&gt; a + b })</pre><pre>val evenWords = strs.filter{ it.length % 2 == 0 }</pre><ul><li><a href="https://kotlinlang.org/docs/reference/inline-functions.html#reified-type-parameters">Reified generics!</a></li></ul><p>Reified generics in Kotlin let you use the generic T in your code at runtime. For example, we’ve used reified generics to implement a clean API for dictionary deserialization to model data classes. Here, we attempt to deserialize an untyped map into some strongly typed data class of type T (like a User):</p><pre>private inline fun deserialize&lt;reified T&gt;(dict: Map&lt;String, Any?&gt;): T { ... } <br>// usage val model = deserialize&lt;ModelData&gt;(modelDataDict)</pre><ul><li><a href="https://kotlinlang.org/docs/reference/extensions.html">Statically resolved extension functions!</a></li></ul><p>Extension functions in Kotlin allow you to add “methods” to objects. These are resolved statically so there is no performance overhead or runtime confusion.</p><p>Extension functions even work on generic “primitives” like Functions or optional types.</p><p>For example, we have defined monadic bind on options (like if-let in Swift if it were an expression and not a statement) and use it all over our codebase [2]:</p><pre>inline fun &lt;T, R&gt; T?.bind(transform: (T) -&gt; R?): R? =<br>    this?.let(transform)</pre><ul><li><a href="https://kotlinlang.org/docs/reference/classes.html#sealed-classes">Algebraic data types and pattern matching!</a></li></ul><p>Algebraic data types or (ADTs) (also called Sum types or tagged unions) allow you model data that can be one of several different variants. Once you’ve used ADTs, you can’t live with out them. The compiler will enforce that you have exhaustively handled all the cases. Swift has them, and as of recently Kotlin does too.</p><p>Here is an example of the model for a button that is either disabled, shows a number, or shows info about a user:</p><pre>sealed class ButtonState { <br>  object Disabled: ButtonState()<br>  class ShowingNum(val num: Int): ButtonState()<br>  class ShowingPerson(val u: User): ButtonState()<br>}</pre><pre>// this state shows 5<br>val showFiveState = ShowingNum(5)</pre><pre>// all states handled (enforced by the compiler!)<br>fun printbutton(state: ButtonState): String = when (state) { <br>  is ShowingNum -&gt; &quot;&lt;{state.num}&gt;&quot;<br>  is ShowingPerson -&gt; &quot;&lt;{state.u.name}&gt;&quot;<br>  Disabled -&gt; &quot;-&lt;&gt;-&quot;<br>}</pre><ul><li>Single-method interfaces/classes can be represented as lambdas! aka</li></ul><pre>view.setOnClickListener(new View.OnClickListener() { <br>  @Override public void onClick(View v) {<br>    /* do something */<br>  }<br>});</pre><p>becomes</p><pre>view.setOnClickListener { /* do something */ }</pre><p>This is great for things like <a href="http://reactivex.io/">RxJava</a>.</p><p>Speaking of which, the Java interoperability is first-class and fantastic. Any Android Java libraries we’ve tried work great from Kotlin.</p><h3>Libraries Created</h3><p>Using these features, we’ve built:</p><ul><li>a simple dependency injection framework</li><li>a handful of really useful extensions on things like T? (for example monadic bind)</li><li>a hack for algebraic data types and pattern matching (before sealed class was released)</li><li>a single-atom-state functional reactive UI component framework</li><li>and of course a fairly complex app.</li></ul><p>Android Studio’s Kotlin support is fantastic (good job JetBrains!) — it’s a pleasure to use.</p><h3>Build Time</h3><p>The biggest issue for us is the build time. Gradle builds used to take around 5–10 minutes. We invested a week of engineering time in getting a <a href="https://buckbuild.com/">Buck</a> build working alongside Gradle. Buck builds are 3 minutes max and usually are around 45 seconds. With the most recent Android Studio update, incremental Gradle builds are back down under a minute. This is not too much longer than a pure Java app of our size would take to build.</p><h3>Use Kotlin!</h3><p>Kotlin is great! The time saved due to the benefits of Kotlin make up for any time lost optimizing build times.</p><p>If you’re interested in learning more, get in touch. We’re hiring!</p><p>Note: this post was adapted from an earlier <a href="https://news.ycombinator.com/item?id=9947020">HackerNews comment</a></p><p>[1] aside: It is more accurate to say Swift is the Kotlin of iOS since Kotlin has existed in the open for many more years than Swift. Due to Kotlin’s obscurity, however, we’re forced to make the Kotlin to Swift comparison.</p><p>[2] Thanks @<a href="https://twitter.com/daniil_vodopian">daniil_vodopian</a> for the terser bind definition</p><p><em>Originally published at </em><a href="http://hkr.me/kotlin.html"><em>hkr.me</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e963864db9e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/math-camp-engineering/kotlin-3e963864db9e">Kotlin, the somewhat obscure modern Android-friendly programming language</a> was originally published in <a href="https://medium.com/math-camp-engineering">Math Camp Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hello World]]></title>
            <link>https://medium.com/math-camp-engineering/hello-world-9e4943285ca2?source=rss----7d82b16c25cf---4</link>
            <guid isPermaLink="false">https://medium.com/p/9e4943285ca2</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Benjamin Garrett]]></dc:creator>
            <pubDate>Tue, 15 Mar 2016 20:11:47 GMT</pubDate>
            <atom:updated>2016-03-15T20:11:31.691Z</atom:updated>
            <content:encoded><![CDATA[<h3>At Math Camp, we believe that the choice of development language has far reaching effects.</h3><p>From defining aspects such as type safety and the use of pointers vs. references down to the small and stylistic details such as supporting only a single public class per file, the language utilized affects not just the end product but also how the programmer thinks and talks about it, what is possible, and who can understand the system.</p><p>As discussed by Paul Graham [1], languages also vary in power. You will end up with a much different program by starting out in Assembly vs. Lisp. The Assembly program requires the programmer to think about how the processor works on an instruction level. In Lisp, the low level concerns have been abstracted away, freeing the programmer to consider the problem at hand more deeply.</p><p>As a startup focused on mobile applications, we want to pick languages that are native to our core platforms but are also as powerful as possible. Most importantly, we want to be immersed in modern languages to grow as engineers and find elegant and reusable solutions to old problems.</p><p>We’ve built plenty of mobile applications in Java and Objective-C using a Model View Controller design. MVC was designed nearly 50 years ago when computing and user interfaces were much simpler. We want to use languages that make it easy to try new approaches such as functional reactive and unidirectional data flow-based user interfaces.</p><p>Therefore, we’ve chosen to use Swift on iOS, Kotlin on Android, and Go on the server. The following posts on this blog will go into greater detail about how we’re using these languages and what approaches we land on. We hope to update frequently and also open source interesting projects we build along the way. Thanks for joining us on this journey.</p><p>[1] Paul Graham: Beating the Averages<br><a href="http://www.paulgraham.com/avg.html">http://www.paulgraham.com/avg.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e4943285ca2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/math-camp-engineering/hello-world-9e4943285ca2">Hello World</a> was originally published in <a href="https://medium.com/math-camp-engineering">Math Camp Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>