<?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 Eason on Medium]]></title>
        <description><![CDATA[Stories by Eason on Medium]]></description>
        <link>https://medium.com/@eason91367?source=rss-51c343ff6947------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*HlbJbI9gxiiX0ACi</url>
            <title>Stories by Eason on Medium</title>
            <link>https://medium.com/@eason91367?source=rss-51c343ff6947------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 18:12:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@eason91367/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[Flutter’s deep link routing]]></title>
            <link>https://medium.com/@eason91367/flutters-deep-link-routing-cf75b4b7a214?source=rss-51c343ff6947------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf75b4b7a214</guid>
            <category><![CDATA[android-ios]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Eason]]></dc:creator>
            <pubDate>Mon, 23 Dec 2024 06:36:19 GMT</pubDate>
            <atom:updated>2024-12-23T06:36:19.413Z</atom:updated>
            <content:encoded><![CDATA[<p>There already plenty of articles teaching how to build up deep link for flutter app, so I’m not here to illustrate how the create deep link. Instead, I want to talk about the routing difference between ios and android platform.</p><p>The package I use for routing is go_router and uni_links. In the very begining, I only use go_router to organize my routes. However, after I implemented deep link, I found there’s different mechanism between ios and android and this would need uni_link page for help.</p><p>The issue I bumped into is when user click on my deep link and want to do some routing. IOS and Android will analyze the route in different place. Let me use some example code to explain this.</p><p>This is the route config of the</p><pre>final _router = GoRouter(<br>  initialLocation: &#39;/&#39;,<br>  routes: [<br>    GoRoute(<br>      name: &#39;home&#39;, // Optional, add name to your routes. Allows you navigate by name instead of path<br>      path: &#39;/&#39;,<br>      builder: (context, state) =&gt; HomeScreen(),<br>    ),<br>    GoRoute(<br>      name: &#39;shope&#39;,<br>      path: &#39;/shope&#39;,<br>      builder: (context, state) =&gt; ShopeScreen(),<br>    ),<br>  ],<br>);</pre><p>For Android, things worked perfectly. If your deep link is: “https//domain.com/shope”, go_router will successfully capture the path you want to go which is “/shope”, and navigate to the right page.</p><p>On the other hand, IOS will not able to capture the subpath, and would only open the home page for you, which is “‘/”.</p><p>To fix this, we will need uni_link to help us listen on path change. Here’s the code:</p><pre>void initUniLinks() {<br>    sub = getLinksStream().listen((String link) {<br>      // Handle the received link<br>      handleLink(link);<br>    }, onError: (err) {<br>      // Handle any errors<br>      print(err);<br>    });<br>  }<br>  void handleLink(String link) {<br>    // Implement logic to handle the Uni_Link<br>    print(&#39;Received link: $link&#39;);<br>  }</pre><p>With this stream, we finally able to handle the right path for both platform. But there’s a tiny problem, android will navigate twice if the path is the same as go_router has. My personal solution is to use unique path to handle in the uni_link. I think there’s a better solution and welcome to share in the comment.</p><p>If you think this article helps, please clap for me, thank you very much!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf75b4b7a214" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What will long transaction cost?]]></title>
            <link>https://medium.com/@eason91367/what-will-long-transaction-cost-a2034608d63d?source=rss-51c343ff6947------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2034608d63d</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Eason]]></dc:creator>
            <pubDate>Tue, 03 Dec 2024 09:40:57 GMT</pubDate>
            <atom:updated>2024-12-03T09:40:57.821Z</atom:updated>
            <content:encoded><![CDATA[<p>When designing an application service which is based on a database, transaction is a good tool to achieve atomic operation. What is atomic? In software, sometimes even a very simple operation would also contain more than two database instruction which would be fine if the operation comes one by one and in a right order. However, in the real world, user’s request will come concurrently so the order would not be as what you thought.</p><p>For example, there are two users, A and B, trying to deposit money to the same account, and “deposit” contain two instruction get the balance and add the amount. If the order is:<br>1. A get the balance. <br>2. B get the balance.<br>3. A add the amount.<br>4. B add the amount.<br>Now the result is not what we expect. So here come’s atomic operation to make get and add as one single operation, you can’t separate them.</p><p>Although the operation now becomes atomic but it still need to access database multiple times so the overall time will not reduce. If you contain many operation in a transaction even include a very huge loop, this is called long transaction.</p><p>So what is the downside of long transaction? Database has maximum connection pool, if the connection is fooled, database will reject others and will cause request failed. Long connection will occupy the connection until all the operations are finished. This will easily cause connection fool compared to short tiny instruction. This means your server will not able to afford high concurrent users.</p><p>Would this lead to performance goes down? No and yes. It won’t cause worse response time, since like what I said it’s just combine multiple instructions together. Sometimes it would has better response time since you use single connection to do all the work. However if you want to cost down and still want to have lots of users at the same time. Then long transaction will not what you should use.</p><p>There’s another situation you need to consider: Can you tolerate race condition? With short instruction, you can tolerate more users, but when it is close to the limit, some of request will failed, this means your request might have partial failure. If your service is very complicated, I recommend you still use long transaction. It’s better to have simple live though.</p><p>I hope this article provide some good thoughts for you, and if there’s anything wrong, please let me know!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2034608d63d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GRPC]]></title>
            <link>https://medium.com/@eason91367/grpc-efbd82da2b05?source=rss-51c343ff6947------2</link>
            <guid isPermaLink="false">https://medium.com/p/efbd82da2b05</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Eason]]></dc:creator>
            <pubDate>Thu, 01 Aug 2024 07:58:37 GMT</pubDate>
            <atom:updated>2024-08-01T07:58:37.243Z</atom:updated>
            <content:encoded><![CDATA[<h3>Abstract</h3><p>In this article, I’ll divide into three parts which are “<strong>what is gRPC?</strong>”, <strong>“Compare to restful RPC”</strong> and “<strong>how to use gRPC?</strong>”. The contents in this article are all found from internet and organized based on my personal understanding. Feel free to fix the mistakes or add more contents to help other readers to comprehend gRPC.</p><h3>What is gRPC?</h3><p>GRPC is a kind of remote procedure call which is an <strong>open-source developed by Google</strong>, aimed for <strong>micro-service’s communication</strong> usage. Unlike restful RPC which focus on easy to use and human readability, gRPC emphasize more on performance. There’s no which one is better than the other. Only which one is better in some use cases.</p><p>GRPC is built base on two main mechanism:<br>1. Protocol buffer:</p><p>Protocol buffer is a format to transport message between RPC. Protocol buffer will <strong>serialize the message into binary</strong> before sent out. By this way, it’ll reduce the size of payload and also enhance the performance of serialization. However this comes from a trade off which the message will become <strong>human unreadable</strong>.<br>Another additional advantage is that protocol buffer will somehow <strong>enhance security</strong>, since the payload is in binary. However the message is actually not encrypted which means hackers can transform the binary back to original string message. Therefore, we still need to keep the message from being stolen.</p><p>2. HTTP/2:</p><p>HTTP/2 is invented to improve the page load speed of website, and is highly compatible to HTTP/1. The enhancement include:<br>- <strong>Request and response multiplexing:<br></strong>This means in HTTP/2, if you have multiple files or request from the same domain, you now only have to handshake once and reuse the connection until all the files and requests are finished.<br>-<strong> Header compression:</strong><br>In HTTP/1, the header would be transferred with plaintext, so if it carried with cookies, than it is possible that the size would up to several MBs. Therefore HTTP/2 use HPACK algorithm to reduce 80% size of header.<br><strong>- Server push:<br></strong>When you’re using traditional static file server with HTTP/1, every request will only get what they request. However in the real life situation, lots of files are relevant and always required together. HTTP/2 now can let server side decide not only return one file but all related files using stream.<br><strong>- Binary framing layer:<br></strong>Lots people got confused with this, since as we all know that all the data is transferred with binaries. This is correct, so the point is not the word “Binary” but “framing”. In order to take advantage of multiplexing, HTTP/2 will send the data concurrently. Hence it is not possible to wait until a file delivered and than next one start. HTTP/2’s solution is to ask every request follow the rules of framing so that receiver would know how to reconstruct the package. This is the reason why HTTP/2 can support streaming now.</p><h3>Compare to RESTful</h3><h4>Similarity</h4><ol><li><strong>Use HTTP as protocol</strong>: However, restful API usually use HTTP/1.1 and gRPC use HTTP/2. You can also upgrade your restful API server to HTTP/2</li><li><strong>Statelessness:</strong> Both gRPC and REST are designed to be stateless, which means that every request contains all of the information the server needs to process it. The server therefore does not have to retain any session state.</li></ol><h4>Difference</h4><ol><li><strong>Data format</strong>: Restful API use <strong>plain-text</strong> format, such as JSON, XML. On the other hand, gRPC use Protobuf to encode message in binary form</li><li><strong>Communication pattern</strong>: Restful API only support unary communication. GRPC support bi-direction communication.</li><li><strong>Long connection:</strong> Restful API have to upgrade to websocket protocol and maintain heartbeat method manually. to have a long connection which gRPC support long connection itself and lots of sdk/package will use long connection as default.</li><li><strong>Coupling</strong>: Restful API is loosely coupled. GRPC need to generate code on both server and client side, hence it is considered highly coupled.</li></ol><h3>How to use gRPC</h3><ol><li>Install protobuf</li></ol><pre>brew install protobuf</pre><p>2. Install Protocol Buffers Plugins</p><pre>go install google.golang.org/protobuf/cmd/protoc-gen-go@latest<br>go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest</pre><p>3. Ensure protoc-gen-go and protoc-gen-go-grpc are in your PATH</p><pre>echo &#39;export PATH=$PATH:$(go env GOPATH)/bin&#39; &gt;&gt; ~/.zshrc<br>source ~/.zshrc<br><br>which protoc-gen-go<br>which protoc-gen-go-grpc</pre><p>4. Generate a .proto file</p><pre>syntax = &quot;proto3&quot;;<br><br>option go_package = &quot;test_grpc/proto&quot;;<br><br>package test;<br><br>// The greeting service definition.<br>service Greeter {<br>  // Sends a greeting<br>  rpc SayHello (HelloRequest) returns (HelloReply);<br>}<br><br>// The request message containing the user&#39;s name.<br>message HelloRequest {<br>  string name = 1;<br>}<br><br>// The response message containing the greetings<br>message HelloReply {<br>  string message = 1;<br>}</pre><ul><li>go_package: specifies the Go package path for the generated code.</li><li>package: create a namespace under which all the messages and services defined in this .proto file will reside.</li><li>message: modal</li><li>service: RPC function</li></ul><p>5. Run the following command in your project root directory to generate the Go code:</p><pre>protoc --go_out=. --go-grpc_out=. $protoFileName.proto</pre><p>This will generate two files: <strong>test_grpc/helloworld.pb.go</strong> and <strong>test_grpc/helloworld_grpc.pb.go</strong>.</p><p>6. Implement Server code. Create a <strong>/server</strong> directory and add a <strong>main.go</strong> file:</p><pre>package main<br><br>import (<br>    &quot;context&quot;<br>    &quot;log&quot;<br>    &quot;net&quot;<br><br>    &quot;google.golang.org/grpc&quot;<br>    pb &quot;test_grpc/test_grpc/proto&quot;<br>)<br><br>// server is used to implement helloworld.GreeterServer.<br>type server struct {<br>    pb.UnimplementedGreeterServer<br>}<br><br>// SayHello implements helloworld.GreeterServer<br>func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {<br>    log.Printf(&quot;Received: %v&quot;, in.GetName())<br>    return &amp;pb.HelloReply{Message: &quot;Hello &quot; + in.GetName()}, nil<br>}<br><br>func main() {<br>    lis, err := net.Listen(&quot;tcp&quot;, &quot;:50051&quot;)<br>    if err != nil {<br>        log.Fatalf(&quot;failed to listen: %v&quot;, err)<br>    }<br>    s := grpc.NewServer()<br>    pb.RegisterGreeterServer(s, &amp;server{})<br>    log.Printf(&quot;server listening at %v&quot;, lis.Addr())<br>    if err := s.Serve(lis); err != nil {<br>        log.Fatalf(&quot;failed to serve: %v&quot;, err)<br>    }<br>}</pre><p>7. Implement Client code. Create a client directory and add a main.go file:</p><pre>package main<br><br>import (<br>    &quot;context&quot;<br>    &quot;log&quot;<br>    &quot;os&quot;<br>    &quot;time&quot;<br><br>    &quot;google.golang.org/grpc&quot;<br>    pb &quot;test_grpc/test_grpc/proto&quot;<br>)<br><br>const (<br>    address     = &quot;localhost:50051&quot;<br>    defaultName = &quot;world&quot;<br>)<br><br>func main() {<br>    // Set up a connection to the server.<br>    conn, err := grpc.Dial(address, grpc.WithInsecure(), grpc.WithBlock())<br>    if err != nil {<br>        log.Fatalf(&quot;did not connect: %v&quot;, err)<br>    }<br>    defer conn.Close()<br>    c := pb.NewGreeterClient(conn)<br><br>    // Contact the server and print out its response.<br>    name := defaultName<br>    if len(os.Args) &gt; 1 {<br>        name = os.Args[1]<br>    }<br>    ctx, cancel := context.WithTimeout(context.Background(), time.Second)<br>    defer cancel()<br>    r, err := c.SayHello(ctx, &amp;pb.HelloRequest{Name: name})<br>    if err != nil {<br>        log.Fatalf(&quot;could not greet: %v&quot;, err)<br>    }<br>    log.Printf(&quot;Greeting: %s&quot;, r.GetMessage())</pre><p>8. The whole project architecture looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fs1vmlX4q8JlEW2G0970sQ.png" /></figure><p>Although gRPC has higher performance than RESTful API, but it comes with sacrifice. It sacrifice the flexibility and simplicity. So for me, I’ll only use in the internal system. I think this is why everyone says this is for microservices. Since in microservice, it will communicate within each service in the internal.</p><p>This is all for now. Hope you guys enjoy GRPC.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efbd82da2b05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Pattern — Factory(Golang)]]></title>
            <link>https://medium.com/@eason91367/design-pattern-factory-golang-401142a53f3a?source=rss-51c343ff6947------2</link>
            <guid isPermaLink="false">https://medium.com/p/401142a53f3a</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Eason]]></dc:creator>
            <pubDate>Tue, 30 Jul 2024 02:22:45 GMT</pubDate>
            <atom:updated>2024-07-30T02:22:45.250Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design Pattern — Factory(Golang)</h3><p>Sometimes we will face some situations when designing a system which in side it have many kinds of object having same functions. For example, hero system. Hero system allow hero have different professions. Hero can be a warrior, wizard, or even Archer and these professions would be chosen by users. Hence, you need a place to encapsulate the choose and creation part. Factory Pattern is here steps in to deal with this.</p><p>The easiest way to do this is to make a function which accept type string or enum and based on it to return the professions which by the way is called Simple Factory. Here’s the code:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>type Hero interface {<br> Describe()<br>} <br><br>type warrior struct {<br>}<br><br>func(w *warrior) Describe() {<br> fmt.Println(&quot;I&#39;m warrior&quot;)<br>}<br><br>type wizard struct {<br>}<br><br>func(w *wizard) Describe() {<br> fmt.Println(&quot;I&#39;m wizard&quot;)<br>}<br><br>func heroFactory(heroType string) Hero {<br> if heroType == &quot;warrior&quot; {<br>  return &amp;warrior{}<br> }<br> if heroType == &quot;wizard&quot; {<br>  return &amp;wizard{}<br> }<br> return nil<br>}<br><br>func main() {<br> hero := heroFactory(&quot;warrior&quot;)<br> hero.Describe()<br>}</pre><p>If you take a look at the code, heroFactory function will need to modify when the process of construct a hero is changed which obviously against Open/Close principle. To avoid this, we can create profession factories in advance. Now you can encapsulate the construction process inside this profession factory. Here’s the modified code:</p><p>hero.go:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>type Hero interface {<br> Describe()<br>} <br><br>type warrior struct {<br>}<br><br>func(w *warrior) Describe() {<br> fmt.Println(&quot;I&#39;m warrior&quot;)<br>}<br><br>type wizard struct {<br>}<br><br>func(w *wizard) Describe() {<br> fmt.Println(&quot;I&#39;m wizard&quot;)<br>}<br><br>func heroFactory(heroType string) Hero {<br> var professionFactory ProfessionFactory<br> if heroType == &quot;warrior&quot; {<br>  professionFactory = &amp;warriorFactory{<br>  }<br> }<br> if heroType == &quot;wizard&quot; {<br>  professionFactory = &amp;wizardFactory{<br>  }<br> }<br><br> if professionFactory != nil {<br>  return professionFactory.CreateHeroWithProfession()<br> }<br> return nil<br>}</pre><p>professions.go</p><pre>package main<br><br>type ProfessionFactory interface {<br> CreateHeroWithProfession() Hero<br>}<br><br>type warriorFactory struct{<br>}<br><br>func(wf *warriorFactory) CreateHeroWithProfession() Hero {<br> // you can add any further process here<br> return &amp;warrior{<br> }<br>}<br><br>type wizardFactory struct{<br>}<br><br>func(wf *wizardFactory) CreateHeroWithProfession() Hero {<br> // you can add any further process here<br> return &amp;wizard{<br> }<br>}</pre><p>main.go</p><pre>package main<br><br>func main() {<br> hero := heroFactory(&quot;warrior&quot;)<br> hero.Describe()<br>}</pre><p>Now, the code looks clean, and every component now has smaller responsibility. Next, let’s add equipments to hero. To do so, maybe you’ll add some code to the factory like this:</p><pre>func(wf *warriorFactory) CreateHeroWithProfession() Hero {<br> // you can add any further process here<br> return &amp;warrior{<br>  Clothe: &amp;clothe{},<br>  Weapon: &amp;weapon{}<br> }<br>}</pre><p>However, this will lead to against Open/Close principle again and also CreateHeroWithProfession has too much jobs. Hence, apparently we need to separate the responsibility by adding another sets of factories to control clothe and weapon which by the way is called abstract factory pattern. There are lots of ways to group these factories. If you focus more on grouping clothes and weapons separately, you can have clothe factory and weapon factory. But to simplify the example, I will focus more on profession’s equipments. So I will have equipments factory for every professions. Here’s the code:</p><p>equipments.go</p><pre>package main<br><br>type Clothes interface {<br> GetName() string<br>}<br><br>type Weapon interface {<br> GetName() string<br>}<br><br>type Armor struct {<br>}<br><br>func(a *Armor) GetName() string {<br> return &quot;wears Armor&quot;<br>}<br><br>type Leather struct {<br>}<br><br>func(a *Leather) GetName() string {<br> return &quot;wears Leather&quot;<br>}<br><br>type Sword struct {<br>}<br><br>func(a *Sword) GetName() string {<br> return &quot;use Sword&quot;<br>}<br><br>type Wand struct {<br>}<br><br>func(a *Wand) GetName() string {<br> return &quot;use Wand&quot;<br>}</pre><p>equipment_factories.go</p><pre>package main<br><br>type EquipmentFactory interface {<br> GetWeapon() Weapon<br> GetClothe() Clothes<br>}<br><br>type WarriorEquipmentFactory struct {<br>}<br><br>func (wef *WarriorEquipmentFactory) GetWeapon() Weapon {<br> return &amp;Sword{}<br>}<br><br>func (wef *WarriorEquipmentFactory) GetClothe() Clothes {<br> return &amp;Armor{}<br>}<br><br>type WizardEquipmentFactory struct {<br>}<br><br>func (wef *WizardEquipmentFactory) GetWeapon() Weapon {<br> return &amp;Wand{}<br>}<br><br>func (wef *WizardEquipmentFactory) GetClothe() Clothes {<br> return &amp;Leather{}<br>}</pre><p>professions.go</p><pre>package main<br><br>type ProfessionFactory interface {<br> CreateHeroWithProfession() Hero<br>}<br><br>type warriorFactory struct{<br> equipmentFactory EquipmentFactory<br>}<br><br>func(wf *warriorFactory) CreateHeroWithProfession() Hero {<br> // you can add any further process here<br> return &amp;warrior{<br>  Weapon: wf.equipmentFactory.GetWeapon(),<br>  Clothe: wf.equipmentFactory.GetClothe(),<br> }<br>}<br><br>type wizardFactory struct{<br> equipmentFactory EquipmentFactory<br>}<br><br>func(wf *wizardFactory) CreateHeroWithProfession() Hero {<br> // you can add any further process here<br> return &amp;wizard{<br>  Weapon: wf.equipmentFactory.GetWeapon(),<br>  Clothe: wf.equipmentFactory.GetClothe(),<br> }<br>}</pre><p>hero.go</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>type Hero interface {<br> Describe()<br>} <br><br>type warrior struct {<br> Clothe Clothes<br> Weapon Weapon<br>}<br><br>func(w *warrior) Describe() {<br> fmt.Println(&quot;I&#39;m warrior&quot;)<br> fmt.Println(w.Clothe.GetName())<br> fmt.Println(w.Weapon.GetName())<br>}<br><br>type wizard struct {<br> Clothe Clothes<br> Weapon Weapon<br>}<br><br>func(w *wizard) Describe() {<br> fmt.Println(&quot;I&#39;m wizard&quot;)<br> fmt.Println(w.Clothe.GetName())<br> fmt.Println(w.Weapon.GetName())<br>}<br><br>func heroFactory(heroType string) Hero {<br> var professionFactory ProfessionFactory<br> if heroType == &quot;warrior&quot; {<br>  professionFactory = &amp;warriorFactory{<br>   equipmentFactory: &amp;WarriorEquipmentFactory{},<br>  }<br> }<br> if heroType == &quot;wizard&quot; {<br>  professionFactory = &amp;wizardFactory{<br>   equipmentFactory: &amp;WizardEquipmentFactory{},<br>  }<br> }<br><br> if professionFactory != nil {<br>  return professionFactory.CreateHeroWithProfession()<br> }<br> return nil<br>}</pre><p>main.go</p><pre>package main<br><br>func main() {<br> hero := heroFactory(&quot;warrior&quot;)<br> hero.Describe()<br>}</pre><p>This article is a little bit longer than before because I think is better to have more details for you to differentiate different kind of factories. I hope you have the same feeling as mine which I think is more layers of grouping from simple factory to abstract factory. Use them properly by different cases. Wish you all have a nice day~.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=401142a53f3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Pattern — Decorator（）]]></title>
            <link>https://medium.com/@eason91367/design-pattern-decorator-e634a87dfbff?source=rss-51c343ff6947------2</link>
            <guid isPermaLink="false">https://medium.com/p/e634a87dfbff</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Eason]]></dc:creator>
            <pubDate>Tue, 16 Jul 2024 02:10:25 GMT</pubDate>
            <atom:updated>2024-07-16T02:10:25.471Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design Pattern — Decorator(Golang)</h3><p>Have you ever met some point that some object would add extra duties onto a method based on some conditions? For example, you’re designing a game character and whenever it upgraded or change career, you’ll need to make some change to its attack method. I think the easiest solution would be you add an attribute(maybe level count or something) and use that as condition in attack method. However, in this way, you’ll found you’re always changing the attack method when upper bound of level increased. This obviously against Open/Close principle.</p><p>To avoid this, we can make upgrade and changing career as individual attack classes and make them in charge of different kind of attack. Furthermore, inside their attack function, find a way to not only pass in the character but also return a character. That’s to say, attack classes are also subclass of character.</p><p>Here are some examples of how to implement decorator in Golang:</p><ol><li>Using struct + interface:</li></ol><pre>package main<br><br>import &quot;fmt&quot;<br><br>type IHero interface {<br> Attack() string<br>}<br><br>type Hero struct {<br>}<br><br>type Upgrade struct {<br> hero IHero<br>}<br><br>type ChangeCareer struct {<br> hero IHero<br>}<br><br><br>func (h *Hero) Attack() string {<br> return &quot;start attack&quot;<br>}<br><br>func (u *Upgrade) Attack() string {<br> return u.hero.Attack() + &quot; with upgraded attack&quot;<br>}<br><br>func (u *ChangeCareer) Attack() string {<br> return u.hero.Attack() + &quot; with special attack&quot;<br>}<br><br>func main() {<br> newHero := &amp;Hero{}<br><br> upgradedHero := &amp;Upgrade{hero: newHero}<br> changedCareerHero := &amp;ChangeCareer{hero: upgradedHero}<br> fmt.Println(changedCareerHero.Attack())<br>}</pre><p>2. Using struct + interface + function</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>type Hero struct {<br> AttackFunc []AttackFunc<br>}<br><br>type AttackFunc func()<br><br>func (h *Hero) Attack() {<br> fmt.Println(&quot;start attack&quot;)<br><br> for i := 0; i &lt; len(h.AttackFunc); i++ {<br>  h.AttackFunc[i]()<br> }<br>}<br><br>func UpgradedAttack()  {<br> fmt.Println(&quot; with upgraded attack&quot;)<br>}<br><br>func ChangedCareerAttack() {<br> fmt.Println(&quot; with special attack&quot;)<br>}<br><br>func main() {<br> hero := Hero{AttackFunc: make([]AttackFunc, 0)}<br> hero.AttackFunc = append(hero.AttackFunc, AttackFunc(UpgradedAttack))<br> hero.AttackFunc = append(hero.AttackFunc, AttackFunc(ChangedCareerAttack))<br> hero.Attack()<br>}</pre><p>3. Using struct + function type</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>type Hero struct {<br> AttackFunc []AttackFunc<br>}<br><br>type AttackFunc func()<br><br>func (h *Hero) Attack() {<br> fmt.Println(&quot;start attack&quot;)<br><br> for i := 0; i &lt; len(h.AttackFunc); i++ {<br>  h.AttackFunc[i]()<br> }<br>}<br><br>func UpgradedAttack()  {<br> fmt.Println(&quot; with upgraded attack&quot;)<br>}<br><br>func ChangedCareerAttack() {<br> fmt.Println(&quot; with special attack&quot;)<br>}<br><br>func main() {<br> hero := Hero{AttackFunc: make([]AttackFunc, 0)}<br> hero.AttackFunc = append(hero.AttackFunc, AttackFunc(UpgradedAttack))<br> hero.AttackFunc = append(hero.AttackFunc, AttackFunc(ChangedCareerAttack))<br> hero.Attack()<br>}</pre><p>As you can see, there are many methods can implement Decorator Pattern. Maybe you’re curious that how to pick the right one. My personal opinion is to take a look on main function which means focus on how to use your classes. Choose the most readable one according to your use case. For example, if in your use case, upgraded hero is still a hero. Than maybe the first struct + interface one suites you. On the other hand, if you want to focus more on function, than maybe second and third one would be your choice.</p><p>Decorator pattern is a powerful pattern. However, it will complex your code. Hence, gave it a second thought before you use it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e634a87dfbff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Pattern — Observer]]></title>
            <link>https://medium.com/@eason91367/design-pattern-observer-4a90cde0ab7d?source=rss-51c343ff6947------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a90cde0ab7d</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Eason]]></dc:creator>
            <pubDate>Mon, 08 Jul 2024 14:39:24 GMT</pubDate>
            <atom:updated>2024-07-08T14:39:24.711Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design Pattern — Observer</h3><p>Have you ever bumped into a circumstance that lots of objects want to get the update of one specific data? Let’s say, you need to create a weather station. To predict the weather you need to keep observing the changes of temperature, humidity and air pressure. After you got the updates you have to change all the monitors or apps’ status.</p><p>If you include all the apps and monitors inside one weather station object, you will found that every time there’s a new monitor or app appears, you need to change station’s code. This obviously against the Open Close Principle which will make it really hard to maintain.</p><p>Observer pattern is here to rescue this situation. The thought here is we narrow down the station’s responsibility to only need to receive the updates and notify the observers(apps and monitors). Next we separate the observers and ask them to provide a united function for station to notify them. In this case station don’t need to change anything when a new app is coming and apps can have more flexibility to display the updates.</p><p>This is the overall graph of Observer pattern:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*UPgAgK2SSISArrtX9vYfxw.png" /></figure><p>There are lots of tools/techs using this pattern, such as webhook, event queue, etc…. If you take a close look, you’ll found they have some common places. They all have lots of observers wants to deal with the data, and they all don’t know when will the updated data come. So next time, if you bumped into same situation, don’t forget this graph. This might save your life.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a90cde0ab7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How and when to use design pattern — Strategy Pattern]]></title>
            <link>https://medium.com/@eason91367/how-and-when-to-use-design-pattern-strategy-pattern-4860b86ba188?source=rss-51c343ff6947------2</link>
            <guid isPermaLink="false">https://medium.com/p/4860b86ba188</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[design-pattern-in-golang]]></category>
            <dc:creator><![CDATA[Eason]]></dc:creator>
            <pubDate>Mon, 01 Jul 2024 15:36:16 GMT</pubDate>
            <atom:updated>2024-07-01T15:39:13.182Z</atom:updated>
            <content:encoded><![CDATA[<h3>How and when to use design pattern — Strategy Pattern</h3><p>If you’re a software engineer with several years experience, maybe you’ve heard of “Design Pattern”. However, it’s not that common to heard people discuss with design pattern when talking about software development which, by the way, I personal think is not a bad thing, since I think as long as every members in your team can understand the design, than it is a good design.</p><p>So what is design pattern? Overall, it is experience of prior engineers. They found a good way to solve and describe the questions and organized their thoughts to become patterns. So is to say, read more patterns more experience you gained. When you bumped into similar scenarios, maybe you would come up with the idea base on the patterns you’ve read.</p><p>How about when to use the pattern? When you’re struggling fixing the bug and found the system is not flexible, then it’s time to use pattern to refactor the system.</p><p>For example, you have a duck system that can derive lots kind of ducks. In the simplest case, you can only have a duck class and says all the duck will have the wings, two feet and can fly. However, there sometimes exist greedy users. For example, they tried to put toy duck into your system which would make the behavior flying very awkward.</p><p>At this time, if you’ve read the strategy pattern, you’ll know how to fix this. In strategy pattern, it says separates the changing part and use interface to delay the implementation which by the way is a good principle to follow: “<strong>has a</strong> is better than <strong>is a</strong>”. Hence you separate the fly part and make a fly interface which contain fly method. Next, put this interface into your duck class which will force every derived ducks choose the behavior of flying. By this way, you can have a can’t fly class for toy duck and finally fix the problem.</p><p>To wrap up, I think it’s not necessary to always using design pattern. <strong>Only use it when it can help your code clean and readable</strong>. This means don’t over design it. It’s good to prepare yourself but don’t use it when it’s not necessary.</p><p>Last but not the least, design patterns use lots of <strong>metaphor</strong> like factory, TV controller and adaptor. This phenomenon not only appears in design pattern but appears everywhere in software design, cause experience comes from life. Practice using metaphor, you’ll found it makes your designing life lots more easier.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4860b86ba188" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The most important principle of developing software]]></title>
            <link>https://medium.com/@eason91367/the-most-important-principle-of-developing-software-a6dc995426df?source=rss-51c343ff6947------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6dc995426df</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Eason]]></dc:creator>
            <pubDate>Tue, 25 Jun 2024 10:14:47 GMT</pubDate>
            <atom:updated>2024-06-25T10:14:47.146Z</atom:updated>
            <content:encoded><![CDATA[<p>There are so many principles out there when it comes to software develop. For example: KISS principle, DRY principle, etc… But during all of them, I personal think there exist most important one: SOLID principle.</p><p>Just in case some readers are not that familiar to SOLID which I think should be a lot. Let me post the defininition here:</p><ul><li><strong>Single Responsibility Principle (SRP)</strong>: Ensuring that each class or module has only one reason to change promotes maintainability and reduces the risk of unintended side effects when modifications are made.</li><li><strong>Open/Closed Principle (OCP)</strong>: By designing software entities to be open for extension but closed for modification, we enhance the system’s ability to accommodate new features and changes without altering existing code, thus minimizing the risk of introducing bugs.</li><li><strong>Liskov Substitution Principle (LSP)</strong>: Upholding this principle ensures that subclasses can be substituted for their base classes without affecting the correctness of the program. This fosters code reuse and promotes a consistent behavior across different parts of the system.</li><li><strong>Interface Segregation Principle (ISP)</strong>: By segregating interfaces based on clients’ specific needs, we prevent clients from depending on interfaces they don’t use. This leads to cleaner, more maintainable code and avoids unnecessary coupling between components.</li><li><strong>Dependency Inversion Principle (DIP)</strong>: Inverting dependencies by depending on abstractions rather than concrete implementations allows for greater flexibility, decoupling higher-level modules from lower-level ones. This enables easier testing, maintenance, and adaptability to changes.</li></ul><p>If you take a close read to the definition, you would find that it’s all about classes which I don’t think it is the only usage. For example, you can replace the word “class” to any unit in software. Such as “function”, “container”, “service”. After you doing this you will found it works perfectly and you finally have a guideline designing the system.</p><p>SOLID doesn’t have a standard metric. So is to say, it is very subjective. Especially when we’re talked about single responsibility. This responsibility can be huge or narrow. As for me, in the very beginning I will narrow it down for the flexibility. As time goes by, the requirements are stable, I will refactor all the modules, services, functions to have wider responsibility.</p><p>To wrap up, SOLID is a very useful mind set for you to think of system design. When you are curious whether you have a good design or not, take a look to SOLID and maybe you can have your judgment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6dc995426df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to prevent out of port in Docker swarm]]></title>
            <link>https://medium.com/@eason91367/how-to-prevent-out-of-port-in-docker-swarm-474d3444878d?source=rss-51c343ff6947------2</link>
            <guid isPermaLink="false">https://medium.com/p/474d3444878d</guid>
            <category><![CDATA[site-reliability-engineer]]></category>
            <category><![CDATA[docker-swarm]]></category>
            <dc:creator><![CDATA[Eason]]></dc:creator>
            <pubDate>Wed, 12 Jul 2023 05:29:48 GMT</pubDate>
            <atom:updated>2023-07-12T05:29:48.744Z</atom:updated>
            <content:encoded><![CDATA[<p>When it comes to deploy a web application, a common issue comes up: choose a port to export. If this is the only application you have and you are using single server, then this won’t be a problem. But what if you have thousands or even millions of applications? The solution of port management become important aggressively.</p><p>Before I start to illustrate my solution of docker swarm, I have to talk about one of the trait of docker container first. All of resources in each of docker container are totally independent. That means as long as application is in different container, it is totally fine to use same port. However eventually we have to expose out application to outside world. So here comes my thought: Open only one gate, and that gate is response to connect all the applications(containers) inside the gate according to the path. By this method we only to expose one single port, is incredible, isn’t it? But there’s one problem to achieve this goal: How this gate connect to other containers in it?</p><p>Docker swarm encapsulate container with several layer. From Top to bottom they are Stack, Service, Task and Container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*_GBZMcyoxBKQyIKdVS2C7w.png" /><figcaption>Docker Swarm Layer</figcaption></figure><p>As you can see, containers are inside services, and all containers inside one service use same image. Hence service is the one who control replicas. Service can connect to another service by using service name and docker network name(another topic and won’t illustrate here), furthermore, if they are both in the same network, network name can be omitted.</p><p>By leveraging this feature, which by the way is called service discover, I can fulfill my goal. First, I will create a proxy service and expose its port which is the only port I expose. Then whenever I create a new application service, I will register a path to that proxy and proxy will connect to application by its service name. After doing all these thing, outside world can finally call the application service through proxy, and we don’t need to care about what port can use and just use the exactly same port. Below is the diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*aSCdwCKZUAPpa1U27GEoOg.png" /></figure><p>Docker swarm or K8s is a huge topic, and is impossible to use just one article to let everybody know the whole concept. This article is just one of its usage. If there’s somewhere I’m not clear, feel free to leave comment to me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=474d3444878d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The explanation of 2 Phase Commit, Saga, TC/C]]></title>
            <link>https://medium.com/@eason91367/the-explanation-of-2-phase-commit-saga-tc-c-794dcca4d4f2?source=rss-51c343ff6947------2</link>
            <guid isPermaLink="false">https://medium.com/p/794dcca4d4f2</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Eason]]></dc:creator>
            <pubDate>Thu, 06 Jul 2023 05:33:24 GMT</pubDate>
            <atom:updated>2023-07-06T05:33:24.660Z</atom:updated>
            <content:encoded><![CDATA[<p>In response to the trend of big data, it’s hard to keep all the data in one database server. Hence, it came up with “Partition”. The concept of partition is we split data by their own key. For example, there are two rows of data: “16, Tom, Engineer”, “17, Maria, Teacher”, first field is age, second field is name, and the last one is career. If we decide use age to be the key for partition, then they might be put in the different server.</p><p>During developing a system, there is a feature we need all the time, and it is “transaction”. It means you want all operations in the currently function to be atomic. There’s a fine solution for database technique, but when it comes to distributed system, things got complicated. There are several solutions that has already came up and the main purpose of this article is to introduce them, so here we go!</p><h3>2 Phase Commit</h3><p>2 Phase Commit is a kind of algorithm that work between multiple database server. Let me post the picture I found on internet first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*ao9Rh8ulzPX6kwqPCFpdyQ.png" /></figure><p>In this algorithm, there is a special role: coordinator. This role is responsible for collect and notify results to every partition of databases. When coordinator receive a transaction request, it will notify all the partitions(workers) which is related to prepare and if they finish preparing they will send back a ready signal so that coordinator can collect all of the signals. In prepare phase, what partitions do is to write the operation into their logs. They will send back ready signal only when the logs are written successfully.</p><p>After collecting all the ready signal, coordinator will send a commit or rollback signal to every partitions based on how many readies he collected. In this phase, there’s no fallback. It means if one of node didn’t send back ack signal, it will be regarded as unreachable, and cannot access by client any more. Usually coordinator will retry multiple times until it get ack signal. This is the general flow of 2 phase commit.</p><p>Maybe you have discovered that the most important problem of this algorithm is how to keep coordinator alive. This is another topic of distributed system, and I will talk about it in the other article.</p><h3>Saga</h3><p>2 Phase commit is implemented in database layer, so if you want to use the transaction, you need to use a single connection to do it. It means these operation can only be in one system. Now a days, micro-service is more and more popular, and 2 phase commit may not work in this kind of system. Hence a method named Saga came up. The whole concept of Saga is we handle the transaction ourselves in the application layer. Since we have to handle both commit and rollback, if we had n operation, we have to deal with 2n kinds situation. In Saga, all the operation will be operated sequentially, so it might not so efficiency. So there’s another alternative: TC/C.</p><h3>TC/C</h3><p>The full name of TC/C is Try-confirm/Cancel. This algorithm will do all the operation in the same time. If one of operation fail, all the operation have to rollback. This Method is also implemented in application layer. Although the efficiency is better than Saga, but the challenge is to know which operation is fail, and rollback the others except this one.</p><h3>Conclusion</h3><p>All algorithm has its pros and cons. There is no best solution only best suitable solution. Keep learning so that you can make a better choice.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=794dcca4d4f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>