<?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 Liu Tao on Medium]]></title>
        <description><![CDATA[Stories by Liu Tao on Medium]]></description>
        <link>https://medium.com/@liutao?source=rss-5170a1b413b5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*4kJBhWVD9APnVjbUlcAI4Q.jpeg</url>
            <title>Stories by Liu Tao on Medium</title>
            <link>https://medium.com/@liutao?source=rss-5170a1b413b5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 06:32:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@liutao/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[null pointer handling in modern Java]]></title>
            <link>https://medium.com/@liutao/null-pointer-handling-in-modern-java-18c05fd3941f?source=rss-5170a1b413b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/18c05fd3941f</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Liu Tao]]></dc:creator>
            <pubDate>Mon, 02 Sep 2019 03:42:18 GMT</pubDate>
            <atom:updated>2019-09-02T03:42:18.055Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1uSGyCTJMUP06HxIKteWxQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@philberndt?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Philipp Berndt</a> on <a href="https://unsplash.com/search/photos/empty?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In traditional programming languages like Java or C++, null is a member of all reference type. It’s used to model that one value is either unknown or non-existent. <a href="https://en.wikipedia.org/wiki/Tony_Hoare">Tony Hoare</a> invented it in 1965 and now described it as a billing dollars mistake.</p><blockquote>This led me to suggest that the null value is a member of every type, and a null check is required on every use of that reference variable, and it may be perhaps a billion dollar mistake.</blockquote><p>For example, you defined a Person class and created a group of person objects. All of them have the same attribute and behavior. But secretly, the language injects null into this group. As showing in below diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*-e1WeT44XSdiv-G_bzlvMg.png" /><figcaption>Person Class</figcaption></figure><p>To use any person object, you have to check whether that reference is null. This null-check adds a lot of unnecessary complexity in our code.</p><h4>non-nullable references by default</h4><p>Unnecessary null-check is a design error on the language side. That’s why in new languages like Kotlin, object reference is non-nullable by default.</p><pre>var a: String = “hello”</pre><pre>a = null; //won’t compile because a is non-nullable by default</pre><p>User needs explicit declare the variable as <strong>nullable</strong>:</p><pre>var a: String? = “hello”</pre><pre>a = null; //compile ok</pre><h4>Option type for old language</h4><p>For old languages like Java, it needs to maintain backward compatibility for the legacy code. So non-nullable reference by default is not a valid approach. Java 8 added Option type to make the possibly null value more explicit. That’s the most the language can provide to us. We still need static analysis tool and engineering discipline to prevent null pointer exception.</p><h4>Best Practice about null pointer handling in Java</h4><ul><li>Use Option for output</li></ul><p>The evil of null comes from its ambiguity. By returning Option from API, we explicitly tell the other party that the value could be missing. They have no chance to miss the necessary check on their side.</p><ul><li>Use <a href="https://projectlombok.org/features/NonNull">@NonNull</a> to protect input</li></ul><p>Lombok provides this annotation to generate null check automatically. Also, it can serve as documentation for the interface.</p><pre><strong>public class </strong>NonNullExample<strong> </strong>{</pre><pre><strong>private </strong>String name;<br> <br> <strong>public </strong>NonNullExample(@NonNull Person person) {<br>   <strong>this</strong>.name = person.getName();<br> }<br>}</pre><ul><li>Use constant literal for comparison:</li></ul><pre>input.equals(&quot;Hello&quot;); // null pointer exception when input is null<br>&quot;Hello&quot;.equals(input); // it&#39;s safe even input is null</pre><ul><li>Use null object pattern</li></ul><p>Martin Fowler says <a href="https://martinfowler.com/eaaCatalog/specialCase.html"><em>Instead of returning null, or some odd value, return a Special Case that has the same interface as what the caller expects</em></a><em>. </em>This simplifies the logic on the caller-side. But we still need to tell the caller that no null value will be returned and they don’t need to do null-check. This can only be done during the contract negotiation with the caller.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18c05fd3941f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Primer on event-driven design]]></title>
            <link>https://medium.com/@liutao/a-primer-on-event-driven-design-1760ca98d2ef?source=rss-5170a1b413b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1760ca98d2ef</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[event-driven-systems]]></category>
            <dc:creator><![CDATA[Liu Tao]]></dc:creator>
            <pubDate>Tue, 30 Jul 2019 22:08:01 GMT</pubDate>
            <atom:updated>2019-07-30T22:08:01.360Z</atom:updated>
            <content:encoded><![CDATA[<h4>And how to use events to build agile and predictive enterprise</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S5svIoN1k5x1fjz0iqGo6g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@kylejglenn?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Kyle Glenn</a> on <a href="https://unsplash.com/search/photos/anfield%2C-liverpool%2C-united-kingdom?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>It’s all about business</h4><p>As pointed out in this post <a href="https://medium.com/zero-equals-false/from-programmer-to-business-enabler-fc5c1bd36c39">From Programmer To Business Enabler</a>:</p><blockquote>The software itself is not an industry, but it’s <a href="https://a16z.com/2011/08/20/why-software-is-eating-the-world/?source=post_page---------------------------">eating the other industry</a>.</blockquote><p>IT system now is the nervous system of the whole enterprise. It enables almost every step of the business process, enable the enterprise to respond to the environment in a timely fashion. There are three areas that one better IT system can contribute to improving business performance:</p><ul><li>Timeliness: How quick can enterprise respond to an event</li><li>Agility: How quick can enterprise update its business process to respond to an event</li><li>Awareness: How quick can enterprise put the right information at the right level.</li></ul><h4>Use event technology to improve business performance</h4><p>First, using event technology is not only about speed up an existing business process. it’s more about a fundamental change in the architecture of the business process.</p><p>Long before the computer was invented, enterprise use events for internal and external business operations. But before we can only use our brain to do the complex event processing. In general, human is the worst information carrier and is very error-prone. Computers do a much better job once we have the event pattern and processing strategy defined. Human should only be left for edge-cases.</p><p>Technology makes it possible for enterprises to respond to all those three areas with events processing. More and more events are captured and transformed into digital form. So can be sent over the network and processed by computer.</p><h4>Why use events for business process</h4><p>In my previous post, <a href="https://medium.com/@liutao/a-primer-on-microservices-and-event-driven-design-f7ffd230a809">A Primer on Microservices</a>, I quoted that we should model the business process through asynchronous events. Here I will explain why we are able to use events for the business process.</p><p>It starts with basic interaction types between any two components. There are three types of interactions:</p><ul><li>Time-driven: the interaction happens at a specific time, with pre-defined participants.</li><li>Request-driven: the interaction is triggered by the client, only the client and server are involved.</li><li>Event-driven: the interaction is triggered by the event producer. <strong>The involved participants are dynamically defined.</strong></li></ul><p>All enterprise has those three types of interactions. We should build the IT system to support all of them. The question is, which type of interaction should be our preferred approach to model business process?</p><p>When the computation and storage system are expensive, we build IT system in time-driven batch mode. As information cost goes down, we build IT system in request-driven mode, using a central server. All data and logic stay in the server and can be accessed by the clients.</p><p>When information cost goes further down, we want to build our IT system with event-driven mode. Each consumer is self-contained and can process the event for a single purpose. The biggest advantage of event-driven mode is that the consumers are dynamically defined. We can easily add or remove consumer or producer or event types as the system evolves. This is a more organic approach to evolve the enterprise’s business capability.</p><h4>The way to migrate to event-driven enterprise</h4><p>The first step is to have the infrastructure ready. Apache kakfa is a common choice for enterprise-wide event processing platform. Once we have the infrastructure ready, we would want to put more events in the event system.</p><p>Event-driven is not something standalone. It could even be layered on top of the existing IT system. Normally the enterprise has a lot of legacy applications with different business capabilities but without events in mind. We can start to expose those business capabilities through event publishing. There could be multiple approaches to expose those events:</p><ul><li>Using DBMS trigger: most application store the data in the database. Any update in the database is inherently an event and can be emitted from a database trigger or log.</li><li>Add event publishing natively: if we have access to the application’s source code, we can import the event publishing library and emit the event when the business logic is done. We can also add a filtering layer to emit events for the selected request/response. For example for Java spring application, we can implement a spring filter to emit the needed events.</li><li>Using request/response monitoring: for the application that we don’t have access to source code, we need to be creative to extract the business event we want. One approach is to monitor the network traffic and generate events from the detected request/response. Or we can scrape the application to generate events for the update we detected.</li></ul><p>The enterprise should have the infrastructure ready to make it’s very easy to publish events to the event bus. When developing any new applications, we should just publish whatever we did meaningful to the event bus, event there is no use case for now.</p><p>The business analyst needs to re-engineer the business process before IT design effort. Whenever we can use event-driven design, we should use it because it’s minimum coupled.</p><h4>Conclusion</h4><p>With the cost of information goes down and the cost for human/time goes up, event-driven become a more favorable architecture for the enterprise IT system. Moden enterprise has much less time to respond to internal and external events than their predecessor has.</p><p>Beside timeliness and agility, the predictive enterprise is also one major motivation for event-processing. With more and more business capability and information exposed as events on the event bus, the enterprise is well-positioned to stay aware of all threats and opportunities going forward.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1760ca98d2ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Primer on Microservices and Event-driven design]]></title>
            <link>https://medium.com/swlh/a-primer-on-microservices-and-event-driven-design-f7ffd230a809?source=rss-5170a1b413b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7ffd230a809</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[event-driven-systems]]></category>
            <dc:creator><![CDATA[Liu Tao]]></dc:creator>
            <pubDate>Thu, 18 Jul 2019 19:15:06 GMT</pubDate>
            <atom:updated>2019-07-30T17:22:51.983Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Primer on Microservices</h3><h4>and how they bring agility to your enterprise</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BF0jzIJwTL6rStT4uShuLg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@ericmuhr?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Eric Muhr</a> on <a href="https://unsplash.com/search/photos/monolith?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>The problem with monolith application</h4><p>You have been working on a monolith application for a long time. As time goes, a lot of feature request made the initially perfect design not that perfect anymore. No matter how much effort you put to keep the module separated and layered, there will always be more and more coupling, and it will become more and more expensive to envolve. You hope you will get a chance to start over.</p><p>The problem with monolith application is not the code quality. It’s the wrong engineering approach. As long as it’s a monolith, the complexity will grow over time and become unmanageable at the end.</p><h4>Microservice give you the chances to start over</h4><p>In monolith application, the static and tight coupling is the root cause of most complexity. We need those coupling to make the system works as a whole. But then we want the coupling to be dynamic and loose so that we can evolve each component separately, or alternatively, we can start over many many times.</p><p>One general principle about any engineering approach is that we should make the right thing easy and wrong thing difficult. With containerized microservices, each component can be developed and deployed independently. It won’t be easy to create a tight coupling between services.</p><h4>Why event-driven microservices?</h4><p>Now we know we need microservices, what’s the coupling should look like between them? It could be synchronous HTTP request/response, or just asynchronous events. Both approaches have valid use cases. But most of the time, we should model the business process through asynchronous events.</p><p>The truth is that we live our lives operating on out-of-date information. There is no such thing as synchronous. Event-driven is inherently asynchronous. From this point of view, events are much more powerful modeling tool than synchronous calls. We can simulate synchronousness with blocking event.</p><p>So we can define our business process event streams. The coupling between components is done through pub/sub pattern. It removes the rigidity created by central control, injects real-time context into the business process. This kind of dynamic coupling is what we want to take advantage of through microservices.</p><h4>Composability is the motivation</h4><p>Most monolith application is designed with only anticipated use cases in mind. They assume they would be the only system need that information and thus don’t expose key events for easy data access. In many cases, we have to resort to database trigger to expose those events.</p><p>With event-driven microservices, each service just publishes whatever they did meaningful to the event bus. As more and more of an enterprise’s applications connect to the event bus, make their functionality available through events, the event bus becomes a centralized point of one-stop-shopping for functionality in the enterprise. A lot of new use cases can be implemented by the composition of existing events.</p><p>The chance to re-purpose and compose existing events is the real power of event-driven microservice. It’s the motivation that we want to publish more events to the event bus.</p><h4>Real-time event processing bring agility</h4><p>The value of any events system is not only about how many events it can process. It’s also about how faster each event gets processed. For a lot of activity, the shorter the feedback loop, the better it can iterate and evolve. With event-driven microservices, the response time for any events could be much shorter. In turn, this could be an increasingly important competitive advantage for high-performing teams.</p><h4>Conclusion</h4><p>The ultimate goal of the event-driven microservices is not about a better IT system, although it definitely helps. It’s about improving business performance.</p><p>Events are the key enabler for agile organizations. Microservice is the most ideal thing for now to implement such an event-driven system. We are still in the process to transform the business process into event-driven one. A lot of new use cases could be implemented as more and more events are exposed and available for the whole organization. But before we get those benefits, we must understand the initial investment for the event-driven system could be much higher. The dedication from top management is needed for any successful migration to the event-driven system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7ffd230a809" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/a-primer-on-microservices-and-event-driven-design-f7ffd230a809">A Primer on Microservices and Event-driven design</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Error Handling Done Right]]></title>
            <link>https://medium.com/swlh/the-error-handling-done-right-d19ffca2656f?source=rss-5170a1b413b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/d19ffca2656f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Liu Tao]]></dc:creator>
            <pubDate>Mon, 15 Jul 2019 03:50:36 GMT</pubDate>
            <atom:updated>2019-07-15T07:41:18.211Z</atom:updated>
            <content:encoded><![CDATA[<h4>And it will save more time in the future</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MOwJSimmKiRBY4yAVPzVQA.jpeg" /></figure><p>I skim through this topic in <a href="https://medium.com/swlh/write-simple-and-no-surprise-code-24fcf6f0156a">this post</a>: separate business logic from error handling. But this topic seems well worth dig much deeper. I have seen in many codebases, error handling is just afterthought of the design phase and most likely are just randomly plugged in. This post will give some thought food about why and how of error handling in our daily practice.</p><h4>It’s all about signal/noise ratio in your code</h4><p>As programmers, we use code to solve problems for our business. If we think harder, write less code, our business will bear less maintenance cost in the long run. In most cases, error handling code won’t provide business values. On the other side, the error-handling code is more complicated than happy path code and is difficult to get it right. It must be safe, and the nested error could be worse.</p><h4>Use different channel for business logic and error handling</h4><p>As mentioned in the <a href="https://medium.com/swlh/write-simple-and-no-surprise-code-24fcf6f0156a">previous post</a>:</p><blockquote>In the ideal world, all your code should be only about happy path. Frameworks, libraries and annotation can handle all the errors for you.</blockquote><p>But we are not there yet, no matter how hard we try, we still need to write some error handling code. Error should be the first-class citizen in our codebase and should have its own channel. Traditionally we will have the error check and business logic in the same block:</p><pre>if (dto != null) {<br> result1 = processA(dto);<br>}<br> <br>if (result1 != null) {<br> result2 = processB(result1);<br>}<br> <br>if (result2 != null) {<br> result3 = processC(result2); <br>}<br> <br>return result3 != null;</pre><p>The more preferred approach is to have separate channels for business logic and error handling logic. Java’s unchecked exception can serve as such an error handling channel. In the following code snippet, each function throws the same exception MyBusinessException:</p><pre>try {<br> result1 = processA(dto);<br> result2 = processB(result1);<br> result3 = processC(result2); <br>} catch(ApplicationExeption e) {<br> //handling exception here<br>}</pre><p>We can see that the business logic and error handling logic are separated. But with the exception, we have to construct the error handling channel using clunky exception syntax.</p><p>Java 8’s Optional provide the built-in channel for such error handling.</p><pre>Optional.ofNullable(dto)<br>        .map(this::processA)<br>        .map(this::processB)<br>        .map(this::processC)<br>        .map(r -&gt; r != null)<br>        .orElse(false)</pre><p>From the above three examples, the traditional way of null pointer check definitely has the lowest signal/noise ratio. Optional and Exception has similar signal/noise ratio. But arguably the Optional way is more eye-friendly for trained professionals. Also, it provides one convenient way to return a default value. With Exceptions, this can only be done in the catch block. One advantage with exceptions is that we can throw Exception across multiple layers easily, and sometimes this can help us get the clean code.</p><p>Another view to understand those difference is from the explicitness point of view. A separate error handling channel is much more explicit than error checks in the middle.</p><h4>Be aware of error’s abstraction level</h4><p>Whenever we write any code, we should be mindful of the abstraction level of our code. The same applies to error handling. When we report any errors, we need to think whether our up layer can make sense of this error and what they can do about it. We should not leak the implementation detail of our code. When applies this principle to Java’s exception, we will translate the low-level exception to exceptions that can be explained in higher-level abstractions, then the higher-level logic is not coupled with low-level exceptions.</p><pre>public class AppExeption extends RuntimeException {<br>    public ApplicationExeption(final String msg) {<br>        super(msg);<br>    }</pre><pre>    public AppExeption(final String msg, <br>                       final Throwable cause) {<br>        super(msg, cause);<br>    }</pre><pre>    public AppExeption(final Throwable cause) {<br>        super(cause);<br>    }<br>}</pre><p>Also, exceptions can serve both as error handling strategy and communication mechanism in your system. The whole department should have the same understanding of its best practices and apply them consistently in the entire system.</p><h4>Error-handling design is part of API design</h4><p>As a guideline for any API design, we want our API has the smallest surface. This is the primary reason that checked exception is considered bad practice for most of the business application. It just bloats our interface unnecessarily.</p><p>Exceptions should be carefully designed and should have a meaningful business meaning. Programer should not just throw exceptions on anything suspicious. Instead, all error scenario should be thought thoroughly, and our business has the final say about how an error should be handled.</p><p>In general, we should try our best to handle errors in our layer. Throwing exception should be the last resort to notify other components to give a hand.</p><h4>The strategies to handle error</h4><p>Whenever we define an error, we should think through whether the caller has any way to handle it. If the caller has no way to handle it and it’s a critical one, we can log and let the application crash. If it’s not critical, we can try our best to return value that’s still meaningful to the caller and no additional overhead on the caller side. For example, for any code that should return a list, if somehow we can’t get the list that caller want, there are three ways to handle it:</p><ul><li>Return null: this shifts the null check responsibility to the caller implicitly. Somewhere else must document the returned value could be null and the caller must handle it.</li><li>Return Optional: this is better than null. It models the valid absence of value explicit. No additional documentation required.</li><li>Return empty list: this is the preferred approach if our business agrees with it. No special handling required.</li></ul><p>This is another general principle for system design. We want any chunk of code has clear boundaries of responsibility. Beyond that, we want to lessen the complexity of our client. That’s the reason that empty list is the preferred approach for error handling.</p><h4>Avoid Simple Log and Rethrow</h4><p>A lot of codebases I worked with still have a lot of simple logging and rethrow for exception handling. First, this indicates that the whole organization doesn’t share the same understanding for exception handling. Second, if logging and rethrow is needed in some case, it can be done by annotation. A company-wide logging framework can be developed for this purpose.</p><h4>Null is a code smell</h4><p>It’s now a common sense that null is at least code smell in software, if not a design error. It represents the wrong way to model the absence of a value in a programming language. Optional in Java 8 make this absence explicit. It also provides constructs like map/filter to retrieve what you want with an easily comprehensible statement, without using the high cognitive-load conditional branches.</p><h4>Use retry mechanism for external dependency</h4><p>For any external dependency, we usually have facades or DAL layer to abstract them away from our business logic. To avoid temporary glitch of those dependencies, we can define a retry strategy using a framework like spring-retry. The system is more robust, and the business logic is not coupled with the low-level retry mechanism.</p><h4>Summary</h4><p>A lot of design strategy is to have each component independent and explicit. For error handling, if we can’t handle it by ourselves, we should at least make it explicit, so our client has no chance to miss the responsibility on their part.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d19ffca2656f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/the-error-handling-done-right-d19ffca2656f">The Error Handling Done Right</a> was originally published in <a href="https://medium.com/swlh">The Startup</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 Write Soft Software]]></title>
            <link>https://medium.com/swlh/how-to-write-soft-software-82919da0ecf0?source=rss-5170a1b413b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/82919da0ecf0</guid>
            <category><![CDATA[software-architect]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Liu Tao]]></dc:creator>
            <pubDate>Mon, 08 Jul 2019 03:57:36 GMT</pubDate>
            <atom:updated>2019-07-08T13:10:55.065Z</atom:updated>
            <content:encoded><![CDATA[<h4>And keep it soft in the long run</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eZPHTzKdnwPP5uVRjMC9Tw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@vegasphotog?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Robert Baker</a> on <a href="https://unsplash.com/search/photos/hard?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Software is Hard</h3><p>Peoples generally think that software is pretty soft and easy to change. It’s right in some sense, if we don’t need to guarantee the software we changed still work. Any experienced programmer will tell you that software is hard to change, and will only get harder and harder over time.</p><h4>What soft means</h4><p>Let’s go to the dictionary and find out what soft means. Below is the first definition from dictionary.com:</p><blockquote>yielding readily to touch or pressure; easily penetrated, divided, or changed in shape; not hard or stiff:</blockquote><p>So peoples are right. Whenever we call something soft, it’s reasonable to expect we can change it easily.</p><h4>Software is hard to change</h4><p>The reason that software is hard to change is the coupling. Software is not something physical. It’s just made up of 0 and 1. There are unlimited ways to create coupling in software, and each one of them could make the software harder and harder.</p><h3>Writing Software is Hard</h3><p>Writing software is easy <strong>if no change required in the future.</strong> Human has the many-thousands-years experience to build something that doesn’t have to be evolvable. Writing software is the first time in human history that we try to build a continuously evolvable system. It’s the evolving requirement that makes writing software so hard.</p><h4>Mismatched Linear, Sequential Methodology</h4><p>For other industries, the process of designing and building something has the following steps:</p><ul><li>Define the target system</li><li>Decompose target into components and build each one separately</li><li>Assemble parts back to the complete system</li></ul><p>This process is iteration by iteration. Once one iteration is done, any improvement can only be implemented in the next iteration.</p><p>With this insight, we thought we could build software in the same fashion, aka <a href="https://en.wikipedia.org/wiki/Waterfall_model">waterfall model</a>. But after practicing waterfall for many years, we realized there is a fundamental mismatch between this methodology and the inherent nature of software development. It misses the <strong>continuous evolvement</strong> part.</p><h4>Evolvement make software hard</h4><p>For software, the target definition and decomposition are quite similar to other industries. But to support continuous evolvability, the assembling methodology needs to be very different. We don’t want the assembling to be hardwired. Instead, we want to tie each piece together to make them work as one complete system. But still, each piece must be individually evolvable. This assembling is the primary source of complexity in software development, and we are still trying to find the best way to do it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*e1NDu8ieGRq9fzNkJg4PXw.png" /><figcaption>Software evolution over time</figcaption></figure><p>Overtimes, each piece could evolve at a different speed and in a different direction, the assembling mechanism must be flexible enough to support this type of evolvement.</p><h4>Misleading software architect title</h4><p>The evolvement requirement also makes the title of software architect totally misleading. Their job is not to draw the blueprint of software and claim it’s done. The actual job should be overseeing the evolvement of the software system and make sure it’s continuously evolvable over time. As pointed out in <a href="https://www.amazon.com/Building-Microservices-Designing-Fine-Grained-Systems/dp/1491950358/ref=sr_1_1?keywords=microservice&amp;qid=1562420790&amp;s=gateway&amp;sr=8-1">this book</a>, the city planner is a much more suitable title, and their responsibilities are to make sure that all the boundaries are well respected.</p><h3>How to Write Soft Software</h3><p>We understand that software is not that soft and writing software is hard. Below I will give a list of principles we can use to develop soft software. Please note software development will never be easy. If its too easy, maybe it doesn’t worth the effort to build it at all. Following the list below can only make the complexity more manageable.</p><h4>Decompose vertically</h4><p>Traditionally, we use 3-tier architecture to decompose the system horizontally — presentation layer, business logic layer, and persistence layer. With system complexity increases, each layer itself could become unmanageable. Vertical is a more scalable approach for decomposition, which means we decompose the system into sub-domains, and then, as you have guessed, into microservices.</p><h4>Use unified communication</h4><p>After the system is decomposed, how we can tie them together becomes the key. Comparing the following two types of systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*B_G_l-ZzBxsnSEAGIHOgOQ.png" /></figure><p>With mesh topology, each component needs to know the location of its dependency component. With bus topology, each component pushes data to the bus and doesn’t need to worry about where it will go and how it can get there. The infrastructure is responsible for routing the data to the interested components. With the bus topology approach, we shift the responsibility like data routing to message bus, and each component is only responsible for its own core business logic.</p><h4>Embrace asynchronous</h4><p>We want communication to be asynchronous most of the time. Synchronicity is an extra overhead we like to avoid. Email and phone calls are two examples of asynchronous and synchronous communication. We know the email is a much more efficient and high throughput way for daily communication need. Most of the time, we don’t need the communication to be synchronous. We only need to guarantee that the other party will get the message at the end.</p><h4>Construct self-contained component</h4><p>Cloud and container technology changed the way how software is developed and deployed. It provides the perfect balance between efficiency and isolation. The output of the development team is a self-contained image, which is immutable and is guaranteed to work in production. Each image is a vertical slice of the whole system and is the only place for the business logic of its subdomain. To communicate with the outside world, each component should be talkative by itself. Whenever it did something meaningful, it should publish it to the message bus.</p><h4>Embrace immutability</h4><p>In the early days of the computer industry, memory and storage are scarce resources. A lot of efforts were put into the language and compiler to generate the most memory-efficient machine code.</p><p>Two advancements in computer hardware, abundant memory and multiple-core CPU, make immutability more and more relevant. But the whole industry is still trying to find a way to embrace immutability in our daily practice.</p><p>When the mutation is unavoidable, we should be at least very clear about the scope of each modification. All side-effect should be explicit, and no hidden side-effect is allowed.</p><h3>Conclusion</h3><p>The ideal conformation for software should be antifragile. Each component can grow and shrink as needed. Messaging is one of the loosest forms of coupling we ever know. Our software will be evolvable enough if we can build it using only message-based coupling. We are still at the early stage of exploring message-driven system design. But the result so far looks very promising.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82919da0ecf0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/how-to-write-soft-software-82919da0ecf0">How to Write Soft Software</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Programmer To Business Enabler]]></title>
            <link>https://medium.com/zero-equals-false/from-programmer-to-business-enabler-fc5c1bd36c39?source=rss-5170a1b413b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc5c1bd36c39</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <dc:creator><![CDATA[Liu Tao]]></dc:creator>
            <pubDate>Fri, 05 Jul 2019 22:54:56 GMT</pubDate>
            <atom:updated>2019-07-06T03:34:50.513Z</atom:updated>
            <content:encoded><![CDATA[<h4>And how it can help you advance further in your career.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kM-2tN39zf44TbqbfvsPNg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Markus Spiske</a> on <a href="https://unsplash.com/search/photos/system?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><strong>You love coding, great. </strong>After practicing in this industry for many years, sometimes, you may be wondering what’s the next step. To survive as a programmer, we always have to write working code and learn new technologies. But to be a great developer, there is something deeper that we need to grasp. This post gives a list of those crucial aspects that may help you advance further in your career.</p><h3>Understand the Problem Space</h3><p>Any software development requires two types of knowledge, technical knowledge and domain knowledge. Many programmers put a lot of effort into the technical side and assume that domain knowledge will slowly build up over time. It would be much better if we intentionally put efforts into learning the domain and try to understand it in a bigger picture. Mainly we need to pay attention to the following aspects:</p><h4>Understand where the money comes from</h4><p>All social activity can be explained from the economic point of view. Programming is no exception here. For whatever software being written, there must be a financial motivation behind it. This motivation will serve as a guideline for domain decomposition and sub-domain prioritization. We need to focus on the core sub-domain that could give the enterprise a competitive advantage.</p><h4>Understand the communication in the domain</h4><p>As many domain-driven designer practitioners observed, the communication between domain experts often reveals essential strategies to decompose the system. It’s the perfect abstraction level we need to understand the domain. For example, when developing software for the healthcare industry, we should not go too deep and become doctor ourselves. More importantly, we need to understand the communication between parties involved in the industry. It is this communication and terminology that help us model the business domain correctly.</p><h4>Understand how the business will evolve</h4><p>The software itself is not an industry, but it’s <a href="https://a16z.com/2011/08/20/why-software-is-eating-the-world/">eating the other industry</a>. The software provides new capabilities that are unprecedented and unparalleled in the world. A lot of new opportunities could emerge when the software is embedded in every aspect of the established industry.</p><p>As a software developer, on top of understanding how the domain works now, we need to help the business to make use of those capabilities to evolve the domain. The more we think about the big picture, the more valuable we are as developers.</p><h3>Explore the Solution Space</h3><p>With the knowledge about money and communication in problem space, we are well equipped to decompose the problem domain into sub-domains and distill the core sub-domain from them. As programmers, producing working solution should only be the entry level goal we have to achieve. In the long term, we should target reducing the total cost of product maintenance and evolvement.</p><h4>Be a problem solver</h4><p>In some agile environment, the product owner will decompose user requirement into user stories. Many developers blindly follow whatever in the story and don’t pay enough attention to the big picture.</p><p>We are paid to solve business problems. We are not paid to write smart or fancy code. If the solution could be lower cost without code, then go for it. Being able to write code doesn’t mean we have to solve every problem with the code. A lot of developers tends to solve every problem with the code. For example, a lot of energy is wasted to solve the edge case that has very minimum business value. A careful analysis of ROI(return of investment) is needed before we put effort into any edge cases.</p><h4>Chase simple solution</h4><p>As mentioned <a href="https://medium.com/swlh/write-simple-and-no-surprise-code-24fcf6f0156a">here</a>, a simple and elegant solution should be our ultimate goal. Whenever we find that coding is hard, we are probably doing something wrong. Instead of pushing hard to crush the obstacles, we should step back to think through the whole problem, or maybe try to attack it from a different angle.</p><p>Don’t just stop at the first working solution you produce, don’t get too attached to your working solution.</p><h4>Avoid unnecessary abstraction</h4><p>Programmers love abstractions, that’s why we invented tools like OOD to help us abstract and model the business domain. After seeing so many meaningless inheritance hierarchies, we finally realized that inheritance is not the right tool to model the business domain. It should be used with caution, and any time, more than three levels of inheritance are merely evil.</p><p>Also, we should be aware of the abstraction level we are working on and don’t mix different abstraction level in the single module. Here the module could be any component like microservices, class, or even functions. For example, at the function level, general purpose code should not be mixed with specific code.</p><h4>As explicit as possible</h4><p>Being explicit means no surprise and works just as everyone could guess. It is always better to be explicit. Hiding important domain concept behind abstraction will significantly increase maintenance cost. To achieve explicitness, we should not allow any hidden side-effects in our system. Whenever we feel we may confuse someone else or future ourselves, we need to step back and start refactoring. The refactoring could be simply renaming variables or functions, but we need to be cautious about any implicitness and try to make everything as explicit as possible.</p><h3>Conclusion</h3><p>Writing a working code is just the minimum requirement for anyone who wants to earn butter and bread with coding. More importantly, we should target reducing Total Cost of Ownership for our business. We need to decompose the business domain into sub-domain and put the right effort in each sub-domain.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc5c1bd36c39" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zero-equals-false/from-programmer-to-business-enabler-fc5c1bd36c39">From Programmer To Business Enabler</a> was originally published in <a href="https://medium.com/zero-equals-false">Zero Equals False</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Write simple and no-surprise code]]></title>
            <link>https://medium.com/swlh/write-simple-and-no-surprise-code-24fcf6f0156a?source=rss-5170a1b413b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/24fcf6f0156a</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Liu Tao]]></dc:creator>
            <pubDate>Wed, 03 Jul 2019 03:03:27 GMT</pubDate>
            <atom:updated>2019-07-03T21:23:03.348Z</atom:updated>
            <content:encoded><![CDATA[<h3>Write Simple and No-surprise Code</h3><h4>And improve your productivity in the long run</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YaooEzYmS_IpTMofcpNchg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@oks_ong95?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Khai Sze Ong</a> on <a href="https://unsplash.com/search/photos/simple?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Why should we write simple code</h3><p>As programmers, one of our most important tasks is to manage complexity. Cognitive load in our code is one primary source of it. If our code is only made up of dull statements, no decision points in between, no fancy data structure or algorithm, the cognitive load is much lower.</p><p>Of course, there are cases that we need to use advanced algorithms, maybe for performance reason. Then as a last resort, we should encapsulate them with boring interfaces, with a meaningful name and minimum parameter.</p><h3>First thing first, try your best to avoid code</h3><p>The simplest code we could ever produce is no code at all. Code is easy to create but hard to remove. Each developer should have a mindset that your code is your debt, not asset. The more you produce, the more you owe.</p><p>To write less, we have to think much much more. Of course, thinking takes more time for now, but this is only a one-time investment. In the long run, you or your organization will be debtless.</p><p>Whenever we get any code working, we should not stop there. Believing the working code is best one prevents us from finding a better solution. Instead, we need to read through our working code many times and think hard about places to improve. Often, <a href="http://www.stackoverflow.com/">StackOverflow</a> is the place to find a more elegant solution. In the beginning, we may not know exactly what better solutions are. But at least, we should develop a sense of code complexity, and that’s our motivation to find a simple solution. Remember, never stopping at your first working code, any working solution is just a start point for a better one.</p><h3>If possible, use annotation</h3><p>This tip is a followup on the previous one. Many of our crosscutting concern could be handled by annotation, like logging or error handling.<br>For Java developers, Lombok is an excellent library for spicing up your java, we should use it as much as possible.</p><p>For example, instead of doing null checks by ourselves, we can use <em>@NonNull</em> annotation. Instead of writing our own get/setter or constructor, we can use @Getter, <em>@Setter</em> and @<em>AllArgsConstructor</em>. Instead of construct log on our own, we can use @Log to construct it.</p><p>All of those seem not a big deal by themselves. However, complexity is accumulated over time, and it’s always better to write a little bit less code. <br>Also, annotation is more declarative than code. The maintenance cost is smaller in the long run.</p><h3>Use control only when unavoidable</h3><p>Of course, no matter how hard we try, we still have to write some code. Fluent API calls is an elegant way to avoid decision point like if/else. Let’s consider following code snippet about deep null checks:</p><pre>if (a != null &amp;&amp; <br>    a.getItem() != null &amp;&amp; <br>    a.getItem().getValue() != null) {<br>    return process(a.getItem().getValue());<br>} else {<br>    return false;<br>}</pre><p>With Java 8’s Optional, we can write something like the following:</p><pre>Optional.ofNullable(a)<br>        .map(A::getItem)<br>        .map(Item:getValue)<br>        .map(this::process)<br>        .orElse(false);</pre><p>Although the second approach has more lines of code, it is still more readable. For cognitive load, the line number doesn’t matter that much, it’s the decision points that make code digestion much harder.</p><p>Considering the following example, we can put all logic inside forEach’s lambda:</p><pre>list.streams().forEach(p -&gt; {<br>   if (p.isValid()) {<br>     process(p);<br>   }<br>})</pre><p>Alternatively, we can split the logic and do the filtering in between.</p><pre>list.streams()<br>    .filter(P::isValid)<br>    .forEach(this::process)</pre><p>In general, the boring code should have only one execution path and it’s very easy to follow through.</p><p>When it comes to OOP, polymorphism is one elegant way to get rid of if/else, we can group logic into subclasses and the compiler or runtime help us pick the expected execution path. So we don’t need to do if/else explicitly in our code. In my option, this is the right use case for inheritance. Inheritance is not the right tool to model complex business domain. Instead, we can use it to replace if/else, or we can use it to share some utility functionality between subclasses.</p><h3>Extract more data from your code</h3><p>Notably, this post is all about getting rid of decision points in your code. Extract more data from your code is also one way to achieve it.<br>Let me use the following use case as an example. There are two address objects we get from the server. We need to check whether these two addresses are the same. The business rule defines that not all fields need to be compared. Some fields should be case insensitive, empty string and null should be considered the same. Instead of comparing those fields one by one, we can do it with the following approach. The code snippet is in Javascript and we use underscore.js to simplify the logic:</p><pre>let caseInSensitive = (val1, val2) =&gt; {<br>   val1 = _.capitalize(val1 || “”); <br>   val2 = _.capitalize(val2 || “”);<br>   return val1 === val2;<br>}</pre><pre>let normal = (val1, val2) =&gt; {<br>   return val1 === val2;<br>}</pre><pre>let properties = [{<br>   “path”: “addressLine1”,<br>   “comparator”: caseInSensitive<br> },{<br>   “path”: “streetNumber”,<br>   “comparator”: normal<br> }<br>]</pre><p>Of course, there could more comparators and more properties. With all those defined, the implementation of address comparator is much simpler:</p><pre>let addressComprator = (addr1, addr2) =&gt; {<br>    return _.every(properties, prop =&gt; {<br>        let val1 = _.get(addr1, prop.path);<br>        let val2 = _.get(addr2, prop.path),</pre><pre>        return prop.comparator(val1, val2);<br>    });<br>}</pre><p>As you can see, data is more declarative than code, since it doesn’t have any decision points inside. The more data we can get from the logic, the more declarative our code is.</p><h3>Separate business logic from error handling</h3><p>In the ideal world, all your code should be only about happy path. Frameworks, libraries and annotation can handle all the errors for you.<br>But still, we are not there yet, and we have to handle error in our code. There is a long-lasting debate on the approach for error handling, whether we should use exceptions or return error code. One strong argument for exceptions is that error code has to be checked by its calling method, but exceptions can be thrown far away and can be caught in a central place, like in Spring’s filter. However, if we throw exception too far, we may lose its semantic meaning. From this point of view, Java 8’s Optional is a sweet spot between error code and exception. With Optional, the execution path of your code is mostly about your business logic. You only need handle errors at the end.</p><pre>if (dto != null) {<br>    result1 = processA(dto);<br>}<br> <br>if (result1 != null) {<br>    result2 = processB(result1);<br>}<br> <br>if (result2 != null) {<br>    result3 = processC(result2); <br>}<br> <br>return result3 != null;</pre><p>With Java 8’s Optional, we can have something like below:</p><pre>Optional.ofNullable(dto)<br>        .map(this::processA)<br>        .map(this::processB)<br>        .map(this::processC)<br>        .map(r -&gt; r != null)<br>        .orElse(false)</pre><p>Clearly, the second approach is much more readable, because there is no decision point between statements, also the intermediate<br>state is not needed anymore. State and decision point are two sources of complexity.</p><h3>Summary</h3><p>In conclusion, thinking harder is the first step and most important mindset to write less code. Whenever you see any if/else in your code, try to think of a way to eliminate this decision point. Also, annotation is a noninvasive way to modify your code’s behavior and should be used as much as you can.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24fcf6f0156a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/write-simple-and-no-surprise-code-24fcf6f0156a">Write simple and no-surprise code</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>