<?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 Eddie Cho on Medium]]></title>
        <description><![CDATA[Stories by Eddie Cho on Medium]]></description>
        <link>https://medium.com/@chochoforwork?source=rss-2201682f1f94------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Eh7TJO39Zq5WwPD3TktIeQ.jpeg</url>
            <title>Stories by Eddie Cho on Medium</title>
            <link>https://medium.com/@chochoforwork?source=rss-2201682f1f94------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 14:04:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chochoforwork/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[Understanding Hibernate’s Application-Level Repeatable Reads]]></title>
            <link>https://medium.com/@chochoforwork/understanding-hibernates-application-level-repeatable-reads-8deeaba7255b?source=rss-2201682f1f94------2</link>
            <guid isPermaLink="false">https://medium.com/p/8deeaba7255b</guid>
            <category><![CDATA[repeatable-read]]></category>
            <category><![CDATA[isolation-level]]></category>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Eddie Cho]]></dc:creator>
            <pubDate>Fri, 02 May 2025 10:10:47 GMT</pubDate>
            <atom:updated>2025-05-12T12:37:50.725Z</atom:updated>
            <content:encoded><![CDATA[<p>When invoking methods like `entityManger.find`, and `CrudRepository.findById`, or querying by natural ID, Hibernate first checks the first-level cache (a.k.a Session or persistence context). If the requested entity is already present in the cache, Hibernate will not execute an SQL query, it will return the cached entity instead.</p><p>When querying using methods other than `entityManager.find`, `CrudRepository.findById`, or queries by natural ID.<br>Regardless of whether the first-level cache already contains the entity or not, Hibernate will always execute the SQL statement. After executing the query, Hibernate constructs an `EntityKey` from the result. It then uses this key to check the persistence context. If the entity is already present, Hibernate will discard the query result and return the cached entity instead. This is how Hibernate provides application-level repeatable reads.</p><p>If you’re interested in discovering more implementation details of Hibernate’s application-level repeatable reads, here’s <a href="https://hackmd.io/@GzkKWjbLTt6YExzxvjL9OA/SJ6avxhkxx">an article</a> for you.</p><p><strong>REPEATABLE_READ Isolation Level vs. Hibernate’s Application-Level Repeatable Reads</strong><br>1. The REPEATABLE_READ Isolation level prevents not only non-repeatable reads but also dirty reads. In modern databases like PostgreSQL, it can also prevent phantom reads. On the other hand, if application-level repeatable reads is used with the READ_UNCOMMITTED isolation level, dirty reads might still occur because the underlying database allows them. Additionally, application-level repeatable reads cannot prevent phantom reads by itself.</p><p>2. The REPEATABLE_READ Isolation level ensures that all reads in a transaction see data from the same snapshot. <br>In contrast, application-level repeatable reads only guarantees that an entity read multiple times within the same Hibernate session will return the same in-memory object (from the first-level cache). When used with the READ_UNCOMMITTED or READ_COMMITTED isolation level, this can lead to unexpected results if a transaction reads some parts of the data directly from the database (potentially showing updates from other transactions), while other parts are served from Hibernate’s session cache. (see <a href="https://stackoverflow.com/questions/25106636/strategies-for-dealing-with-concurrency-issues-caused-by-stale-domain-objects-g">this example</a>) The cache is not aware of changes committed by other transactions unless the entities are explicitly refreshed.</p><p>This <a href="https://github.com/EddieChoCho/isolation-level-demo">Github repository</a> conatins showcases of Hibernate’s application-level repeatable reads</p><p><strong>References</strong><br>1. <a href="https://github.com/hibernate/hibernate-orm">Hibernate-ORM Github Repository</a><br>2. <a href="https://docs.jboss.org/hibernate/stable/orm/userguide/html_single/Hibernate_User_Guide.html">Hibernate User Guide</a><br>3. <a href="https://vladmihalcea.com/jpa-hibernate-first-level-cache/">The JPA and Hibernate first-level cache</a><br>4. <a href="https://vladmihalcea.com/hibernate-application-level-repeatable-reads/#:~:text=A%20Hibernate%20persistence%20context%20can,have%20application%2Dlevel%20repeatable%20reads">How does Hibernate guarantee application-level repeatable reads</a><br>5. <a href="https://dataintensive.net/">Designing Data-Intensive Applications</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8deeaba7255b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Does Spring Distributed Lock Work? Exploring Source Code of RedisLockRegistry and RedisSpinLock]]></title>
            <link>https://medium.com/@chochoforwork/introduction-to-spring-distributed-lock-with-redis-exploring-redislockregistry-and-redisspinlock-7ca57f23a4db?source=rss-2201682f1f94------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ca57f23a4db</guid>
            <category><![CDATA[distributed-locks]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-distributed-lock]]></category>
            <category><![CDATA[spring-integration]]></category>
            <dc:creator><![CDATA[Eddie Cho]]></dc:creator>
            <pubDate>Sun, 20 Aug 2023 09:30:49 GMT</pubDate>
            <atom:updated>2024-03-29T19:53:40.491Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we embark on a journey to unravel the intricate mechanisms of Spring Distributed Lock using Redis.</p><p>With a keen focus on source code analysis, this article unveils essential insights into the architecture of <strong>RedisLockRegistry</strong>. It sheds light on crucial design considerations that drive the creation of a distributed lock solution within a single Redis node environment.</p><p>If you’re new to the concept of Spring Distributed Lock, consider exploring this informative article: <a href="https://tanzu.vmware.com/developer/guides/spring-integration-lock/">How To Implement a Spring Distributed Lock</a>, or watch this video: <a href="https://youtu.be/firwCHbC7-c">Spring Tips: Distributed Locks with Spring Integration</a>, to familiarize yourself before delving into the content presented here.</p><p>The Spring Integration project offers a range of distributed lock options. we will delve into the implementation using Redis, specifically through <strong>RedisLockRegistry.java</strong>.</p><p><strong>RedisLock</strong> is an abstract inner class of <strong>RedisLockRegistry</strong> class, the instance of <strong>RedisLock</strong> will be used to manage concurrent access by insert, update, or delete data, the status of the lock, in Redis service. <strong>RedisSpinLock</strong> and <strong>RedisPubSubLock</strong> are the classes that inherit from the <strong>RedisLock</strong> abstract class. Our focus in this article will be on the former, <strong>RedisSpinLock</strong>.</p><p>In this section, we will explore the source code of <a href="https://github.com/spring-projects/spring-integration/blob/6.1.x/spring-integration-redis/src/main/java/org/springframework/integration/redis/util/RedisLockRegistry.java"><strong>RedisLockRegistry.java </strong>(version 6.1.x )</a> in detail, dissecting its components to comprehend the underlying mechanism of this distributed lock.</p><p><strong>The Construction of RedisLockRegistry Bean</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7590a8bde74844a63f44e34ae8ac6fbd/href">https://medium.com/media/7590a8bde74844a63f44e34ae8ac6fbd/href</a></iframe><p>When creating a <strong>RedisLockRegistry</strong> instance, you need to provide three parameters: `connectionFactory`, `registryKey`, and `expireAfter`.</p><p>The `connectionFactory` parameter is used to generate the redisTemplate instance field within the <strong>RedisLockRegistry</strong>. This redisTemplate facilitates interaction with Redis using string values.</p><p>The `registryKey` parameter serves as a prefix for key names. These key names are formed by combining the `registryKey` and the key’s specific value, separated by a colon. For example, if `registryKey` is set to “Spring” and you intend to lock a key with the value “Integration”, the actual key used to communicate with Redis would be “Spring:Integration”.</p><p>The `expireAfter` parameter, of type long, determines the Time To Live (TTL) for the lock status data inserted into Redis by RedisLock instances.</p><p>An important point to note is the `clientId` instance field. This is a UUID string generated during the creation of a <strong>RedisLockRegistry</strong> object. It represents the process’s identity and is used as the value associated with each key. Which will be used to veirfy the ownership of the distributed lock.</p><p><strong>Obtaining a Lock from RedisLockRegistry</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b43ee97102e132f1833acc1178c6f47/href">https://medium.com/media/0b43ee97102e132f1833acc1178c6f47/href</a></iframe><p>To initiate the acquisition of a distributed lock, the initial step is to obtain a <strong>RedisLock</strong> object from the <strong>RedisLockRegistry</strong>. This process can be accomplished by invoking the `obtain` method on a <strong>RedisLockRegistry</strong> instance, passing in a string key.</p><p>In the source code of the `obtain` method, the <strong>ReentrantLock</strong> instance field of <strong>RedisLockRegistry</strong> — `lock` is pivotal in ensuring the orderly acquisition of a <strong>RedisLock</strong>. Its purpose is to restrict only one thread at a time from attempting to acquire a <strong>RedisLock</strong>. Should no <strong>RedisLock</strong> object be associated with the provided key in the `locks` map, a new <strong>RedisLock</strong> is created with the key and returned. The value of the key will be composed with the `registryKey` and assigned to the String instance variable `lockKey` of RedisLock. By default, this newly created <strong>RedisLock</strong> is an instance of <strong>RedisSpinLock</strong>. On the other hand, if a <strong>RedisLock</strong> object already exists for the key, that existing instance will be returned.</p><p>Furthermore, the `lock` instance field also manages concurrent access to the `locks` map in the `expireUnusedOlderThan` method. Consequently, there is no need to be concerned about potential race conditions between these two methods.</p><p><strong>Acquiring a Distributed Lock Through Invoking `tryLock` Method of RedisLock</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/466e39b1d1e0a4a513cd5bbc80e24828/href">https://medium.com/media/466e39b1d1e0a4a513cd5bbc80e24828/href</a></iframe><p>Once the <strong>RedisLock</strong> instance is obtained, we can proceed to invoke the `tryLock` method. This call attempts to acquire the distributed lock from Redis. It’s noteworthy that <strong>RedisLock</strong> is equipped with its own <strong>ReentrantLock</strong> instance, referred to as `localLock`. This local lock ensures the thread safety of using the RedisLock.</p><p>At the outset of the `tryLock` method, the `localLock` serves to ensure that only one thread can execute lock-related methods of the same <strong>RedisLock</strong> instance simultaneously.</p><p>Subsequently, the `tryRedisLock` method is executed to make an attempt at acquiring the lock from Redis, with a defined waiting time. If the lock is successfully acquired, the `localLock` is unlocked and true is returned. Conversely, if the acquisition fails or any exceptions occur during the process, the `localLock` is still unlocked to prevent potential deadlocks, and false is returned to signal the unsuccessful acquisition to the caller.</p><p>The `tryRedisLock` method internally invokes the `tryRedisLockInner` method, an abstract method with distinct implementations in <strong>RedisSpinLock</strong> and <strong>RedisPubSubLock</strong>. For an in-depth exploration of this process, we’ll now delve into the implementation within <strong>RedisSpinLock</strong> to understand the specific actions undertaken.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a71e07da8a1aa73d680f81be2da09974/href">https://medium.com/media/a71e07da8a1aa73d680f81be2da09974/href</a></iframe><p>The `tryRedisLockInner` method diligently attempts to invoke the `obtainLock` method every 100 milliseconds, which handles the communication task with Redis.</p><p>When `time` is set to -1, indicating that the waiting time hasn’t been specified, the `tryRedisLockInner` method perseveres until the `obtainLock` method returns true.</p><p>Alternatively, when a waiting time is specified, the method continuously checks if the waiting time has been exceeded. In either case, the method returns the acquisition result, whether successful or unsuccessful.</p><p>In the pursuit of reliability, the `tryRedisLockInner` method showcases a robust structure that supports both indefinite and time-bound lock acquisition scenarios.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1414bfc40e31d3eae01baad1ad7cb02b/href">https://medium.com/media/1414bfc40e31d3eae01baad1ad7cb02b/href</a></iframe><p>The `obtainLock` method carries out a Lua script, <strong>OBTAIN_LOCK_SCRIPT</strong>, utilizing the `EVALSHA` command. This script involves three components: the `lockKey`, which was assigned a value during the instantiation of <strong>RedisLock</strong>; `clientId`, and `expireAfter`, both derived from the constructor of <strong>RedisLockRegistry</strong>.</p><p>Upon execution of the Lua script, the following operations occur within Redis:</p><ol><li>Check if a value exists for `lockKey` using the `GET` operation.</li><li>If there’s no existing value, implying the distributed lock for this key hasn’t been acquired by any process, execute a `SET` operation. This inserts data into Redis with the key, value (clientId), and a TTL specified by `expireAfter`. The TTL will function as a safeguard against potential deadlocks.</li><li>If the value retrieved from the `GET` operation matches `clientId`, it indicates the current process has previously acquired the distributed lock for this key and it’s still locked. In this case, execute a `PEXPIRE` operation to update the lock’s timeout using the `expireAfter` value.</li><li>If the value from the `GET` operation differs from `clientId`, indicating the distributed lock is currently held by another process, the script returns false to signify an unsuccessful acquisition.</li></ol><p>It’s important to note that although the script may execute multiple commands, Redis guarantees atomic execution of scripts and functions, eliminating concerns about concurrency issues.</p><p>The method showcases a well-structured script execution process within Redis, ensuring the proper acquisition and management of distributed locks.</p><p><strong>Releasing a Distributed Lock by Invoking the `unlock` Method of RedisLock</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69c93e295a4c2fd6a092cc356667f9c3/href">https://medium.com/media/69c93e295a4c2fd6a092cc356667f9c3/href</a></iframe><p>Upon successfully acquiring the distributed lock and completing execution within the critical section, it’s imperative to release the lock. This is achieved by invoking the unlock method on the <strong>RedisLock</strong> object.</p><p>Within the execution of the `unlock` method, `isHeldByCurrentThread` of the `localLock` is invoked to verify if the RedisLock is locked by the current thread. If another thread holds the lock, the current thread must not proceed with unlocking. Consequently, an <strong>IllegalStateException</strong> is raised.</p><p>Given that the `localLock` is an instance of <strong>ReentrantLock</strong>, it’s feasible for a thread to hold the lock through multiple locking actions that aren’t necessarily matched by an equal number of unlocking actions. To account for this, the hold count of the thread is examined:</p><ol><li>If the hold count surpasses one, signifying that additional unlock actions must be executed before releasing the distributed lock, the `unlock` method of `localLock` is invoked, and the method’s execution concludes.</li><li>Conversely, if the hold count equals one, denoting that the distributed lock can be released, the `removeLockKey` method is called within a try block. This method is responsible for erasing the lock’s status — previously inserted into Redis by the `obtainLock` method of <strong>RedisLock</strong>. The final invocation of `localLock.unlock` within the current lifecycle of distributed lock utilization takes place within the finally block. This ensures that regardless of exceptions or flow control, the lock is reliably released.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b49d1474f70ff743405f414dedb55cb/href">https://medium.com/media/8b49d1474f70ff743405f414dedb55cb/href</a></iframe><p>During the execution of the `removeLockKey` method, the `unlinkAvailable` flag serves as a determinant for choosing between invoking `removeLockKeyInnerUnlink` or `removeLockKeyInnerDelete` methods to eliminate the lock’s status.</p><p>By default, the value of `unlinkAvailable` is set to true, which triggers the execution of the `removeLockKeyInnerUnlink` method. If an exception occurs during the execution of `removeLockKeyInnerUnlink`, it indicates that the Redis service does not support the `UNLINK` operation. Consequently, the `unlinkAvailable` flag is switched to false, subsequently leading to the execution of the `removeLockKeyInnerDelete` method. This method employs the `DEL` command to perform the deletion of the lock’s status from Redis.</p><p>When the `removeLockKeyInnerUnlink` method returns a true value, it confirms the successful release of the distributed lock. Conversely, a false value indicates that the lock has either expired or is held by another process, prompting the generation of an <strong>IllegalStateException</strong>.</p><p>The `removeLockKey` method exemplifies an essential aspect of the distributed lock’s lifecycle — safely releasing the lock’s hold on shared resources while accounting for potential exceptions and variations in Redis service capabilities.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c472f378d53fd41ccdaeedefd20126b5/href">https://medium.com/media/c472f378d53fd41ccdaeedefd20126b5/href</a></iframe><p>The `removeLockKeyInnerUnlink` method carries out a Lua script named <strong>UNLINK_UNLOCK_SCRIPT</strong> by utilizing the `EVALSHA` command. This script involves two components: the `lockKey` and `clientId`.</p><p>Upon executing the Lua script, the following Redis operations transpire:</p><ol><li>A` GET` operation checks if a value exists for the `lockKey`.</li><li>If the retrieved value matches the `clientId`, signifying that the current process holds the distributed lock, a `UNLINK` operation is executed. This operation removes the lock’s status.</li><li>If the value from the `GET` operation differs from the `clientId`, indicating that the distributed lock is currently held by another process, the script returns false, indicating an unsuccessful release.</li><li>When there’s no existing value for the `lockKey`, indicating the distributed lock has expired, the script also returns false to indicate an unsuccessful release.</li></ol><p>The `removeLockKeyInnerDelete` method features a nearly identical implementation to `removeLockKeyInnerUnlink`. The sole distinction lies in the script executed by `removeLockKeyInnerDelete`, which employs the `DEL` command as opposed to the `UNLINK` command.</p><h3><strong>Summary</strong></h3><p>Central to this solution desgin of <strong>RedisLockRegistry</strong> is the utilization of the lock construct, specifically the <strong>ReentrantLock</strong>. This essential component ensures the thread-safe characteristic of the distributed lock within a single process. By encapsulating critical sections of code with these locks, we guarantee that only one thread gains access at a time, mitigating potential conflicts that arise from concurrent execution.</p><p>However, the scope of distributed locks extends beyond the boundaries of a single process. The solution integrates the concept of atomic execution. By orchestrating operations such as lock acquisition and release with atomic execution, the solution prevents concurrency issues across processes.</p><p><strong>References</strong></p><ul><li>[<a href="https://github.com/spring-projects/spring-integration">Spring Integration</a>]</li><li>[<a href="https://github.com/spring-projects/spring-integration/blob/6.1.x/spring-integration-redis/src/main/java/org/springframework/integration/redis/util/RedisLockRegistry.java">RedisLockRegistry.java(6.1.x version)</a>]</li><li>[<a href="https://tanzu.vmware.com/developer/guides/spring-integration-lock/">How To Implement a Spring Distributed Lock</a>]</li><li>[<a href="https://redis.io/docs/manual/patterns/distributed-locks/">Distributed Locks with Redis</a>]</li><li>[<a href="https://redis.io/docs/interact/programmability/">Redis programmability</a>]</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ca57f23a4db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Clean Code Talks — Inheritance, Polymorphism, & Testing重點整理]]></title>
            <link>https://medium.com/@chochoforwork/the-clean-code-talks-inheritance-polymorphism-testing%E9%87%8D%E9%BB%9E%E6%95%B4%E7%90%86-dccfa8e4ea9c?source=rss-2201682f1f94------2</link>
            <guid isPermaLink="false">https://medium.com/p/dccfa8e4ea9c</guid>
            <category><![CDATA[twjug-lite]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[twjug]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Eddie Cho]]></dc:creator>
            <pubDate>Sat, 14 Mar 2020 13:56:17 GMT</pubDate>
            <atom:updated>2020-03-15T02:37:51.326Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>The Clean Code Talks — Inheritance, Polymorphism, &amp; Testing 重點整理</strong></h3><p>兩年多前我接觸到Misko Hevery的一系列Clean Code演講，這些演講幫助我建立了一些良好的程式撰寫原則，對於後續開發與維護專案上給予了很大的幫助，因此想摘錄一些重點與大家分享。</p><p><a href="https://youtu.be/4F72VULWFvc">影片連結</a></p><p><strong>藉由多型來取代條件式(但要避免過多層的繼承)</strong></p><p>在實務上我們儘可能避免條件式(if..else, switch)出現在函式中。函示中出現越多條件式，在閱讀程式碼的過程需要記住的案例就越多，我們也需要為這些案例分別撰寫測試。因此沒有條件式的函示是比較好閱讀與測試的。</p><p>事實上大部分的條件式都可以被多型所取代。當你發現特定的物件會因為不同的狀態而有不同的行為(State Based Behavior)，或是相同的條件式出現在多處(Same condition in multiple places)，這兩個情境都透露出了一個訊息 — 你該使用多型了！</p><p><strong>1. State Based Behavior</strong></p><p>假設你的程式碼中包含條件式來依照物件的種類選擇不同的行為（例如依照物件中的一個屬性的狀態來執行不同的行為）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fLS794odtWyB7i2C" /></figure><p>這樣的程式碼就很適合使用多型來取代條件式。</p><p>我們可以讓父類別負責一般情境的邏輯，而將條件是內各個案例交由不同子類別覆寫（Override）的方法負責。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KeB8arDzvOx09chf" /></figure><p>在更複雜的情境中，我們也可以先整理出所有的案例再決定該設計出多少種子類別，也可以藉由這樣個設計來避免撰寫出需要檢查null的程式碼（請參考另一個<a href="https://youtu.be/4F72VULWFvc?t=459">練習</a>）。</p><p>但是在使用多型時也需要注意避免過多層級的繼承，在<a href="https://youtu.be/wEhu57pih5w?t=222">[The Clean Code Talks — Unit Testing 3:24]</a>的演講中有提到，過多層級的繼承會讓程式難以理解且不易於測試。</p><p>要能成功避免過多條件式的另一個前提是不撰寫任何會回傳null的函式，在<a href="https://youtu.be/RlfLCWKxHJ0?t=1434">[The Clean Code Talks — Don’t Look For Things 23:54]</a>的演講中有提過：「null是測試的好朋友，但是是產品(production code)的敵人」。因為在測試中，我們可以藉由判斷傳入的參數是否為null，來了解哪些參數在哪些測試案例中扮演重要的角色。</p><p>當然在一些案例中，null在商業邏輯上具有特殊的意義，而在Java在8版之後也提供Optional類別，讓我們可以用更好的方式為這些案例撰寫程式。</p><p>在這邊做個小總結，多型的設計大部分會比使用條件式更好，因為:</p><ul><li>易於擴充：透過增加子類別，新的案例可以很解單的被加入。</li><li>易於維護：每個案例被歸類在不同的類別中，讓我們可以更好的理解與測試各個案例。</li><li>大部分的switch表達式可以被多型取代</li></ul><p><strong>2. Same condition in multiple places</strong></p><p>當你設計的物件有多個方法，會依照向同的條件式來決定其行為，而你每新增一個方法，都需要在方法內加入相同的條件式時，我們就該使用多型了！</p><p>這樣的程式碼會為測試帶來困難，因為我們很難透過單純閱讀程式碼來判斷測試需要覆蓋的條件式排列組合，進而導致我們可能撰寫了一些不會再實務上發生的測試案例，以下圖為例，我們無法判斷Update物件是否會有execute()執行A邏輯，但是在render()執行B邏輯的情境。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AzRs7xQ0_bTuacOp" /></figure><p>若使用多型我們的程式將更容易維護。由於每個子類別負責單一一個情境，我們能更容易理解程式，各個子類別的測試並不需要考慮到其他子類別的測試，測試案例也會更單純、更容易理解。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4hB6vwHVEq-1gXsu" /></figure><p>使用多型，商業邏輯將由各個子類別負責，先前的條件式並不會完全消失，而是被集中在負責建構的物件中，用來決定要回傳哪個子類別。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*En7vdg6rpcGMCZtn" /></figure><p>這邊提一下在<a href="https://youtu.be/RlfLCWKxHJ0?t=1817">[The Clean Code Talks — Don’t Look For Things 30:17]</a>演講中提到的另一個設計原則：將物件分為兩類去設計，一類負責商業邏輯，另一類負責建構（物件的尋取或生成）。透過這樣的原則來設計，我們很容易分別為商業邏輯以及物件建構來撰寫測試；反之若將這兩類責任都交由一個函式去處理，測試將難以撰寫。</p><p><strong>優點總結</strong></p><ul><li>條件式被集中在一個地方</li><li>避免重複的程式碼/條件式</li><li>分開不同的責任</li><li>不同情境會用到的相同邏輯被集中在一處</li><li>可獨立測試不同情境</li><li>使用多個子類別可讓我們很容易分辨不同情境的差異</li></ul><p>實務上我們的程式碼中可能還是會有一些條件式，但Misko Hevery鼓勵我們可以嘗試寫一個不使用任何條件式小專案，我們可以從中學到多種方式來善用多型的優點。</p><p>這邊也推薦其他學習寫撰寫良好程式碼的資源：<a href="https://medium.com/@qrtt1/twjug-lite-%E7%B7%B4%E7%BF%92%E5%AF%AB%E5%87%BA%E5%A5%BD%E6%87%82%E7%9A%84%E7%A8%8B%E5%BC%8F-6edf86102bd2">[twjug-lite] 練習寫出好懂的程式</a>、<a href="https://youtu.be/dJUVNFxrK_4">Unit Testing Best Practices with Roy Osherove</a>、以及<a href="https://www.youtube.com/playlist?list=PLx5t1p9LqYUe_3LrWrrJN5agu5Jcd-3bG">Misko Hevery的一系列Clean Code演講</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dccfa8e4ea9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>