<?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 Jeremy Song on Medium]]></title>
        <description><![CDATA[Stories by Jeremy Song on Medium]]></description>
        <link>https://medium.com/@jeremy.song?source=rss-80a8f602bf23------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Hj21-QQj5vBRCToK8g1GIg.jpeg</url>
            <title>Stories by Jeremy Song on Medium</title>
            <link>https://medium.com/@jeremy.song?source=rss-80a8f602bf23------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 17:17:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jeremy.song/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[Lessons on Delivering a Large Project]]></title>
            <link>https://medium.com/stochastic-stories/lessons-on-delivering-a-large-project-9fcdd8d3b9a4?source=rss-80a8f602bf23------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fcdd8d3b9a4</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Jeremy Song]]></dc:creator>
            <pubDate>Thu, 05 Oct 2023 05:02:39 GMT</pubDate>
            <atom:updated>2023-10-05T05:02:39.407Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently led teams in my org to complete a 2-year project that re-architected a big data processing platform. I gave an internal talk about some lessons we learned in this project. I am sharing those lessons here as I think they might benefit engineers outside my company too.</p><h3>Incremental Delivery</h3><p>One of the things we insisted on at the very beginning of the project is incremental delivery: we want to make sure we deliver small features frequently at pace. Looking back, this was the right decision because <em>incremental delivery improves morale</em>. We, engineers, are builders and like to see our work make a clear impact as soon as possible. Nothing is more rewarding than seeing one project completed and putting us closer to the finishing line.</p><p>Incremental delivery also <em>gives leadership the confidence</em> that we are making meaningful progress toward our goal. In this project, we use a single, easy-to-understand metric to track the progress. And we present this metric in quarterly business reviews with leadership. I rarely got asked when we would fully launch the project because leadership is able to see the number moving in the right direction every quarter.</p><p>Lastly, incremental delivery allows us to <em>benefit from the new system sooner</em>. In our case, since last year, the workload on the legacy system has increased by more than 100%. Thanks to incremental delivery, we were able to shift most of the workload to the new system. Without incremental delivery, the legacy system had to take all the workload. We either had to scale up the old system even more, which we knew was approaching its scaling limit or had to throttle our biggest customers.</p><h3>Software Correctness</h3><p>In this project, we spent almost 30% of the time just to ensure the software correctness. Due to the nature of the project, a subtle bug in the code generation would be very difficult to detect and could lead to a huge customer impact.</p><p>We know that ensuring software correctness and eliminating bugs is difficult. But we made lots of progress on that front. We used lightweight formal method and shadow testing. We borrowed the lightweight formal method from <a href="https://www.amazon.science/publications/using-lightweight-formal-methods-to-validate-a-key-value-storage-node-in-amazon-s3">this</a> S3 paper. We developed a shadow testing framework so that every data processing job will be executed on old and new platform and compare the results. The result is that we rarely had any bugs in production since the launch.</p><p>The lesson here is that traditional unit test is not enough. <a href="https://dev.to/jdsteinhauser/intro-to-property-based-testing-2cj8">Property-based testing</a> and lightweight formal method is the new unit test, and the industry is already moving in that direction. If you look at the newer languages like Rust, the Rust community developed several property-based testing, and formal verification libraries and tools. Similar property-based testing libraries also exist in popular programming languages such as Java, Python, and Scala. I strongly encourage everyone to start using it.</p><h3>On re-architecting</h3><p>In this project, the initial goal is just to move the workload from the old platform to the new one. Typically, we would choose a lift-and-shift approach. But we asked two important questions: 1) what do customers really care about? 2) what are the use cases that have not been served well?</p><p>So <em>we worked backwards from customers</em>. We talked to our customers to get answers to those questions and we used those answers as our North Star to build the new system, which ended up drastically different from the old one.</p><p><em>Innovation should be every software development team’s core value.</em> Don’t be afraid to spend time innovating. You need to work backwards from customers to understand the use case, you also need to read papers, watch talks, and learn from other people to get inspired on novel solutions. Always remember that we owe our customers to innovate on their behalf at pace.</p><h3>People/team</h3><p>When people talk about building systems, they typically talk about software and hardware. <em>But re-architecting is not just about changing software/hardware. It’s also about re-architecting the team.</em> In many software companies, the organizational structure always mirrors the system architecture. In this <a href="https://www.youtube.com/watch?v=sc3J4McebHE">talk</a>, VP/Distinguished Engineer Andy Warfield from AWS talked about how Amazon S3 org structure closely mirrors the S3’s system architecture. When system evolves and the discrepancies happen, the org will spend lots of effort to fix that. That’s just the nature of software.</p><p>In this project, we did two things to make sure our org structure mirrors the system architecture. <em>We create a virtual team so that we can move extremely fast</em>. A virtual team is a team within a two-pizza team, but we had our own standup progress and different way to track the project progress. A small team allows us to make two-way door decisions very fast.</p><p>We realized that there should be a dedicated team to take ownership of one important component in the architecture. So we engaged with our leadership and did a lot of work to <em>make sure there was a right team to own it</em>. We then helped that team to create a roadmap and get them to develop that component.</p><p>The lesson here is that, for large projects, if the org structure does not map to the system architecture, it will impact delivery speed. So work with your leadership to fix that.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fcdd8d3b9a4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stochastic-stories/lessons-on-delivering-a-large-project-9fcdd8d3b9a4">Lessons on Delivering a Large Project</a> was originally published in <a href="https://medium.com/stochastic-stories">Stochastic Stories</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Solve Software Problems]]></title>
            <link>https://medium.com/stochastic-stories/how-to-solve-software-problems-d15a1f32a714?source=rss-80a8f602bf23------2</link>
            <guid isPermaLink="false">https://medium.com/p/d15a1f32a714</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Jeremy Song]]></dc:creator>
            <pubDate>Mon, 01 Feb 2021 23:23:42 GMT</pubDate>
            <atom:updated>2021-02-02T00:04:21.407Z</atom:updated>
            <content:encoded><![CDATA[<p>As software engineers, a big part of our job is to solve software problems, big or small. Big software problems are ambiguous and require lots of thinking, discussion, and debate. Typical big software problems are to improve architecture efficiency, to propose technical solutions to ambiguous business problems, etc. Small software problems have smaller scopes and less ambiguous than big software problems. Typical small software problems are fixing bugs, resolving technical difficulties.</p><p>No matter how big or small the software problems are, they both can be solved in similar ways. Over the years, I have developed my own (not necessarily unique) methodologies to tackle those software problems.</p><h4>Understand the problem</h4><p>Before solving a problem, you need to have a deep understanding of the problem. When encountering a problem, ask the following questions, in this specific order:</p><ol><li>Why is this even a problem? There are always some problems in the world for you to solve. If it’s problem that hurts no one, it’s not worth solving.</li><li>What will happen if we don’t solve this problem? This again questions the necessity of solving this problem, even after you confirm this is a real problem. Use your SLA, estimated customer impact, your product, and business directions to help you find the answer.</li><li>What’s the root cause of this problem? Lots of problems we encounter, on the surface, are symptoms, not root causes. You need to dive deep and understand the root cause. If you receive lots of tickets because the error rate breaches the threshold, find out the root cause, and don’t just adjust the threshold, yet.</li></ol><h4>Understand how the system works</h4><p>You cannot possibly identify the correct root cause if you don’t understand how the system works (unless you’re extremely lucky). Before even starting to root causing a problem, try to have a basic understanding of how the system works. If your requests are randomly dropped/rejected by the service, try to understand how VIP routes your requests to the service hosts. If you don’t see the metrics you expect, understand how those metrics are being sent to the dashboards. Then you will have your hypothesis.</p><h4>Write down the problem and solutions</h4><p>Root causing a problem can be difficult and tricky because there could be lots of possibilities. Even if you are convinced that a root cause has been found, applying a proposed solution may still not solve the problem.</p><p>In this case, the best way to move forward is to write down the problem and the solutions you have tried. Writing is a magical process because it allows you to think critically and logically. When you go back and read what you have just written, you may realize that you have identified the wrong root cause, or the solutions you just tried would have never worked in the first place.</p><h4>Use Occam’s Razor</h4><p>When root causing the problems, try to propose multiple hypotheses. For example, when you are observing a high error rate in the service metrics, you could have several hypotheses:</p><ol><li>Those errors are caused by clients sending invalid requests.</li><li>Those errors are caused by service throttling their requests.</li><li>The service is emitting the wrong metrics.</li><li>The dashboard is broken and displays the wrong data.</li></ol><p>Note that those hypotheses are ranked by the likelihood, guided by Occam’s razor — the simplest explanation is usually the correct one, unless being proven otherwise.</p><h4>Use 50/50 rule</h4><p>Use <strong>at least</strong> 50% of the time to understand the problem, propose a hypothesis, research the solutions, write them down, pick the best/most likely solution. I call this “preparation step”. Then use the rest of the time to implement the solution (aka implementation step).</p><p>If you spend less than 50% on the preparation step, you think you’re saving the total problem-solving time, but unfortunately, it’s not likely to be the case. The time you save by not doing some work in the “preparation step” will cost you more in the “implementation step”. If you don’t fully understand the problem, you will implement the wrong solution, which may cause more problems than it solves.</p><h4>Ask for help, appropriately</h4><p>Don’t be afraid of asking for help. Most of the problems you encounter are not new and most of the solutions are already there. Sometimes you just need a simple pointer to correctly diagnose the problem and reuse an existing solution.</p><p>When asking for help, do it appropriately. It means that while your colleagues are there to help you, their time is valuable. The way of showing your respect to their time is to do as much work in the “preparation step” as possible. Writing down your thoughts on the problems and potential solutions is a concrete way to show that. When someone reaches out to me for help, I would typically ask for a short document describing the problems and the solutions they have tried. This encourages them to write down the problem and make them go through a critical thinking process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d15a1f32a714" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stochastic-stories/how-to-solve-software-problems-d15a1f32a714">How to Solve Software Problems</a> was originally published in <a href="https://medium.com/stochastic-stories">Stochastic Stories</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using CRDT to Resolve Conflicted Operations]]></title>
            <link>https://medium.com/stochastic-stories/using-crdt-to-resolve-conflicted-operations-a21cb48a167e?source=rss-80a8f602bf23------2</link>
            <guid isPermaLink="false">https://medium.com/p/a21cb48a167e</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[crdt]]></category>
            <dc:creator><![CDATA[Jeremy Song]]></dc:creator>
            <pubDate>Sat, 23 May 2020 21:32:22 GMT</pubDate>
            <atom:updated>2020-05-23T21:51:08.537Z</atom:updated>
            <content:encoded><![CDATA[<p>In the conversation I had with some software engineers, I realized that the concept of CRDT (Conflict-free Replicated Data Type) is not well known. I want to raise the awareness of the ubiquitousness of out-of-order, duplicated operations/data in distributed systems and give a very simple introduction on how CRDT can resolve those conflicts.</p><p>The problem we are facing in designing distributed systems that support both reads and writes is straightforward, but also critical. As we accepts data/operation, we cannot assume the data arriving to the system is properly ordered and without duplication. For example, an ordering system, which is responsible for sending reliable notifications about order and shipment level events, can be built on top of AWS SNS/SQS and both systems do not guarantee the order of the messages and only guarantee the messages will be delivered <strong><em>at last once</em></strong>. When building a data storage system that persists customers’ orders, we need to resolve the conflicts such as a cancellation message can write before the ordering message. In a broader sense, as long as at least one of upstream data pipelines do not guarantee the order of the events, undesired behavior will happen. In reality, out-of-order/duplicated messages are very common. Hosts and network failures can lead to retries; a cluster without consensus distributed algorithms can send messages without consulting each other.</p><p>Conflict-free Replicated Data Type (CRDT) is a set of data structures that can be replicated across network and can guarantee the data to be consistent and correct eventually. Those data structure do not make assumptions on how the data are replicated, or the order of the data it arrives. Details of those data structures and the mathematical prove of their correctness can be found in these two papers:</p><ul><li><a href="https://hal.inria.fr/file/index/docid/555588/filename/techreport.pdf">https://hal.inria.fr/file/index/docid/555588/filename/techreport.pdf</a></li><li><a href="https://hal.inria.fr/hal-00932836/file/CRDTs_SSS-2011.pdf">https://hal.inria.fr/hal-00932836/file/CRDTs_SSS-2011.pdf</a></li></ul><p>Here I gave two examples on how CRDT can be used.</p><h4>Example 1: Using key-value database to store most-recent data</h4><p>Imagine we want to build a system that allows users to stores their data and the system should vend the most recent data <em>eventually</em>. <strong>Eventually</strong> here means that if users submit two operations set (key_1, value_1) at t1 and set (key_1, value_2) at t2, where t2 &gt; t1, no matter what order and duplicates they send to our system, the system should vend (key_1, value_2) after certain reasonable amount of time.</p><p>For simplicity, let’s assume that users cannot delete the key. If we simply store key-value pair in the table, this won’t work because if (key_1, value_2) is written to the table before (key_1, value_1), (key_1, value_1) will be stored in the table forever.</p><p>What CRDT proposes, is to use additional field to resolve the conflicts. Many systems simply use system clock or physical timestamp to denote the order of the operations/data. Timestamp can be either supplied from the clients or automatically generated within the system. But CRDT does not make assumption on what types of timestamp we use: it can be physical time, can be logic clock, etc.</p><p>What if we want to support deletion as well? In this case, we cannot simply delete the item from the database. Imagine users submit two operations <em>set </em>(key_1, value_1) at t1 and delete key_1 at t2, where t2 &gt; t1. If deletion operation arrives before set operation, the (key_1, value_1) will be stored in the database forever!</p><p>The solution proposed in CRDT is to retain the deletion records and mark it with a special deletion flag, commonly known as tombstone flag. A record with tombstone flag is typically not visible to clients, but used internally to make sure we don’t overwrite a deleted record. For example, when receiving the deletion operation, instead of deleting the data, we update the record to (key_value, value_1, tombstoned, timestamp_2), so that when we receive the set (key_1, value_1, timestamp_1) operation after deletion operation, if timestamp_1 &lt; timestamp_2, the set operation will be ignored by the system.</p><h4>Example 2: Adding and deleting items in a set</h4><p>Imagine we want to build a feature that allows users to add and remove individual items to and remove a set. For example, the set could contains a list of customer IDs who are eligible for a promotion. If we allow users to perform those operation concurrently and want to resolve those conflicted writes to this set, special cares are needed.</p><p>To explain this further, if the existing set contains three items {value_1, value_2, value_3}, and there are two users want to apply delta updates to this set concurrently. User A tries to delete value_3 and user B wants to add the same item back. If we cannot resolve the order of the operation, we will get divergent results which could be ether {value_1, value_2, value_3} or {value_1, value_2}.</p><p>There are two ways to solve this problem. We can use the same approach used in the previous example: instead of storing only key-value pair in the set, we can store additional information in each item (e.g. event time) to help us resolve the conflicts.</p><p>But what if you cannot add additional information to the item because this will introduce non-backward-compatible changes, or simply because the limitation of the system? CRDT proposes that you can actually maintain two sets: one for addition, one for deletion, each of which stores item and additional information to resolve the conflict. Whenever users request the data, we merge both addition and deletion sets by resolving the conflict data (e.g. comparing the event time of the same item from both sets).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a21cb48a167e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stochastic-stories/using-crdt-to-resolve-conflicted-operations-a21cb48a167e">Using CRDT to Resolve Conflicted Operations</a> was originally published in <a href="https://medium.com/stochastic-stories">Stochastic Stories</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solve Urn of Mystery]]></title>
            <link>https://medium.com/stochastic-stories/solve-urn-of-mystery-4c0d9bcd893e?source=rss-80a8f602bf23------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c0d9bcd893e</guid>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Jeremy Song]]></dc:creator>
            <pubDate>Wed, 19 Dec 2018 08:38:41 GMT</pubDate>
            <atom:updated>2018-12-19T20:14:52.243Z</atom:updated>
            <content:encoded><![CDATA[<h3>Another Approach to Solve Urn of Mystery</h3><p>Urn of Mystery is an example in the book <a href="https://www.amazon.com/How-Measure-Anything-Intangibles-Business-ebook/dp/B00INUYS2U/ref=mt_kindle?_encoding=UTF8&amp;me=&amp;qid=">How to Measure Anything: Finding the value of Intangibles in Business</a>. Douglas (the author) uses this example to convey a rule: The Single Sample Majority Rule.</p><blockquote>The Single Sample Majority Rule</blockquote><blockquote>Given maximum uncertainty about a population proportion — such that you believe the proportion could be anything between 0% and 100% with all values being equally likely — there is a 75% chance that single randomly selected sample is from the majority of the population.</blockquote><p>Urn of Mystery is a contrived example to prove this. Suppose we have a warehouse full of large urns. Each urn is filled with marbles and each marble is either green or red. The percentage of marbles that are green can be anything between 0% and 100%, and all percentages are equally likely. The remaining portion of the urn is red marbles. We draw one urn at random from the entire warehouse. If we draw one marble from the urn and it’s green, what’s the probability of the majority of the marbles in this urn are green?</p><p>The answer is 75% and the author uses a solution that involves simple math (with Bayes’ theorem) to get this answer.</p><h4>Another Approach</h4><p>Here I would like to propose a different way to solve this problem — a pure Bayesian approach. This solution involves a little bit more math as we will use Beta distribution and conjugate distributions. However, this solution is more general.</p><p>The question “What’s the probability of the majority of the marbles in this urn are green” can be decomposed into two questions:</p><ol><li>What’s the distribution of the percentage of green marbles in the urn, given that we draw one green marble from it?</li><li>What’s the probability that percentage is greater than 0.5 (being majority)?</li></ol><p>The setup:</p><ul><li>Let θ be the percentage of marbles that are green in the urn</li><li>Let X be the observation of the draw.</li><li>Since we draw one urn at random from the entire warehouse, we can safely assume the prior distribution is uniform distribution: U(0, 1).</li><li>We draw one marble from the urn. The probability of that marble being green approximately follows bernoulli distribution: Bern(θ).</li></ul><p>According Bayes’ Theorem:</p><p>P(θ|X=Green) ∝ P(X=Green|θ)P(θ)</p><p>U(0,1) can be written as beta distribution Beta(1,1). Thus,</p><p>P(θ|X=Green) ∝ Bern(θ)·Beta(1,1)</p><p>In this case, Bernoulli distribution and Beta distribution are conjugate distribution with Beta distribution as prior. This means that P(θ|X=Green) is a Beta distribution too. With some math, we can get P(θ|X=Green) ~ Beta(2,1).</p><p>So far we solve the question 1. We now know that the distribution of the distribution of the percentage of green marbles in the urn (given that we draw one green marble).</p><p>To solve question 2, all we need is to figure out: P(0.5 &lt; θ ≤ 1| X = Green) = 1- P(0 ≤ θ ≤ 0.5|X = Green), which can be done in python easily:</p><pre>&gt;&gt;&gt; from scipy.stats import beta<br>&gt;&gt;&gt; a = 2<br>&gt;&gt;&gt; b = 1<br>&gt;&gt;&gt; 1 - beta.cdf(0.5, a, b)<br>0.75</pre><p>The author also calculates the probability of the green marble being majority if we draw more marbles. This can be easily solved using the approaches discussed above. For example:</p><ul><li>If the second draw is green marble: 1 — beta.cdf(0.5, 3, 1) , which is 0.875.</li><li>If the second draw is red marble: 1- beta.cdf(0.5, 2, 2) , which is 0.5.</li></ul><h4>Prior is important</h4><p>In this problem, our prior distribution is uniform distribution, which is Beta(1,1), which is why a single data point could change the probability from 50% to 75%.</p><p>But think about another similar problem: if this is not urn, but a coin that is randomly draw from a mint. You flip the coin once, you get a head. Will you say that the coin has 75% probability of biased to head? Probably no.</p><p>In the case of flipping coin, we usually don’t assume that the prior is Beta(1,1). Instead we probably choose Beta(100, 100) or Beta(1000, 1000). When we choose Beta(1000,1000) as prior, we basically assume that someone already flipped the coin from that mint 1998 times and they got 999 heads and 999 tails, even though their initial prior was Beta(1,1). If we flip a coin and got a head, the probability of the coin is based to head is 1 — beta.cdf(0.5, 1001, 1000) , or 0.5089, which is hardly biased at all.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c0d9bcd893e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stochastic-stories/solve-urn-of-mystery-4c0d9bcd893e">Solve Urn of Mystery</a> was originally published in <a href="https://medium.com/stochastic-stories">Stochastic Stories</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Bean Validation: a Classic Example of Separation of Mechanism and Policy]]></title>
            <link>https://medium.com/@jeremy.song/java-bean-validation-a-classic-example-of-separation-of-mechanism-and-policy-1f55829fd728?source=rss-80a8f602bf23------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f55829fd728</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[validation]]></category>
            <dc:creator><![CDATA[Jeremy Song]]></dc:creator>
            <pubDate>Sat, 25 Aug 2018 22:56:47 GMT</pubDate>
            <atom:updated>2018-08-25T22:57:35.960Z</atom:updated>
            <content:encoded><![CDATA[<h3>Abstract</h3><p>We recently discovered that Java <a href="https://beanvalidation.org/2.0/">Bean Validation</a> is a very powerful, extendable way to validate the Java POJO. We found that by using Bean Validation, we can achieve the separation of mechanism and policy, which leads to an implementation that requires less code and easier to understand.</p><h3>The Problem</h3><p>In one of our projects, we need to validate the JSON input provided by the UI front-end in the back-end Java code. We have two requirements:</p><ul><li>We want to validate the JSON format. If the UI front-end provides a malformed JSON string, we want to throw an exception.</li><li>After converting JSON to POJO, we want to validate the POJO. More specifically, we want to make sure:<br>1. A string field is within a certain length.<br>2. A Collection (e.g. List) has a certain size.<br>3. A Collection only contains unique elements.<br>4. A Collection has to contain certain elements.<br>If any of these constraints a violated, we need to throw exceptions that could help users to understand the problem. When a user provides a well-formed JSON string, but its content violates our constraints, we want to inform her which constraints are violated and why.</li></ul><p>For the first requirement (validate the JSON format), our team has been using <a href="https://github.com/FasterXML/jackson">Jackson</a> extensively, so Jackson is our go-to solution. It’s also able to detect if a required property is missing. Bean Validation (discussed later) also supports this.</p><p>For the second requirement, our initial implementation was to write our own code to validate the POJO converted from JSON using Jackson. The code looks like this:</p><pre>if (!(obj.getStringField().length &gt; 10 || obj.getStringField().length &lt; 20)) {<br>    throw new ConstriantViolationException(lengthViolationMessage);<br>}<br>if (obj.getCollectionField().size &lt; 5) {<br>    throw new ConstriantViolationException(collectionSizeViolationMessage);<br>}<br>// Other validations</pre><p>Of course, the actual code is more complicated than this as we also need to pass the value into the exception message. So we end up with writing lots of message templates.</p><p>We quickly sensed that, although this solution works, it mixes the mechanism and policy. <em>Policy</em> here means the constraints we impose on the POJO. For example, “the length of this string has to be between 10 and 20” is a policy. <em>Mechanism</em> here means using Java code to check the length and throw an exception. Mixing mechanism and policy together has two major issues:</p><ul><li>The solution does not generalize very well. If we need to validate another POJO with a different set of constraints, we need to write similar code again.</li><li>The policy is not apparent. We need to “decode” the policy by reading the validation code. Ideally, we want to declare those constraints in the POJO class.</li></ul><h3>Java Bean Validation 2.0</h3><p>If you ever find yourself trying to solve a very common problem, chances are other people already solved that problem for you. This also applied to this problem. We found that <a href="https://beanvalidation.org/2.0/">Bean Validation 2.0</a> provide <strong><em>almost</em></strong> everything we want and more.</p><p>Bean Validation 2.0 is the successor of Bean Validation 1.1. Compared to 1.1, 2.0 supports Java 8, meaning that it supports java.util.Optional new Date/Time types, and some new built-in constraints.</p><p>Since Bean Validation is a specification,<a href="https://mvnrepository.com/artifact/javax.validation/validation-api/2.0.1.Final">javax-validation</a> jar itself does not provide the concrete implementation. We use hiberate-validator and javax.el to provide the implementations (see pom.xml <a href="https://github.com/jeremysong/javaxvalidation/blob/master/pom.xml#L28-L36">here</a>).</p><p>Bean Validation is attractive because it allows us to use Java annotations to define constraints in the POJO class. The actual validation can happen elsewhere. This is the beauty of <a href="https://en.wikipedia.org/wiki/Separation_of_mechanism_and_policy">separation of mechanism and policy</a>:</p><ul><li>By defining the policy (validation constraints) in the POJO class, we essentially set up a contract between the object producer and the object consumer. The constraint definitions are succinct and apparent. A bonus feature of Bean Validation: when defining a constraint, Bean Validation allows us to define a message template, which could contain placeholders for us to replace it with the specific value during the validation.</li><li>The mechanism is manifest in two places. 1) Here we use hiberate-validator to provide the validation mechanism, but it’s possible to use other libraries to perform the validation. 2) The actual validation can be performed elsewhere if it even occurs. For example, it can happen on the producer side, or the client side. If the client trusts the data provided by the producer, it can choose not to validate the POJO at all.</li></ul><p>Go back to our requirements:</p><ol><li>For the constraint “a string field is within a certain length”, we can use @Size(min=10, max=20)annotation.</li><li>For the constraint “a Collection (e.g. List) has a certain size”, we can use @Size(min=10, max=20)annotation as well.</li><li>For the constraint “a Collection only contains unique elements”, we realize there is no such annotation in Bean Validation specification. But since we use hibernate-validator, we found UniqueElements annotation in this library. Turns out it also provides many other useful annotations such as URL, ISBN, etc. All additional constraints can be found <a href="https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/?v=6.0#validator-defineconstraints-hv-constraints">here</a>.</li><li>For the constraint “a Collection has to contain certain elements”, we didn’t find an existing annotation in either Bean Validation specification or hibernate-validator. I do see the challenge for Bean Validation provides a generic specification for this use case: Java annotation only supports certain return types as specified in the <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-9.html#jls-9.6.1">Java Language Specification</a>. Since we only care about the String and Integerelements, we decide to extend Bean Validation by creating custom constraints.</li></ol><h3>Define Our Own Constraints</h3><p>We define new constraints ContainsStrings and ContainsInts, and we want to use them like this:</p><pre>public class Customer {<br>    @ContainsInts(values = {1, 2, 3, 4}, message = &quot;The list misses required elements: {missingValues}&quot;)<br>    List&lt;Integer&gt; scores;</pre><pre>// Getter and setter<br>}</pre><p>We want the validation to fail when scoresdoes not contain value 1,2,3,4. And we want to tell the user what are those missing values. Example being if scores is [1,2], our message should be The list misses required elements: 3,4.</p><p>Both implementations can be found in my <a href="https://github.com/jeremysong/javaxvalidation">GitHub repository</a>. Let’s take a look at ContainsInts annotation in this post. The official tutorial on creating custom constraints can be found <a href="https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/?v=6.0#validator-customconstraints">here</a>.</p><h4>The Implementation</h4><p>We define the annotation like this:</p><pre>@Constraint(validatedBy = {ContainsIntValidator.class})<br>@Target({ <em>METHOD</em>, <em>FIELD</em>, <em>ANNOTATION_TYPE</em>, <em>CONSTRUCTOR</em>, <em>PARAMETER</em>, <em>TYPE_USE </em>})<br>@Retention(<em>RUNTIME</em>)<br>public @interface ContainsInts {</pre><pre>    String message() default &quot;{org.jeremy.ContainsInts.message}&quot;;</pre><pre>    Class&lt;?&gt;[] groups() default {};</pre><pre>    Class&lt;? extends Payload&gt;[] payload() default {};</pre><pre>    int[] values();<br>}</pre><p>Note that we specify ContainsIntValidator.class in validatedBy parameter. This allows the ContainsInts annotation to use ContainsIntValidator class to validate the collection. We implement ContainsIntValidator as:</p><pre>public class ContainsIntValidator implements ConstraintValidator&lt;ContainsInts, Collection&lt;Integer&gt;&gt; {</pre><pre>    private Set&lt;Integer&gt; values;</pre><pre>    @Override<br>    public void initialize(ContainsInts constraintAnnotation) {<br>        values = Arrays.<em>stream</em>(constraintAnnotation.values()).boxed().collect(Collectors.<em>toSet</em>());<br>    }</pre><pre>    @Override<br>    public boolean isValid(Collection&lt;Integer&gt; collection, ConstraintValidatorContext constraintValidatorContext) {<br>        Set&lt;Integer&gt; missingValue = values.stream().filter(v -&gt; !collection.contains(v)).collect(Collectors.<em>toSet</em>());</pre><pre>        if (missingValue.isEmpty()) {<br>            return true;<br>        }</pre><pre>        if (constraintValidatorContext instanceof HibernateConstraintValidatorContext) {<br>            constraintValidatorContext.unwrap(HibernateConstraintValidatorContext.class)<br>                    .addMessageParameter(&quot;missingValues&quot;, missingValue.stream().map(String::<em>valueOf</em>).collect(Collectors.<em>joining</em>(&quot;,&quot;)))<br>                    .withDynamicPayload(ImmutableSet.<em>copyOf</em>(missingValue));<br>        }</pre><pre>        return false;<br>    }<br>}</pre><p>Notice that this class implements ConstraintValidator&lt;ContainsInts, Collection&lt;integer&gt;&gt;. This means that this validation works on any Collection&lt;Integer&gt;, such as List&lt;Integer&gt;, Set&lt;Integer&gt;, ArrayList&lt;Integer&gt;, etc.</p><p>To be able to display the missingValues in the constraint violation message, we use addMessageParameter method to add a key-value pair that maps the missingValues placeholder to all the missing values the validator found.</p><p>To test our own constraint and its validator, we create a Customer object and set scores to [1,2]:</p><pre>public class App {<br>    public static void main(String[] args) {<br>        ValidatorFactory factory = Validation.<em>buildDefaultValidatorFactory</em>();<br>        Validator validator = factory.getValidator();</pre><pre>        Customer customer = new Customer();<br>        customer.setScores(Lists.<em>newArrayList</em>(1, 2));</pre><pre>        Set&lt;ConstraintViolation&lt;Customer&gt;&gt; violations = validator.validate(customer);<br>        violations.forEach(violation -&gt; System.<em>out</em>.println(violation.getMessage()));<br>    }<br>}</pre><p>The output:</p><pre>The list misses required elements: 3,4</pre><h3>Takeaways</h3><p>After replacing our own validator code with Bean Validation, we believe that our code is much simpler and easier to read. We are also able to pull our own constraint annotation into a separate library, which can be reused in many other packages.</p><p>I also observed that creating new Java annotations to separate mechanism and policy is an uncharted area for many teams. Usually, people think that creating custom Java annotations is a more advanced solution than writing Java code. Maybe it is true. But I also believe that creating and using custom Java annotations usually brings greater rewards.</p><p>When writing code, always keep “separation of mechanism and policy” in mind. More often than not, dividing an implementation into mechanism and policy helps me imagine the new use cases beyond the current use case at hand. This allows me to come up with solutions that are able to scale out from solving one problem to solving multiple similar problems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f55829fd728" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Return-Driven Decision-Making on Software Projects]]></title>
            <link>https://medium.com/hackernoon/return-driven-decision-making-in-software-projects-5586a4426eba?source=rss-80a8f602bf23------2</link>
            <guid isPermaLink="false">https://medium.com/p/5586a4426eba</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-projects]]></category>
            <category><![CDATA[decision-making]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[return-driven]]></category>
            <dc:creator><![CDATA[Jeremy Song]]></dc:creator>
            <pubDate>Mon, 05 Feb 2018 05:14:19 GMT</pubDate>
            <atom:updated>2018-02-10T10:43:35.436Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is Return-Driven Decision-Making?</h3><p>Doing a project is like making an investment. A company does a project by investing engineering resources, hardware resources, operational resources, etc., in hope of (eventually) making more money than they initially invested.</p><p>As a project owner, managing your projects is just like managing your stocks. Before buying a stock (initializing a project), you need to decide if the stock is worth buying (if the project is worth doing). You only buy that stock if you believe that stock will have a positive return in the future, and the return should be large enough to worth the effort. You may plan to hold the stock for a period of time (plan the project duration), but if you estimate that you will lose money if you keep holding it, you will immediately sell the stock (abandon project) even though it hasn’t reached your financial goal. If you estimate that stock will give you more return in the future, you might want to hold the stock longer than you planned or to increase the investment (add more features to that project). Every decision stock investment is about the financial return.</p><p>Software project decisions can be made in a similar way. Essentially, you want to maximize the return, which is the difference between the gain (how much you have made) and the cost (how much you have invested):</p><pre>return = gain — cost</pre><h4>Value metrics</h4><p>Unlike the stock market, where you can always measure your return in dollars, measuring return in a software project is more complicated, because the gain and the cost are measured in different value metrics. For example, a project whose gain is to reduce p99 latency by 50% does not have same value metric as its engineering cost (e.g. one SDE working one month to release this project).</p><p>Here are some typical value metrics:</p><ul><li>Dollar, such as sales this project generates, the hardware cost, etc.</li><li>Engineering cost, such as how many SDEs, how long they work on this project</li><li>Latency</li><li>Throughput</li><li>Scalability</li><li>Usability, such as saving one mouse click to login</li><li>Complexity</li><li>Customer trust</li></ul><p>The challenge is that to be able to compare different value metrics, you need to project non-dollar value metrics to dollar value metric. For instance, figure out much 1ms latency is worth in dollars in your service. Some conversions are easy: you always know the SDE’s salary and the hardware cost; Some conversions are very difficult: how much does 1-mouse-click worth in dollars? Many companies use A/B tests to measure this.</p><p>Even though you can’t exactly project all non-dollar value metrics to dollar value metric, you at least should have a reasonable value range.</p><h4>Maximize the return</h4><p>Because return is the difference between gain and cost, to maximize the return:</p><ul><li>When looking at a single project, you need to maximize the gain and minimize the cost.</li><li>When comparing the different projects, you need to compare the return. Neither gain nor cost alone can help you make right decisions.</li></ul><p>There are two common pitfalls when they make decisions in software projects:</p><ol><li>They only think about gain, don’t think about cost. They usually rush to a project without thinking about the engineering cost and opportunity cost. The right thing to do is to estimate both gain and cost, calculate the return. Among all candidate projects, only pick up a project that has the highest return.</li><li>They only think about the cost, and ignore the gain. This pitfall could manifest in this situation: preferring “a feature takes 2 days to implement can make the operational load a little better” to “a feature takes 20 days to implement can make the operational load a lot better”. When making this decision without estimating the dollar value of “a little better” and “a lot better”, a wrong decision can be made.</li></ol><h3>Return-Driven Approach in Software Project Life-Cycle</h3><h4>Regularly use return-driven decision-making approach</h4><p>In a project life-cycle, project return should be constantly re-evaluated, just like investors periodically evaluate the stock and estimate the return based on the new information.</p><p>While many projects conduct thorough initial scoping and planning, not many projects (especially smaller projects that span less than 6 months) actually do a regular re-estimating on return, while they regularly adjust the release dates. For those projects, my suggestion is that when adjusting the release dates, also re-estimate the project’s return.</p><h4>Project Initialization</h4><p>Applying return-driven approach in project initialization phase, you need to answer this question: among all other candidate projects, can this project bring the highest return when it’s delivered?</p><p>Project scoping tries to answer this question by gathering information to estimate the gain and the cost. Talking to customers to understand their use case is a typical way to estimate the gain. Estimate the engineering cost and hardware cost is a typical way to estimate the cost.</p><p>When making a decision on whether to pick up the project, be aware of the pitfalls mentioned earlier: either gain and cost along can help you make the right decision, only return can.</p><h4>Project Design/Implementation</h4><p>If I want to see if a team can make rational decisions, one metric I would look at is how many projects have been canceled/abandoned in the design and implementation phases because the team does not believe this project could bring positive return (assuming the team already estimated that this project could have positive return in project initialization phase).</p><p>I find that developers rarely re-estimate the return after a project has been officially kicked off, while the leadership does that, but less frequently. It’s very common that, in the agile development, developers re-estimate the points they need to spend on different tasks in design and implementation phases. Often, they also need to adjust the project’s release date in the implementation phase. Nevertheless, it’s uncommon that developers frequently re-estimate the project’s return based on the new information they have learned in the design and implementation phases.</p><p>One of the famous fallacies in economics is <a href="https://en.wikipedia.org/wiki/Sunk_cost">sunk cost</a> fallacy. While it happens to many inexperienced stock traders, I wonder if it happens more often to software projects, because developers can easily build personal bonds to projects when they invest a large amount of time and energy. I seriously doubt that a team working on a project for 3 years would have the guts to abandon this project if they found out that the future return will not be positive.</p><p>Even initially a project’s estimated return is positive, it could be negative later, when:</p><ul><li>During the implementation, the team finds out that the cost of running this feature is much higher than they expected, which will not bring a positive return.</li><li>Their project has been delayed many times, so their customers have used other solutions.</li><li>They find out that the problem they try to solve does not exist anymore because other dependency systems or user behavior have changed.</li><li>Completing this project next month will have less return than completing it 2 months later because a complex component can be delegated to a new service, which will be released next month.</li></ul><p>More situations can make the project’s return negative. Unfortunately, those situations are not or could not be anticipated in the project initialization phase. At this point, the team should evaluate the cost of abandoning this project and use return-driven approach to decide if it would be better to abandon this project.</p><h4>Feature Deprecation</h4><p>After a project is completed, the team needs to maintain features delivered by this project. Depends on the design, implementation, architecture, or upstream/downstream services, a feature’s gain and cost will change constantly. Thus, a feature will generate either positive or negative return as the time goes by.</p><p>A regular return analysis should also be done after a project is completed. A return could be negative in either of two situations:</p><ul><li>Operational cost is increasing. The team needs to spend lots of engineering resources to maintain features released by this project.</li><li>Gain is diminishing. It may be caused by users moving to a cheaper and/or more efficient solution.</li></ul><p>When the project’s return is negative and the analysis shows that it’s unlikely to be positive in the future, the team can:</p><ul><li>Propose a deprecation project to eliminate its cost (as well as its gain).</li><li>Propose new projects to increase the gain.</li></ul><p>It’s worth noting that deprecating a feature is not free. As any regular features, return-driven decision-making approach can also be applied to feature deprecation project. There are two types of cost in a feature deprecation project:</p><ul><li>Cost of off-boarding existing customers. This means that your gain will be less. It also means that during the feature deprecation, your return will diminish more rapidly until you completely release all the hardware resources used by this feature.</li><li>Engineering cost for developing this project.</li></ul><p>Sometimes the cost of deprecating the feature is so high that results a huge negative return. In this case, stopping on-boarding new customers and continuing supporting existing customers to confine the negative return is a better decision than deprecating this feature. This is especially true if you consider that hardware cost is always decreasing and the engineering cost is always increasing.</p><h3>Apply Return-Driven Decision-Making Approach to Multiple Projects</h3><p>Return-driven decision-making approach can also be applied to multiple related projects (e.g. projects for one service) together. It’s not uncommon that a single project could have a negative return, but it will generate positive return when being combined with other projects later. When being applied to multiple related projects, return-driven approach can:</p><ul><li>Mitigate the risk of an individual project.</li><li>Provide a holistic view of the return of the service as a whole.</li></ul><p>When you zoom out to estimate the return of multiple projects together, then zoom into a specific project, you will be able to estimate the return that this project brings to its related projects, in addition to the return generated by this project alone. It is a risk if you look at one project, but it could be a win for the service as a whole.</p><h3>Limitation of Return-Driven Approach</h3><p>Return-driven approach is not useful when the gain and/or the cost cannot be reasonably estimated. This could happen in situations such as proposing long-term visions for a team or exploring new business domain, or new market.</p><p>The gain in those situations cannot be reasonably estimated because:</p><ul><li>long-term visions do not always have concrete customer use cases; Long-term visions usually focus on what the team wants to do for their customers in the future, not necessarily on what customers want right now.</li><li>new business domain or new market do not always provide enough data for estimating the gain. A very small market may no longer exist in next 3 years, but also may become a huge one.</li></ul><p>The cost in those situations cannot be reasonably estimated because cost, in most cases, depends on how to implement those visions and how to explore new business domain and new market.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5586a4426eba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/return-driven-decision-making-in-software-projects-5586a4426eba">Return-Driven Decision-Making on Software Projects</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Don’t be a Software Engineer, be a Software Artist]]></title>
            <link>https://medium.com/hackernoon/dont-be-a-software-engineer-be-a-software-artist-204dbd47e8ca?source=rss-80a8f602bf23------2</link>
            <guid isPermaLink="false">https://medium.com/p/204dbd47e8ca</guid>
            <category><![CDATA[software-artist]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[artist]]></category>
            <category><![CDATA[software-engineer]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Jeremy Song]]></dc:creator>
            <pubDate>Tue, 24 Oct 2017 05:43:15 GMT</pubDate>
            <atom:updated>2017-11-03T17:25:43.581Z</atom:updated>
            <content:encoded><![CDATA[<p>Occasionally, new software engineers are confused by me saying their design or code are “not good enough”, and their question/response is usually one of the these:</p><ol><li>this code works, why should I keep changing it?</li><li>this design is feasible, why do you want it to be simpler?</li><li>let me explain this code to you, and you will undestand.</li></ol><p>“Not good enough” is a very vague term here. Usually I would use some less-vague-but-still-very-vague-terms such as “not simple enough”, “not easy to understand”, “not user friendly”, “not self-explainable”, etc. Usually I would have a chat with this engineer about why we need to design a simple architecture, why you should write simple, easy-to-understand code, why you should format your code, why you should put an extra space between these two symbols…</p><p>If you have been in software industry for couple of years, or care enough to read some books about how to write good code and how to design good architectures, you probably will feel the same way. Those are basic concepts that should be grasped by every new software engineer, but unfortunately not everyone understands the necessity of those concepts.</p><p>Not only do some new engineers don’t insist on highest standards on the quality of the design and code, some engineers who have been in the software industry for a while also have this problem. You can ask them to read <a href="https://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/0735619670">Code Complete 2</a>, <a href="https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882">Clean Code</a>, <a href="https://www.amazon.com/UNIX-Programming-Addison-Wesley-Professional-Computng/dp/0131429019">Art of Unix Programming</a>, and other 10 different programming books (you name them), some of them will improve their engineering quality, some still won’t.</p><h3>Software Engineer vs. Software Artist</h3><p>Why not every software engineer producing high quality code and high quality design? Maybe some of them are inexperienced; maybe some of them don’t know how to generalize what they have already learned from those books and past experience; maybe some of them just want to finish their work and to them, being a software engineer is just a job. But fundamentally, it’s because<strong> they think they are software engineers, not software artists.</strong></p><p>The requirements of being a software engineer are:</p><ul><li>knowing how to write code and test code;</li><li>knowing how to identify business problems, collect user requirements, design a project and release it;</li><li>and anything in software engineer’s job description.</li></ul><p>Usually, there is no requirement of writing easy-to-understand code, or desinging a project that is easy-to-use.</p><p>So what’s the requirements of being a software artist? To answer this question, we should look at what a design done by software artist look like; or more general, what a design done by an artist look like.</p><p>When I first looked at Charles and Ray Eames’ plastic side chair years ago, I was amazed by its simplicity and its unreasonably comfort brought by this simple design. This chair was designed 1950 and has been very famous since then. As a software developer, I naturally thought was: how can we build a software like this chair?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KQI5FlOIVNAQfIiPn6RI1g.jpeg" /><figcaption>Eames Modeld Plastic Side Chair Wire Base (Picture Taken from <a href="http://www.hermanmiller.com/">Herman Miller Website</a>)</figcaption></figure><p>I have been using this chair daily for more than three years, here are what I like about this chair:</p><ul><li>It’s very pleasant to look at it.</li><li>Everyone can immediately recognize this is a chair and its functionality. This is probably a silly example, but think about something you see but you have no idea what it is or what it does.</li><li>The seat and back are molded into one plastic piece; the base adds its own complexity because it’s less boring to look at than the traditional chair.</li><li>Because of this plastic piece, when you sit on it, it will slightly adjust the support based on your sitting position. I personally think this is very ingenious. Many chairs use complex structure to provide good support, but this chair leverages the material to do the same thing without adding extra components.</li><li>It fits everywhere: bedroom, office, living room, dining room, etc.</li><li>It’s environmental friendly. It’s made of 100 percent recyclable polypropylene. Historically, this chair was also be made of fiber glass but the production was paused until an environmental friendly way of producing fiber glass was discovered.</li></ul><p>So what’s the project/product would look like if we ought to build a “Eames Plastic Chair” in software industry?</p><ul><li>The code, the design, the architecture should be very pleasant to look at.</li><li>Whoever read the code snippet, method, class, design doc, architecture doc, they should be able to immediately recognize the purpose of this entity and know how to use it.</li><li>The code/component/design/architecture should be as simple as possible. But not simpler than necessary.</li><li>The project leverages existing products, libraries, code, etc. to simplify the design.</li><li>The design should be flexible so it can cope with future policy changes. This is a <a href="https://en.wikipedia.org/wiki/Separation_of_mechanism_and_policy">separation between mechanism and policy</a>.</li><li>The project should be environmentally friendly. It should not cost more hardware resources than necessary; it should not cost more peopleware resources than necessary either.</li></ul><p>Whoever can design such project/product should be recognized as software artist rather than software engineer. They really insist on the highest standards for designing, architecting, and implementing a project.</p><h4>How to Quantify</h4><p>Readers may argue that it’s extremely difficult to quantify those requirements. For example, how to define “as simple as possible”? Some people attempt to classify a “long method” by checking if this method can be fit into a computer screen. Some people suggests to count how many states an object can be in the life cycle of the system.</p><p>I think the real value of being a software artist is that <strong>you don’t quantify, you constantly improve</strong>. When you design a project, constantly ask yourself: can this project be designed better? When you write a code, after testing all the functionality, sit back, look at it, and ask yourself: is this code structured beautifully as a finest artwork you have ever seen?</p><p>Software engineers will stop improving their projects once they checked all the checkboxes, software artists do not have those checkboxes because their work are already above the standards. As a software artist, once you settle down on measuring your project against some baselines, your project is no longer an artwork because you would not challenge yourself any more.</p><p>Of course, you will release the current project, but you will always go back and improve it because you’re a software artist.</p><h3>More Than a Software Builder</h3><p>Software artists can surely build software with highest standards. But being a software artist is more than just being an excellent software engineer who can write good code and design good architectures. Being an artist in software industry requires you to:</p><ol><li>understand your customers</li><li>be a teacher and an influencer</li></ol><h4>Understanding Your Customers</h4><p>When I just came to software industry, I only thought about how to write good code to solve customers’ problems in a given business domain. As I started to talk to our customers, I realized that customers know what they don’t like or sometimes, what they want. But they rarely know the specific requirements.</p><p>I always believe that “what customers want are not what they actually want”. Most customers are really good at proposing solutions based on what they see and know by looking at your competitors. But if you accept their proposers, you will realize that your customers are transforming you to your competitors.</p><p>Working with your customers to understand what they actually want to is much more difficult than optimizing a slow algorithm to make it run faster. If they want to sell their artworks, artists need to understand their customers. This is a really difficult because their customers want beautiful paintings that can be hang in the living room, for example. Painter need to figure out the specific requirements for this painting.</p><p>Our customers sometimes complain that the search results in our website only contain the top 200 entities. New software engineers usually will go ahead to increase number of the search results displayed by changing the configuration, and if the search is slow, adding more machines, etc. A software artist tries to understand the customers’ problems and figure out what they actually want. The questions for our customers could be:</p><ul><li>why do you need more results? (200 entities is really a lot in our problem domain.)</li><li>how do you use those results if we could give you 2000 entities?</li><li>how about we categorize all the entities and each category could have 200 entities?</li></ul><h4>Long-term Influence</h4><p>Artists usually influence other people by what they do and/or what they produce. Furnitures designed by Charles and Ray Eames influenced the whole furniture design industry after WWII. <a href="https://en.wikipedia.org/wiki/Claude_Debussy">Claude Debussy</a>’s impressionism music made people rethink how to use music to convey the moods and emotions in a more abstract way.</p><p>When architecting a design, think about if this design can stand the test of time or this project is just a <em>fashion</em>. A design can stand the test of time when:</p><ul><li>other people, other teams in the similar business domain can reuse your design.</li><li>your design can cope with some policy changes. (<a href="http://www.catb.org/esr/writings/taoup/html/ch01s06.html#id2877777">Rule of Separation</a>)</li></ul><p>Being a software artist is also about being a teacher. You need to teach other software engineers to be software artists. There are some typical ways to influence other people:</p><ul><li>Document everything you did. If you did something great, other people should be able to use your document to repeat the success.</li><li>Mentor other engineers.</li><li>Occasionally, give a talk in your team, organization, or even in your company.</li><li>Publish your work.</li></ul><h3>Acknowledgment</h3><ul><li><a href="https://medium.com/u/6b1efd342366">Kazuki Yokoyama</a> who inspired me to write <strong>More Than a Software Builder</strong> section.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=204dbd47e8ca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/dont-be-a-software-engineer-be-a-software-artist-204dbd47e8ca">Don’t be a Software Engineer, be a Software Artist</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tuning My IntelliJ IDE]]></title>
            <link>https://medium.com/stochastic-stories/tuning-my-intellij-ide-8255781f6a0d?source=rss-80a8f602bf23------2</link>
            <guid isPermaLink="false">https://medium.com/p/8255781f6a0d</guid>
            <category><![CDATA[garbage-collection]]></category>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[intellij]]></category>
            <dc:creator><![CDATA[Jeremy Song]]></dc:creator>
            <pubDate>Wed, 16 Aug 2017 02:26:59 GMT</pubDate>
            <atom:updated>2017-08-16T02:30:33.587Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>I have been using IntelliJ IDE for Java development (occasionally Javascript development) for more than 3 years now. It’s probably the biggest application (in terms of the amount of resources it consumes) running on my working laptop. Even though at most time it’s running very smoothly, I wonder if I could make it run even faster by tuning the JVM options.</p><h3>Default IntelliJ JVM Options</h3><p>The following configuration is the default JVM configuration for IntelliJ 2017.2.</p><pre>-Xms128m<br>-Xmx750m<br>-XX:ReservedCodeCacheSize=240m<br>-XX:+UseCompressedOops<br>-Dfile.encoding=UTF-8<br>-XX:+UseConcMarkSweepGC<br>-XX:SoftRefLRUPolicyMSPerMB=50<br>-ea<br>-Dsun.io.useCanonCaches=false<br>-Djava.net.preferIPv4Stack=true<br>-XX:+HeapDumpOnOutOfMemoryError<br>-XX:-OmitStackTraceInFastThrow<br>-Xverify:none<br><br>-XX:ErrorFile=$USER_HOME/java_error_in_idea_%p.log<br>-XX:HeapDumpPath=$USER_HOME/java_error_in_idea.hprof<br>-Xbootclasspath/a:../lib/boot.jar</pre><h4>The Good</h4><ul><li>It does not specify the specific compiler for the Java application. What’s good about this is that Java 8 uses tiered compilation. Tiered compilation was introduced in Java 7 with the idea that your Java bytecode is first compiled with <em>client</em> compiler and later on switched to <em>server</em>compiler. Tiered compilation now is turned on by default in Java 8. For a GUI application like Intellij, this could make sure that your application runs with compiled code most of time.</li><li>It automatically does a heap dump when OOM occurs.</li></ul><h4>The Bad</h4><ul><li>Initial heap size is too low. 128M is too small for a writing a complex web application. If the JVM uses more than 128M heap size anyway, we should bump this value.</li><li>Maximum heap size is too low. 750M is also too small for large Java applications. My laptop has 16GB memory and I would give Intellij more memory.</li></ul><h3>Custom JVM Options</h3><p>Here is my custom JVM configuration. You can learn how to change JVM options for IntelliJ <a href="https://intellij-support.jetbrains.com/hc/en-us/articles/206544869-Configuring-JVM-options-and-platform-properties">here</a>.</p><pre># custom IntelliJ IDEA VM options<br><br>-Xms1G<br>-XX:ReservedCodeCacheSize=480m<br>-XX:+UseCompressedOops<br>-Dfile.encoding=UTF-8<br>-XX:+UseG1GC<br>-XX:MaxGCPauseMillis=100<br>-XX:+PerfDisableSharedMem<br>-XX:SoftRefLRUPolicyMSPerMB=50<br>-ea<br>-Dsun.io.useCanonCaches=false<br>-Djava.net.preferIPv4Stack=true<br>-XX:+HeapDumpOnOutOfMemoryError<br>-XX:-OmitStackTraceInFastThrow<br>-Xverify:none<br><br>-XX:ErrorFile=$USER_HOME/java_error_in_idea_%p.log<br>-XX:HeapDumpPath=$USER_HOME/java_error_in_idea.hprof<br>-Xbootclasspath/a:../lib/boot.jar</pre><h4>Changes</h4><ol><li>I changed initial heap size (<strong>-Xms</strong>) to 1G. I used jconsole to connect to my IntelliJ JVM process and observed that it frequently uses about 900MB memory. So I bumped this value to 1GB.</li><li>I removed maximum heap size (<strong>-Xmx</strong>). By default, JVM calculates this value ergonomically by setting it to 1/4 of your physical memory. Since my laptop runs with 16GB memory, 4GB is a decent number.</li><li>I switched the GC algorithm from <em>CMS</em> to <em>G1</em>. Both algorithms are concurrent GCs. But CMS uses <em>mark-and-sweep</em>, which suffers from memory fragmentation issue. It will perform a full GC to compact the memory. But during the full GC, it will stop the application, which will definitely affect the GUI user experience. G1GC is less likely to do a full GC.</li><li>I set <strong>MaxGCPauseMillis</strong> to 100ms. It will basically set a goal for the GC so JVM can decide how much heap size to use.</li><li>I bumped the code cache size to 480MB. This decides how much compiled code the JVM can have. Once the code cache is full, JVM will stop compiling bytecode. If the size is too small, it will definitely hurt the Java application performance. But I didn’t gather data to prove that my IntelliJ application need more than 240M code cache. So I am exercising a black magic here.</li><li>I turned on <strong>PerfDisableSharedMem</strong>.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8255781f6a0d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stochastic-stories/tuning-my-intellij-ide-8255781f6a0d">Tuning My IntelliJ IDE</a> was originally published in <a href="https://medium.com/stochastic-stories">Stochastic Stories</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Worse is Better” on AWS]]></title>
            <link>https://medium.com/stochastic-stories/worse-is-better-on-aws-7fa1eaa02ddd?source=rss-80a8f602bf23------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fa1eaa02ddd</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Jeremy Song]]></dc:creator>
            <pubDate>Sun, 16 Jul 2017 06:31:35 GMT</pubDate>
            <atom:updated>2017-07-16T06:56:31.983Z</atom:updated>
            <content:encoded><![CDATA[<p>If you haven’t read <a href="https://www.jwz.org/doc/worse-is-better.html">Worse is Better</a>, you should read it now.</p><p>You can find all the details in article above. Just to summarize it even more, there are two design styles:</p><ul><li>A simpler interface. Hide the complexity on the server side, but easier for users to understand.</li><li>A simpler implementation. It’s easier for the project developers to maintain and understand, but users might have to know more about the assumptions that the service makes and write more code to handle the complexity that service exposes in the interface.</li></ul><p>There is a whole spectrum of trading between simpler interface and simpler implementation. The leftmost side of this spectrum indicates a system with simplest interface and has all complexity baked into it. The rightmost side of this spectrum indicates a system with simplest implementation and has all complexity exposed in the interface. Most of the systems are somewhere in-between; they have some complexity baked in their system, but meanwhile shift other complexity to the interface. Most of the core AWS services are in this category (more on that later).</p><p>Here are some examples for both design styles.</p><h4>Example: Simpler Interface</h4><p>Services that are open to everyone on the earth fall into this category. Just to name a few:</p><ul><li>Dropbox: as an UI user, you simply upload your files to your Dropbox account. When it says it’s done, it’s done. You don’t need to worry about retry strategy, consistency, latency, etc. If the upload failed, you might want to try it again. However, if you have a Dropbox client, things get even more simpler. You simply put your files in your local folder that is synced with Dropbox and you’re done.</li><li>Amazon one-click purchase: it’s so simple that all you need to do is to click “1-click purchase” button.</li><li>A bowl of ramen: you just have to sit down and eat it. You shouldn’t have to worry about how the chef made this delicious ramen.</li></ul><h4>Example: Simpler Implementation</h4><p>A necessary but not sufficient condition for this kind of services is that the targeted users are not everyone but a specific population.</p><ul><li>S3: from an API user’s perspective, you need to be aware that S3 is an eventually consistent system for upload and deletion operations. You might have to write extra code in your system to deal with this assumption.</li><li>Most of the UNIX tool: you use ls to list a directory, cd to change a directory, grep to filter content, etc. In fact, one of the UNIX design philosophy is do one thing and do it well. However, in lots of cases, you need to use pipe to glue those tools together.</li><li>An IKEA furniture: you need to do assemble an IKEA furniture.</li></ul><h3>More About AWS</h3><p>AWS’s main users are developers. So they are lucky to have an option to build systems with simpler implementation.</p><p>I talked about S3. Let’s talk about another two popular AWS services:</p><ul><li>DynamoDB: DynamoDB is entirely an eventually consistent system before they released Strongly Consistent Reads feature. You put your DynamoDB item in the table, you might not see that item when you query it <em>immediately</em>.</li><li>SQS: before releasing SQS FIFO queue, SQS is entirely an eventually consistent system. This is actually very counter-intuitive for users who don&#39;t know much about distributed system: it says that it is a queue but cannot guarantee the delivery ordering and can only deliver messages in at least once fashion.</li></ul><p>There are couple of compelling reasons for AWS to build systems like this:</p><ul><li>Not all users need strong consistency.</li><li>It’s easier to implement, Building distributed system with strong consistency is difficult (think about PAXOS and Raft) and usually those systems have higher latency and lower throughput.</li><li>If a system is easier to implement, it’s usually easier to test, faster to release. For AWS, releasing new services and new features is very important for acquisition.</li></ul><h3>Personal Preference</h3><p>As a software engineer, I like <em>Simpler Implementation</em> when building a software system but hate it in other areas. For example, I don’t like barbecue because it requires me to manually put the meat on the fire and you have to PAY to do that! I also don’t like IKEA because I am lazy.</p><p>Here are the reasons why I like <em>Simpler Implementation</em> when building a software system:</p><ul><li>To build a simple implementation is actually harder than it sounds. What I observed that junior software engineers usually tend to write complex code and design complex solutions. Senior software engineers tend to come up with simpler implementations. Also, you really need to talk to customers and make sure you actually are able to shift some complexity from your implementation to your interface. Design a truly simple system requires years of experience.</li><li>As I mentioned above, simpler implementation is faster to build. Constantly releasing new features makes everyone happy.</li><li>Operation. Simpler implementation is easy to understand, so it’s easier to maintain and people can quickly know how to resolve the operational issues.</li></ul><h3>Disadvantages of Simpler Implementation and How to Fix it</h3><p>Someone said that if you released a product without any embarrassment, you probably have waited too long. Agreed. Releasing a service with <em>Simpler Implementation</em> design style is to make sure that you can release it faster than the one with <em>Simpler Interface</em> approach, but with some embarrassment. The real question is: after you release your product with those embarrassment, what can you do to improve it?</p><p>SQS recently released a new feature called FIFO queue. This is because they realized that people usually don&#39;t read documentation and even they do, traditional SQS queue&#39;s design assumptions put too much burdens on users. To use SQS queue, you need to think really hard about your architecture and make sure that the operations incurred after receiving a SQS message have to be idempotent. But sometimes your operations cannot simply be idempotent. One solution could be to put a buffer after the SQS queue so this buffer can remember what message it has received so far. Some people simply believe that those assumptions are unacceptable and use <a href="https://kafka.apache.org/">Kafka</a> instead. Releasing FIFO queue feature makes perfect sense for SQS to fill this gap.</p><p>To deal with systems that have not-so-simple interface, lots of users use facade patterns by writing code to hide the complexity. For example, SQS’s FIFO queue requires that every message has an unique ID. In most of cases, an unique ID can be obtained by performing SHA256 on the SQS message itself. Rather than asking every AWS SQS users to write the same code, AWS already added that code in the AWS Client package. A less interesting but more common problem is that everyone wants to retry their requests, so AWS Client natively supports exponential backoff in all the requests to AWS services unless configured otherwise.</p><p>UI is actually very important even for software engineers! I don’t completely agree with people who think that terminal is so powerful and they don’t need an UI. Who wants to write lots of code if they can do the same in the browser? Who wants to read the API documentation every time they want to onboard a new service if they can do the same thing with an UI?</p><h3>Conclusion</h3><p>When designing a new feature or a new system, I like trying Simpler Implementation design style first. It&#39;s possible that your users may not like the idea of taking on the burdens of handling complexity in your service interface. But even this is the case, you can still use Simpler Implementation with some stitches later:</p><ol><li>Because you want to release fast, you can always make your system extensible and add new features later (assuming your first release can meet the requirements of most of users).</li><li>Give your users a nice client packages. Complexity in the interface is still there. But you can handle it for your users on their behalf.</li><li>Build an UI to completely hide the service interface complexity.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fa1eaa02ddd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stochastic-stories/worse-is-better-on-aws-7fa1eaa02ddd">“Worse is Better” on AWS</a> was originally published in <a href="https://medium.com/stochastic-stories">Stochastic Stories</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>