<?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 Sameh Adel on Medium]]></title>
        <description><![CDATA[Stories by Sameh Adel on Medium]]></description>
        <link>https://medium.com/@samehadel?source=rss-81f91041e452------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QnvPKkuG-kXwsA6xLYywHQ.jpeg</url>
            <title>Stories by Sameh Adel on Medium</title>
            <link>https://medium.com/@samehadel?source=rss-81f91041e452------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 10:27:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@samehadel/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[Optimizing JPA Fetch Strategies: Navigating Performance Pitfalls and Memory Overheads]]></title>
            <link>https://medium.com/@samehadel/optimizing-jpa-fetch-strategies-navigating-performance-pitfalls-and-memory-overheads-efa42d2f9b5f?source=rss-81f91041e452------2</link>
            <guid isPermaLink="false">https://medium.com/p/efa42d2f9b5f</guid>
            <dc:creator><![CDATA[Sameh Adel]]></dc:creator>
            <pubDate>Thu, 25 Jul 2024 14:19:27 GMT</pubDate>
            <atom:updated>2024-07-25T14:19:27.870Z</atom:updated>
            <content:encoded><![CDATA[<p>As a developer working with Object-Relational Mapping (ORM) in Java Persistence API (JPA), you are likely familiar with the delicate balancing act between performance and memory consumption. While ORM frameworks abstract away the complexities of database interactions, they also introduce unique challenges that can significantly impact the efficiency of your application. Among these challenges is the selection of the appropriate fetch strategy. Choosing the right fetch strategy is crucial for optimizing database interactions, yet it often creates frustration and performance bottlenecks for developers. In this article, we will explore the available fetch strategies in JPA, and their implications on performance and memory usage.</p><h3>What are the JPA Fetch strategies?</h3><p>A fetch strategy in JPA defines how related entities are loaded from the database. It determines whether the related entities are loaded immediately or only when accessed. The two main fetch strategies in JPA are:</p><ol><li><strong>Eager Fetching</strong>: Loads the related entities immediately along with the main entity. This can lead to faster access times for related data but can also load unnecessary data, increasing memory usage.</li><li><strong>Lazy Fetching</strong>: Loads the related entities only when they are accessed for the first time. This can save memory and improve initial load times but may cause additional database queries, which can slow down the application if not managed properly.</li></ol><h3>Eager Loading and its problem</h3><p>The eager fetch strategy is useful when parent and child objects are often accessed together. It reduces the number of database round-trips, enhancing application performance. The following example demonstrates how the eager strategy works and the SQL generated to achieve this.</p><pre>@Entity<br>public class Author {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    private String name;<br><br>    @OneToMany(fetch = FetchType.EAGER, mappedBy = &quot;author&quot;)<br>    private List&lt;Book&gt; books;<br><br>    // Getters and setters<br>}</pre><p>The generated SQL uses a JOIN to fetch the Author’s books in a single query. This helps reduce the number of queries and round-trips needed to retrieve the required data. However, this strategy can lead to a serious problem known as the Cartesian Product.</p><h3><strong>Cartesian Product Problem</strong></h3><p>The problem with the Cartesian Product is the redundancy of data when fetching multiple collections at the same time. This redundancy leads to an excessive number of rows being returned, which can degrade performance and increase memory usage.</p><pre>@Entity<br>public class Item {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    private String name;<br><br>    @OneToMany(mappedBy = &quot;item&quot;, fetch = FetchType.EAGER)<br>    protected Set&lt;Bid&gt; bids = new HashSet&lt;&gt;();<br><br>    @ElementCollection(fetch = FetchType.EAGER)<br>    @CollectionTable(name = &quot;IMAGE&quot;)<br>    @Column(name = &quot;FILENAME&quot;)<br>    protected Set&lt;String&gt; images = new HashSet&lt;&gt;();<br><br>    // Getters and setters<br>}<br><br>@Entity<br>public class Bid {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    private Double amount;<br><br>    @ManyToOne<br>    @JoinColumn(name = &quot;item_id&quot;)<br>    private Item item;<br><br>    // Getters and setters<br>}</pre><p><strong>Executed SQL</strong></p><pre>SELECT i.id, i.name, <br>       b.id, b.amount, b.item_id,<br>       img.FILENAME<br>FROM ITEM i<br>LEFT JOIN BID b ON i.id = b.item_id<br>LEFT JOIN IMAGE img ON i.id = img.Item_id<br>WHERE i.id = ?</pre><p><strong>Result Set</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*bjyhVzSYROp4MbBNWmao7g.png" /></figure><p>As you can see, this result set contains 6 rows (2 bids × 3 images), even though we’re only fetching a single Item. This is the <strong>Cartesian Product Problem</strong> in action. The number of rows in the result set is the product of the number of related entities in each eagerly fetched collection.</p><p>This problem can lead to:</p><ol><li>Increased memory usage: The application needs to hold this larger result set in memory.</li><li>Decreased performance: More data is transferred from the database to the application.</li><li>Potential data duplication: The same data (like the item details) is repeated multiple times.</li></ol><h3>Lazy Loading and its problem</h3><p>Lazy loading is a fetch strategy where related entities or collections are not loaded from the database immediately when the main entity is fetched. Instead, they are loaded only when explicitly accessed. While this can be beneficial for performance in some cases, it can lead to the n+1 selects problem.</p><h3>n+1 selects problem</h3><p>The n+1 selects problem occurs when you fetch a list of n parent entities, and then access a lazily loaded relationship for each of these n entities, resulting in n additional queries plus the original query to fetch the parent entities — hence “n+1” queries.</p><p>Let’s illustrate this with an example:</p><pre>@Entity<br>public class Author {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    private String name;<br><br>    @OneToMany(mappedBy = &quot;author&quot;, fetch = FetchType.LAZY)<br>    private List&lt;Book&gt; books;<br><br>    // Getters and setters<br>}<br><br>@Entity<br>public class Book {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    private String title;<br><br>    @ManyToOne(fetch = FetchType.LAZY)<br>    private Author author;<br><br>    // Getters and setters<br>}</pre><p>Now, consider the following code:</p><pre>List&lt;Author&gt; authors = entityManager.createQuery(&quot;SELECT a FROM Author a&quot;, Author.class)<br>                                    .getResultList();<br><br>for (Author author : authors) {<br>    System.out.println(author.getName() + &quot; has written &quot; + author.getBooks().size() + &quot; books.&quot;);<br>}</pre><p>This code will result in the <strong>n+1 selects</strong> problem. Here’s what happens:</p><ol><li>The first query fetches all authors (1 query).</li><li>For each author, when we access author.getBooks(), a separate query is executed to fetch the books for that author (n queries, where n is the number of authors).</li></ol><p>So, if there are 10 authors, this will result in 11 database queries: 1 query to fetch all authors + 10 queries (one for each author) to fetch their books. This problem can severely impact performance, especially as the number of entities grows. It leads to:</p><ol><li>Increased database load due to multiple queries.</li><li>Higher network overhead from numerous database round-trips.</li><li>Slower application performance as each iteration of the loop waits for a database query to complete.</li></ol><h3>Solution</h3><p>@BatchSize annotation can help mitigate both the Cartesian Product Problem and the n+1 selects problem.</p><p>The @BatchSize annotation allows us to specify how many entities or collections should be fetched in a single query when initializing a lazy collection. This can significantly reduce the number of queries executed, thus improving performance.</p><p>Let’s see how we can modify our Author entity to use @BatchSizeto improve its performance:</p><pre>import org.hibernate.annotations.BatchSize;<br><br>@Entity<br>public class Author {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    private String name;<br><br>    @OneToMany(mappedBy = &quot;author&quot;, fetch = FetchType.LAZY)<br>    @BatchSize(size = 10)<br>    private List&lt;Book&gt; books;<br><br>    // Getters and setters<br>}</pre><p>Now, let’s see how this affects our previous example:</p><pre>List&lt;Author&gt; authors = entityManager.createQuery(&quot;SELECT a FROM Author a&quot;, Author.class)<br>                                    .getResultList();<br><br>for (Author author : authors) {<br>    System.out.println(author.getName() + &quot; has written &quot; + author.getBooks().size() + &quot; books.&quot;);<br>}</pre><p>With @BatchSize(size = 10), here&#39;s what happens:</p><ol><li>The first query fetches all authors (1 query).</li><li>When we access author.getBooks() for the first time, Hibernate will fetch the books for this author and the next 9 authors in a single query.</li><li>This process repeats for every 10 authors.</li></ol><p>So, if we have 100 authors, instead of executing 101 queries (1 + 100), we now execute only 11 queries (1 + 10), which is a significant reduction. This will result in a new equation: <em>number_of_queries = (n + 1) / BatchSize</em></p><p>This approach helps with both problems we discussed:</p><ol><li>It reduces the n+1 selects problem by batching multiple lazy collection initializations into a single query.</li><li>It helps avoid the Cartesian Product Problem by keeping the collections lazy but efficiently loading them when needed.</li></ol><h3>Summary</h3><p>Optimizing JPA fetch strategies is crucial for maintaining high performance in database-driven applications. We’ve explored common pitfalls like the Cartesian Product Problem and the n+1 selects issue, which can lead to excessive memory usage and unnecessary database queries. These problems often stem from the improper use of eager and lazy loading strategies.</p><p>To mitigate these issues, we’ve discussed the effective use of Hibernate’s @BatchSize annotation. This approach strikes a balance between eager and lazy loading, allowing for more efficient data retrieval by batching related entity fetches. While not a universal solution, it significantly reduces query count and improves overall application performance in many scenarios.</p><p>Remember, the key to optimizing JPA fetch strategies lies in understanding your data model, access patterns, and specific use cases. Regular profiling and testing are essential to ensure your chosen strategies truly enhance your application’s performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efa42d2f9b5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crafting Efficient and Effective hashCode Function in Java]]></title>
            <link>https://medium.com/@samehadel/crafting-efficient-and-effective-hashcode-function-in-java-860e1f2b9606?source=rss-81f91041e452------2</link>
            <guid isPermaLink="false">https://medium.com/p/860e1f2b9606</guid>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[hashcode]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sameh Adel]]></dc:creator>
            <pubDate>Sat, 15 Apr 2023 14:20:44 GMT</pubDate>
            <atom:updated>2023-04-17T02:04:56.865Z</atom:updated>
            <content:encoded><![CDATA[<h3>Crafting Efficient and Effective hashCode Method in Java</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xqHxMouuYemwD480Wi5ppg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@glenncarstenspeters?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Glenn Carstens-Peters</a> on <a href="https://unsplash.com/s/photos/blog-about-coding?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In Java, some built-in libraries depend on the object’s implemented hashcode method. For example, HashMap and HashSet depend on the value returned from this method. Ensuring the proper implementation of hashCode is a MUST, not just for these data structures to work effectively, but also to enable them to process these objects efficiently. In this article, we are going to explore the general contract of proper implementation of the hashCode, when it’s important to implement it, how to write the state-of-the-art one, and some tricks to optimize its performance.</p><h3>Relation between equals and hashCode</h3><p>When the equals() method is overridden in a class, it’s important to also provide an implementation for the hashCode() method to ensure the proper functioning of the class in collections that rely on hash codes, such as HashMap and HashSet. Remember that, It’s important to include every significant field in the computation of the hash code for a class that is involved in the equals() method. Think of them like they are a reflection of each other. For a class that iterates an array to check for equality, the implementation of the hashCode() method also needs to iterate over the same array to calculate the hash code for each element. You can check my <a href="https://medium.com/@samehadel/javas-object-equals-the-overlooked-function-that-can-make-or-break-your-code-e30b738043de">post</a> about the implementation of the equals method to ensure these two methods work reliably.</p><h3>The general contract of Object.hashCode() implementation</h3><ul><li>If the hashCode() method is called multiple times on an object during the execution of an application, it should always return the same value as long as no information used in equals() comparisons has been modified.</li><li>If two objects are equal, according to their equals(Object) method, then calling their hashCode methods should produce the same result.</li><li>It’s better for unequal objects to have distinct hash codes. In a less-than-ideal world, it’s possible for two objects that are not equal to have the same hash code.</li></ul><p>Equal objects must have equal hash codes. The violation of this rule would make a collection like HashMap behave unexpectedly. Let’s see an example of the HashMap behavior as a result of a violation of the second part of the contract. Assume the Person.hashCode() has a wrong implementation that produces different results for equal objects.</p><pre>/* Example of HashMap behaviour as result of <br>   violation of the second part of the contract */<br>Map&lt;Person, Integer&gt; map = new HashMap&lt;&gt;();<br><br>Person p1 = new Person(&quot;Name&quot;, 20);<br>Person p2 = new Person(&quot;Name&quot;, 20);<br><br>p1.equals(p2); // true<br><br>map.put(p1, 800);<br>map.get(p2); // Is null</pre><p>We can assume p1.hashCode() returns 10, and p2.hashCode() returns 100. Calling map.put(p1, 800) inserts <strong>p1</strong> into a bucket corresponding to its hash code, which is 10. On the other hand calling map.get(p2) tries to find <strong>p2</strong> in a bucket that corresponds to its hash code, which is 100. Clearly, it will return null because it doesn&#39;t exist there. This is what will happen when violating the second part of the contract. When equal objects, based on the implementation of the equals method, have different hash codes, any collection or client code that rely on this hash value will behave in a wrong way.</p><p>When writing the hashCode function, we aim to fulfill two fundamental requirements. First, objects that are considered equal must produce the same hash code. Also, a good hash function tends to produce distinct results for different objects. Second, the hash function is better to generate hash codes that are evenly distributed among a finite range of values. Doing so reduces the number of collisions during the insertion into hash-based data structures. If all objects have the same hash, this means a data structure like HashMap will behave like a LinkedList, because it handles collisions using a concept called <strong>Separate Chaining</strong>. In the real world, collision prevention is almost impossible, but we could achieve better results with the good implementation of the hashCode method.</p><h3>How to reach a fair approximate for no collisions solution</h3><ol><li>Calculate the hashCode for the first significant field “A” and store it in a variable (assume its name is hashResult).</li></ol><ul><li>If “A” is a primitive type call its wrapper class hashCode method.</li><li>Call A.hashCode() if it’s an object reference. If the object is null you can replace it with any constant value, but zero is the most common.</li><li>If it’s an array, we consider every entry as it’s a significant object. So, iterate through the array and accumulate each hash code to the hashResult.</li></ul><p>2. For the remaining significant fields call their hashCode method and sum it to the previously calculated hashResult * 31</p><blockquote>Choosing the number 31 because it’s prime number and easy to get calculated using the shift operator, which is much faster than the normal multiplication</blockquote><p>An example is better to illustrate these steps.</p><pre>class Employee {<br>	private int age;<br>	private int salary;<br>	private String name;<br><br>	private int hashResult;<br><br>	public Employee(int age, int salary, String name) {<br>		this.age = age;<br>		this.salary = salary;<br>                this.name = name;<br>	}<br><br>	@Override<br>	public int hashCode() {<br>		hashResult = Integer.hashCode(age);<br>		hashResult = 31 * hashResult + Integer.hashCode(salary);<br>		hashResult = 31 * hashResult + (name == null ? 0 <br>                    : name.hashCode());<br><br>		return hashResult;<br>	}<br>}</pre><p>Here equals method is eliminated to shorten the code, but it must use these fields for its result, in this case, the <strong>age</strong>, <strong>salary</strong>, and <strong>name</strong>. If the object contains any derived field (a field whose value gets derived from one or more fields) for example, integer field <strong>days</strong> get calculated from the <strong>start</strong> and <strong>end</strong> dates, it shouldn’t participate in hash code calculation if the values used to derive it were already used in the computation. In this case, we may exclude the <strong>days</strong> field if <strong>start</strong> and <strong>end</strong> dates are involved in calculating the hash code.</p><p>Multiplying the <strong>hashResult</strong> each time by <strong>31 </strong>yields a much solid result that depends on the order of the fields. So, if two classes have the same values for different fields the result would be different for both. In our example, if an employee e1 has age = 30, salary = 50 and another e2 has age = 50, <br>salary = 30, the <strong>hashResult </strong>would be different for each of them.</p><blockquote><strong><em>Performance Tip:</em></strong><em> It’s better to optimize the multiplication by using the shift operator in your code. So </em><em>hashResult * 31 == (hashResult &lt;&lt; 5) - hashResult) is true. Shift operator is known to be faster than the normal multiplication operation.</em></blockquote><h3>Building your own hashCode or using Java built-in method (Performance Tip)</h3><p>The Java Object class contains an implementation that looks almost the same as ours, Object.hash(Object... values). Although it performs all the calculations that we need, it has a drawback that should prevent us from using it. The hash method takes a variable number of arguments of object type, which leads to an array creation to hold these objects as well as the process of boxing and unboxing them. This could yield a slow performance if you are using many fields in the hash code computation and the hashCode method gets called multiple times. So it’s better to build your own one using the same steps that we mentioned.</p><h3>Cache the hash result for immutable classes (Performance Tip)</h3><p>If the hashCode() method of an immutable class gets called frequently, it is advisable to cache the hash code result instead of calculating it each time it is requested. See the below code snippet to see how to do that.</p><pre>// Immutable class<br>class Point {<br>    private final int x;<br>    private final int y;<br>    private int hashResult; <br><br>    public Point(int x, int y) {<br>        this.x = x;<br>        this.y = y;<br>    }<br><br>    @Override<br>    public int hashCode() {<br>        int result = hashResult;<br>        <br>        if(result == 0){<br>            result = Integer.hashCode(x);<br>            result = 31 * result + Integer.hashCode(y);<br>            <br>            hashResult = result;<br>        }<br>        return hashResult;<br>    }<br>}</pre><p>In order to minimize collisions and enhance the performance of the HashMap, it’s crucial to incorporate the highly significant fields, even if it comes at the expense of the hashCode method performance. Incorporating these fields helps to avoid situations where multiple objects are mapped to the same hash codes, which can cause the HashMap to behave like multiple LinkedLists and lead to a quadratic time complexity instead of linear. It is recommended to concentrate on using fields that have a higher probability of being unique, such as an employee’s ID, which cannot be identical for two different employees.</p><h3>Conclusion</h3><p>You are required to write a hash function that produces equal hash codes for equal objects and as much as possible distinct results for unequal objects. Use the same fields that are used in the object’s equals method. Don’t rely on the Objects.hash(Object... values) because it will badly affect your performance and memory usage a bit. Remember to cache the hash code for immutable objects if they get called multiple times. To achieve a more even distribution of hash codes, it&#39;s recommended to select the most significant fields that are unlikely to have identical values and utilize them for hash code computation.</p><blockquote>Thank you for reading! If you’re interested in Java coding best practices and performance optimization tips and other Backend Engineering topics, feel free to follow me and subscribe to my newsletter for updates on my latest articles.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=860e1f2b9606" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java’s Object.equals(): The Overlooked Function That Can Make or Break Your Code?]]></title>
            <link>https://medium.com/@samehadel/javas-object-equals-the-overlooked-function-that-can-make-or-break-your-code-e30b738043de?source=rss-81f91041e452------2</link>
            <guid isPermaLink="false">https://medium.com/p/e30b738043de</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[corequality]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Sameh Adel]]></dc:creator>
            <pubDate>Fri, 31 Mar 2023 23:01:41 GMT</pubDate>
            <atom:updated>2023-04-15T01:56:51.155Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WnlX1Jd4mZ_Gl0cj" /><figcaption>Photo by <a href="https://unsplash.com/@max_duz?utm_source=medium&amp;utm_medium=referral">Max Duzij</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As software engineers, we know that even the smallest details can make a big difference in the performance and quality of our code. No one wants to spend endless hours debugging issues that could have been avoided with proper coding practices.</p><p>Unfortunately, the misuse of programming language features is a common culprit behind these nightmares. But fear not, by taking the time to learn and apply best practices, we can ensure our code is efficient, reliable, and easy to maintain. In this article, we’ll explore one such best practice in Java: the proper implementation of the Object.equals() method. We&#39;ll dive into the reasons why this seemingly small detail can have a significant impact on the behavior of our applications and how to do it right. So, if you&#39;re looking to improve your Java skills and write better code, read on!</p><h3>Default implementation</h3><p>If you ignored or decided not to implement the inherited Object.equals(), then you have to know what is the default implementation that Object class provides. But first let’s know the difference between the two ways of comparing objects:<br> 1. Comparing objects using “==” operator. <br> 2. Comparing objects usingObject.equals(Object o)</p><p>The first way compares the references of the two objects, the second calls the equals method that exists inside your object (if overridden).</p><pre>public class Number {<br>    private final int number;<br><br>    public Number (int n){<br>  <br>        number = n;<br>    }<br>}</pre><pre>@Test<br>public void testEqualityWays() {<br>    Number n1= new Number(50);<br>    Number n2= new Number(50);<br>    <br>    Assertions.assertTrue(n1 == n2); // Fails<br>    Assertions.assertTrue(n1.equals(n2)); // Fails<br>}</pre><p>As we can see from the above test n1 == n2result is false because they don’t have the same reference. But why the second statement gives us the same result ? That’s because th Object class implementation of the equals method uses the “==” operator !</p><pre>class Object {<br><br>/* .. remainded of the object code ommitted .. */<br><br>  public boolean equals(Object obj) {<br>        return this == obj;<br>    }<br>}</pre><p>Being aware of this crucial detail motivates us to override the Object.equals() method whenever we need to compare two objects. In the following sections, we will dive into the correct implementation of this method.</p><h3>Equals method general contract</h3><p>Before we dive into details, we should know the contract that we must follow when overriding the equals method which is inherited from the Object class.</p><ol><li><strong>Reflexive:</strong> if we have non-null object instance A, then A.equals(A) must return true.</li><li><strong>Symmetric:</strong> if we have two non-null object instances A and B, if A.equals(B) is true, then B.equals(A) must be true.</li><li><strong>Transitive:</strong> if we have three non-null object instances A, B and C, if A.equals(C) is true, and B.equals(C) is true, then A.equals(C) must be true.</li><li><strong>Consistent:</strong> if we have two non-null object instances A and B, then calling A.equals(B) multiple times must return a consistent value whether true or false.</li></ol><p>These concepts might be hard to grasp at first, but it’s important to avoid violating them. In this article, I won’t be discussing the Reflexive and Consistent parts of the contract, since they are difficult to break. However, it’s still crucial to test them in your code to ensure they are functioning properly.</p><h3>Violation of Symmetry</h3><p>Violations of the <strong>Symmetric </strong>part of the contract are common, especially in cases involving inheritance. To illustrate this point, let’s take a closer look at an example:</p><pre>public class Person {<br>    private final Long id;<br>    private final String name;<br><br>    public Person(long id, String name) {<br>        this.id = id;<br>        this.name = name;<br>    }<br>  <br>    @Override<br>    public boolean equals(Object o) {<br>        if (this == o) return true;<br>  <br>        if (o == null || !(o instanceof Person)) return false;<br>  <br>        Person person = (Person) o;<br>        return Objects.equals(id, person.id) <br>               &amp;&amp; Objects.equals(name, person.name);<br>   }<br>}</pre><pre>public class Employee extends Person {<br>    private final Integer salary;<br><br>    public Employee(long id, String name, Integer salary) {<br>	super(id, name);<br>	this.salary = salary;	<br>    }<br><br>    @Override	<br>    public boolean equals(Object o) {<br>        if (this == o) return true;<br><br>        if (o == null || !(o instanceof Employee)) return false;<br><br>        Employee that = (Employee) o;<br>        return super.equals(o) &amp;&amp; Objects.equals(salary, that.salary);<br><br>    }<br>}</pre><p>We now possess a Person superclass and an Employee subclass. While using the superclass equals method and passing the subclass as a parameter would produce the right outcome, doing otherwise would be inaccurate. The following example illustrates this behavior:</p><pre>@Test<br>public void testSymmetric() {<br>    Person person = new Person(1L, &quot;Name&quot;);<br>    Employee employee = new Employee(1L, &quot;Name&quot;, 1000);<br><br>    Assertions.assertTrue(person.equals(employee)); // Succeed<br>    Assertions.assertTrue(employee.equals(person)); // Fails<br>}</pre><p>Obviously, this test will not pass since employee.equals(person) would result in false due to Person not being an instance of Employee. Can you identify the violation of <strong>Symmetry</strong> in this scenario?</p><h3>Violation of <strong>Transitivity</strong></h3><p>One way to solve this issue is to compare the two objects blindly by ignoring the salary attribute if the parameter passed to the Employee equals method is a Person object employee.equals(person). <br>However, while this approach may fix the <strong>Symmetry</strong> problem, it will lead to disruption of the <strong>Transitivity</strong> part.</p><pre>// Employee equals method<br>// Solves the Symmetric but disrupt Transitivity<br><br>@Override<br>public boolean equals(Object o) {<br>    if (this == o) return true;<br>		<br>    if(!(o instanceof Person))<br>	return false;<br><br>    if(o.getClass() == Person.class) //If superclass -&gt; neglect salary<br>        return o.equals(this);<br><br>    Employee that = (Employee) o;<br>	<br>    return super.equals(o) &amp;&amp; Objects.equals(salary, that.salary);<br>}</pre><p>Again, the result of employee.equals(person) and person.equals(employee) is true. But we still have a <strong>Transitivity </strong>issue.</p><p>Let’s see how the Transitive part of the contract has been broken:</p><pre>@Test<br>public void testTransitive() {<br>    Employee e1 = new Employee(1L, &quot;Name&quot;, 1000);<br>    Person p1 = new Person(1L, &quot;Name&quot;);<br>    Employee e2 = new Employee(1L, &quot;Name&quot;, 5000);<br><br>    Assertions.assertTrue(e1.equals(p1)); // true<br>    Assertions.assertTrue(p1.equals(e2)); // true<br>    Assertions.assertTrue(e1.equals(e2)); // false<br>}</pre><h3>Real effect on these violations on your program</h3><p>At this point, you may be wondering how the violation of <strong>Symmetry </strong>or <strong>Transitivity </strong>could impact your program in practical terms. This is a valid concern; let’s examine the following example to provide the answer.</p><pre>@Test<br>public void testRealWorldCase() {<br>    List&lt;Person&gt; persons = new ArrayList&lt;&gt;();<br>    Person parentObject = new Person(1, &quot;Person_1&quot;);<br>    Employee inheritedObject = new Employee(1, &quot;Person_1&quot;, 1000);<br><br>    persons.add(parentObject);<br><br>    Assertions.assertTrue(persons.contains(inheritedObject)); // false<br>}</pre><p>Clearly, this outcome is not what was anticipated, as the inheritedObject, despite being of Employee type, is still regarded as a Person object, and calling the persons.contains(parentObject) should return true.</p><h3>Solution</h3><p>The issue at hand is a fundamental problem with equivalence relations in object-oriented languages. When trying to extend an instantiable class and add a value component (in our case is salary component), while preserving the equals contract, there is no solution available unless one is willing to sacrifice the advantages of object-oriented abstraction.</p><p>If you opt to abandon the OOP abstraction and instead implement objects that can be compared to each other to achieve the desired outcome, you could refer to the following example:</p><pre>class Employee {<br>    private final Person person;<br>    private final Integer salary;<br>	<br>    public Employee(Long id, String name, Integer salary) {<br>        person = new Person(id, name);<br>	this.salary = Objects.requireNonNull(salary);<br>    }<br>	<br>    /**<br>    * Returns the person-view of this employee.<br>    */<br>    public Person asPerson() {<br>        return person;<br>    }<br>	<br>    @Override <br>    public boolean equals(Object o) {<br>	if (!(o instanceof Employee))<br>	    return false;<br>		<br>        Employee employee = (Employee) o;<br>		<br>	return employee.person.equals(person) <br>               &amp;&amp; employee.salary.equals(salary);<br>    }<br>}</pre><h3>Conclusion</h3><p>The problem discussed in this context is not meant to find a straightforward solution, but rather to alert you about the significance of implementing the equals method carefully when using inheritance, as well as when using codes that depend on the implementation of the equals method, such as List.contains(Object). If you choose to rely on OOP abstractions, a conservative approach is to refrain from using Polymorphism with Collections that use the equals method of the object behind the scene. In our case this means to use List&lt;Employee&gt; to hold Employee objects without the use of Person to achieve the abstraction. Further analysis and comprehension of the internal workings of the libraries utilized in your program are required to insure the reliability and order to write reliable and consistent applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e30b738043de" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>