<?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 Berkay Baris Algun on Medium]]></title>
        <description><![CDATA[Stories by Berkay Baris Algun on Medium]]></description>
        <link>https://medium.com/@barisalgun?source=rss-3a27323cdf8e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wW4F9qPOBmuruUDJZQqAgg.jpeg</url>
            <title>Stories by Berkay Baris Algun on Medium</title>
            <link>https://medium.com/@barisalgun?source=rss-3a27323cdf8e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 00:56:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@barisalgun/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 Elasticsearch: A Comprehensive Guide for Beginners]]></title>
            <link>https://medium.com/@barisalgun/understanding-elasticsearch-a-comprehensive-guide-for-beginners-838a27ad5a8f?source=rss-3a27323cdf8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/838a27ad5a8f</guid>
            <category><![CDATA[search-engines]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[query]]></category>
            <category><![CDATA[full-text-search]]></category>
            <dc:creator><![CDATA[Berkay Baris Algun]]></dc:creator>
            <pubDate>Fri, 02 Aug 2024 08:46:04 GMT</pubDate>
            <atom:updated>2024-08-02T08:47:30.295Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*d7iE0p7yvuqHNEzk7hbYjg.png" /></figure><h3>Section 1: What is Elasticsearch?</h3><p>Elasticsearch is an advanced, index-based, full-text search system that helps users create custom queries to receive clear results. A major benefit of Elasticsearch is its ability to handle complex searches efficiently.</p><p>— <em>Elasticsearch is built on the </em><a href="https://lucene.apache.org/"><em>Apache Lucene library</em></a><em>, which is written in Java. Lucene is a powerful text search engine library that provides the core search functionality in Elasticsearch. </em>—</p><h4><strong>What is a Complex Search or Query?</strong></h4><p>You might have heard about complex searches and queries, but what do they actually mean? A basic explanation of a complex search is a query that involves multiple conditions. For example, let’s say you want to find my articles on Medium, but within a specific date range, and the topics must include Java. These kinds of searches require the system to process and combine different criteria to deliver precise results.</p><p>Here is an example of complex query.</p><pre>SELECT *<br>FROM articles<br>WHERE author = &#39;Baris Algun&#39;<br>  AND published_date BETWEEN &#39;2023-01-01&#39; AND &#39;2023-12-31&#39;<br>  AND topic LIKE &#39;%Java%&#39;<br>ORDER BY published_date DESC;</pre><p><em>This query finds all articles written by ‘Baris Algun’, published within the year 2023, and includes ‘Java’ in the topic. It then orders the results by the published date in descending order.</em></p><h4><strong>Where and Who Uses Elasticsearch?</strong></h4><p><strong>E-commerce Platforms</strong>:</p><ul><li><strong>Use Case</strong>: Enhancing search and autocomplete features.</li><li><strong>Example</strong>: Online stores use Elasticsearch to help customers quickly find products and get search suggestions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_g3Y69KBTsq-2PQMj7KBUw.png" /><figcaption>Amazon auto-complete example</figcaption></figure><p><strong>Log and Event Data Analysis:</strong></p><ul><li><strong>Use Case</strong>: Monitoring system logs in real-time.</li><li><strong>Example</strong>: Companies analyze server logs to detect issues and improve performance.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jEHcEcf2aDCERpcuFY9NjQ.png" /><figcaption>Log monitoring</figcaption></figure><p>For my experience, the use case of autocompletion when searching for products and product suggestions on e-commerce websites impressed me, and I wrote this article.</p><h3>Section 2: Core Concepts</h3><h4><strong>Clusters and Nodes</strong></h4><p>Before these two words overwhelm you, I want you to take a look at the image below. This will help us understand these terms better before we dive deeper into them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sfEynQdJimfVtzg1OVmafg.png" /><figcaption>Example of Cluster-Node Structure</figcaption></figure><ul><li><strong>Red Arrow -&gt; Cluster</strong>: The cluster is the foundation for nodes. Think of it as a tent that houses nodes.</li><li><strong>Blue Arrow -&gt; Node</strong>: Nodes are critical components within the cluster. They are where indexing, data storage, and searching occur. Also they are instances of Elasticsearch.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JsXzdnWlVlQcmdwt1kMfEg.png" /><figcaption>Master Node Example</figcaption></figure><ul><li><strong>Green Arrow -&gt; Master Node</strong>: The Master Node controls the cluster. It is responsible for managing the process of creating and deleting indexes, ensuring that the cluster remains healthy and operational. (<em>The rest of the nodes in the cluster are often referred to as Client Nodes, which handle tasks like processing search requests and collecting results.</em>)</li></ul><h4>4. Shards and Replicas</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bbvGMTWdRtGpq0cFYrGEew.png" /><figcaption>Shards Example</figcaption></figure><ul><li><strong>Pink Arrow -&gt; Shard: </strong>Shards are the fundamental data storage units in Elasticsearch. When we start our Elasticsearch engine, nodes are created first, which serve as the basic structure. Shards are instances of Lucene controlled by these nodes, and they are responsible for storing and indexing data.</li><li><strong>Primary Shard</strong>: This is the main copy of the data.</li><li><strong>Replica Shard</strong>: A copy of the primary shard, providing backup. Replica shards are stored on different nodes than the primary shards to ensure data reliability.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M4EUu0-_Zu8GhguN6I4mvA.png" /><figcaption>Example of Primary and Replica Shard</figcaption></figure><h4>How does the backup system work in Elasticsearch?</h4><p>I know we’ve used the term ‘index,’ and you may be wondering, what is indexing? Check the image below; I’m sure it will make things clearer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*5L8tH6suvXnVb7hxq_pHTw.png" /><figcaption>Indexing Example</figcaption></figure><h4>Index and Indexing in Elasticsearch</h4><p>In Elasticsearch, an index is similar to a database in traditional systems. It is a collection of documents that share similar characteristics.</p><ul><li><strong>Example</strong>: An e-commerce site might use an index named products to store details about items for sale, such as names, prices, descriptions and discounts.</li></ul><p><strong>Indexing</strong>: Indexing is the process of adding, updating, or deleting data in an index. This process involves analyzing the data and storing it in a way that allows for fast and efficient searching.</p><h3>Section 3: Basic Operations</h3><p>In this section, I’ll demonstrate basic operations in Elasticsearch. Since Elasticsearch supports interactions through RESTful APIs, we’ll cover four main request methods: POST, PUT, GET, and DELETE.</p><h4>Indexing data (PUT)</h4><p>As I mentioned earlier, indexing refers to adding new data to an Elasticsearch index.</p><p>For example, to add a new customer to an index called customer, you would use the following PUT request:</p><pre>PUT customer/_doc/1<br>{<br>  &quot;id&quot;: 13,<br>  &quot;name&quot;: &quot;Baris&quot;,<br>  &quot;isActive&quot;: true,<br>  &quot;contact&quot;: {<br>    &quot;address&quot;: &quot;Istanbul&quot;,<br>    &quot;phone&quot;: &quot;99999999999&quot;<br>  }<br>}</pre><p><em>Let’s examine what is </em><strong><em>customer/_doc/{id}</em></strong><em> refers to ?</em></p><p>customer — This is the name of our index. Index is like a database in which data is stored.</p><p>_doc — This indicates that we are working with a document type. In this context, it means we are creating or interacting with a document.</p><p>id — our custom id. (if we don’t specify the id, Elasticsearch create one for us)</p><p>Let’s examine the response from Elasticsearch:</p><pre>{<br>  &quot;_index&quot;: &quot;customer&quot;,<br>  &quot;_id&quot;: &quot;1&quot;,<br>  &quot;_version&quot;: 1,<br>  &quot;result&quot;: &quot;created&quot;,<br>  &quot;_shards&quot;: {<br>    &quot;total&quot;: 2,<br>    &quot;successful&quot;: 1,<br>    &quot;failed&quot;: 0<br>  },<br>  &quot;_seq_no&quot;: 7,<br>  &quot;_primary_term&quot;: 1<br>}</pre><ul><li><strong>_index</strong>: The name of the index where the document is stored, e.g., “customer.”</li><li><strong>_id</strong>: The unique identifier for the document.</li><li><strong>_version</strong>: The version number of the document, used for tracking changes. Here, it is version 1.</li><li><strong>result</strong>: The outcome of the operation. “created” means a new document was successfully added.</li><li><strong>_shards</strong>: Details about the shards:</li><li><strong>total</strong>: Total number of shards involved.</li><li><strong>successful</strong>: Number of shards where the operation succeeded.</li><li><strong>failed</strong>: Number of shards where the operation failed (0 means no failures).</li><li><strong>_seq_no</strong>: A sequence number assigned to the document, used internally by Elasticsearch.</li><li><strong>_primary_term</strong>: A number that helps manage the lifecycle of the primary shard.</li></ul><h4>2. Searching Data (GET)</h4><p>Let’s retrieve the data that we created.</p><p>To do this, we use the GET request:</p><p>GET customer/_doc/1</p><p>Let’s examine the response from Elasticsearch:</p><pre>{<br>  &quot;_index&quot;: &quot;customer&quot;,<br>  &quot;_id&quot;: &quot;1&quot;,<br>  &quot;_version&quot;: 6,<br>  &quot;_seq_no&quot;: 5,<br>  &quot;_primary_term&quot;: 1,<br>  &quot;found&quot;: true,<br>  &quot;_source&quot;: {<br>    &quot;id&quot;: 5,<br>    &quot;name&quot;: &quot;Baris&quot;,<br>    &quot;isActive&quot;: &quot;true&quot;,<br>    &quot;contact&quot;: {<br>      &quot;address&quot;: &quot;Istanbul&quot;,<br>      &quot;phone&quot;: &quot;90555553432&quot;,<br>      &quot;postalCode&quot;: &quot;34765&quot;<br>    }<br>  }<br>}</pre><p>You may realise that first 6 rows are metadata. If you just want to get<em> “_source” you can use “</em>GET musteri/_source/1<em>”</em></p><h4>3. Updating Data (POST)</h4><p>Let’s modify our existing document in the index:</p><p>POST customer/_update/1</p><pre>{<br> &quot;doc&quot;:{<br> &quot;name&quot;:&quot;Berkay Baris Algun&quot;<br> }<br>}</pre><p>This request updates the document with ID “1” in the customer index, changing the name field. Let’s examine the response from Elasticsearch:</p><pre>{<br>  &quot;_index&quot;: &quot;customer&quot;,<br>  &quot;_id&quot;: &quot;1&quot;,<br>  &quot;_version&quot;: 2,<br>  &quot;result&quot;: &quot;updated&quot;,<br>  &quot;_shards&quot;: {<br>    &quot;total&quot;: 2,<br>    &quot;successful&quot;: 1,<br>    &quot;failed&quot;: 0<br>  },<br>  &quot;_seq_no&quot;: 10,<br>  &quot;_primary_term&quot;: 1<br>}</pre><p>As you can see, the _version is updated every time we create or update a document.</p><h4>4. Deleting Data (DELETE)</h4><p>Let’s delete our existing document in the index</p><p>DELETE customer/_doc/1</p><p>This request deletes the document with ID “1” in the customer index. Let’s examine the response from Elasticsearch:</p><pre>{<br>  &quot;_index&quot;: &quot;customer&quot;,<br>  &quot;_id&quot;: &quot;1&quot;,<br>  &quot;_version&quot;: 4,<br>  &quot;result&quot;: &quot;deleted&quot;,<br>  &quot;_shards&quot;: {<br>    &quot;total&quot;: 2,<br>    &quot;successful&quot;: 1,<br>    &quot;failed&quot;: 0<br>  },<br>  &quot;_seq_no&quot;: 11,<br>  &quot;_primary_term&quot;: 1<br>}</pre><h3>Section 4: Searching for Data</h3><h4>How does search work?</h4><p>Elasticsearch allows you to query both structured and unstructured data. Here is a brief overview of search types. We will be using GET customer/_search for requests.</p><h4>Structured Search</h4><p>For example, searching for documents where a specific field matches a given value. Here is an example of finding all customers from “Istanbul”:</p><pre>{<br>  &quot;query&quot;: {<br>    &quot;match&quot;: {<br>      &quot;contact.address&quot;: &quot;Istanbul&quot;<br>    }<br>  }<br>}</pre><h4>Unstructured Search</h4><p>As the name suggests, unstructured data stands for full-text search, which is what Elasticsearch is popular for. Here is an example of finding all documents that mention “Istanbul”:</p><pre>{<br>  &quot;query&quot;: {<br>    &quot;match&quot;: {<br>      &quot;message&quot;: &quot;Istanbul&quot;<br>    }<br>  }<br>}</pre><p><strong>Example of Query Types</strong></p><p>Elasticsearch supports various query types to handle different search needs. Here are a few commonly used query types:</p><p><strong>Term Query</strong></p><p>Term queries are used to search for exact matches. This query is useful when you need to match exact values, such as IDs or keywords.</p><p><strong>Example</strong>: Finding a customer with a specific ID.</p><pre>{<br>  &quot;query&quot;: {<br>    &quot;term&quot;: {<br>      &quot;id&quot;: 13<br>    }<br>  }<br>}</pre><p><strong>Range Query</strong></p><p>Range queries are used to search for documents with values within a specific range. This query is useful for numerical or date fields.</p><p><strong>Example</strong>: Finding customers who were born within a certain date range.</p><pre>{<br>  &quot;query&quot;: {<br>    &quot;range&quot;: {<br>      &quot;born_date&quot;: {<br>        &quot;gte&quot;: &quot;2000-01-01&quot;,<br>        &quot;lte&quot;: &quot;2001-03-19&quot;<br>      }<br>    }<br>  }<br>}</pre><p><strong>Boolean Query</strong></p><p>Boolean queries combine multiple query clauses, such as must, should, and must_not, to form complex searches.</p><p><strong>Example</strong>: Finding customers from “Istanbul” who mentioned “Baris”:</p><pre>{<br>  &quot;query&quot;: {<br>    &quot;bool&quot;: {<br>      &quot;must&quot;: [<br>        { &quot;match&quot;: { &quot;contact.address&quot;: &quot;Istanbul&quot; }},<br>        { &quot;match&quot;: { &quot;message&quot;: &quot;Baris&quot; }}<br>      ]<br>    }<br>  }<br>}</pre><p><strong>Documentation Reference</strong>: If you want to explore more query types and detailed explanations, please refer to the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl.html">Elasticsearch documentation</a>.</p><h3>References</h3><ul><li><a href="https://www.dbi-services.com/blog/elastic-elk-stack-elasticsearch-terminologies/">https://www.dbi-services.com/blog/elastic-elk-stack-elasticsearch-terminologies/</a></li><li><a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/add-elasticsearch-nodes.html">https://www.elastic.co/guide/en/elasticsearch/reference/current/add-elasticsearch-nodes.html</a></li><li><a href="https://www.progress.com/tutorials/odbc/using-indexes">https://www.progress.com/tutorials/odbc/using-indexes</a></li><li><a href="https://blog.arcanna.ai/elasticsearch-shard-optimization">https://blog.arcanna.ai/elasticsearch-shard-optimization</a></li><li><a href="https://www.devopsschool.com/blog/what-is-seq_no-and-primary_term-in-elasticsearch/#:~:text=Elasticsearch%20keeps%20tracks%20of%20the,primary_term">https://www.devopsschool.com/blog/what-is-seq_no-and-primary_term-inelasticsearch/#:~:text=Elasticsearch%20keeps%20tracks%20of%20the,primary_term</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=838a27ad5a8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns — Strategy Pattern]]></title>
            <link>https://medium.com/@barisalgun/design-patterns-strategy-pattern-9ef81cbc8a15?source=rss-3a27323cdf8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ef81cbc8a15</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[strategy-pattern]]></category>
            <category><![CDATA[design-patterns-in-java]]></category>
            <dc:creator><![CDATA[Berkay Baris Algun]]></dc:creator>
            <pubDate>Tue, 14 May 2024 09:34:54 GMT</pubDate>
            <atom:updated>2024-05-14T09:41:00.757Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design Patterns — Strategy Pattern</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*jbYxaBcLQxY-NiDqTAEpfg.png" /></figure><h4>Technical Definition</h4><p>Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.</p><p><em>I get it might be confusing, but let’s try explaining it in a simpler way.</em></p><h4>Basic Definition</h4><p>The strategy Pattern is a desing approach in software that allows a program to choose between different methods at runtime. Instead of being restricted to one fixed method, the program can decide which one to use while it is running.</p><h4>Why Strategy Pattern Is Important?</h4><p>Strategy pattern helps make our code more reusable, scalable, and easier to maintain. With this pattern, each algorithm can decide its own way of doing things while the program is running. This flexibility makes it simple to add new algorithms or change existing ones, making our system more adaptable and easier to manage.</p><p>I suppose things are clearer now. However, let’s delve deeper using a practical human analogy as an example.</p><p>Let’s say you want to create a real-life human-like system. Basically, you’ll include different types of people like “student,” “worker,” “baby,” etc. Each type will have similar and different characteristics. For example, they all have a physical appearance, which is common among them. However, only the worker earns money, which means they’re the only type with a “salary” method. We will be implementing our human system based on this approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*1Ik_3FbmJAjTWHXRTN_Hnw.png" /></figure><p>From this UML diagram, you can observe that both the “student” and “worker” classes inherit the “appearance” and “talk” methods from the “person” class. Everything appears to be fine at this point because the way a student talks and the way a worker talks are the same. Everything seems to be in order for now. However, let’s consider adding another method, “run,” which makes sense because a person can run. So, the “student” and “worker” classes will inherit this method, allowing them to run as well!</p><p>Now let’s add one more person type. Baby!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*umcR7pYL48R1nQTXL7LIoA.png" /></figure><p>Since babies shouldn’t be running, we can’t simply inherit the “run” method from the person class without considering this.</p><p>Let’s introduce another class called “Athlete.” Since the way athletes run is different from normal people, we need to handle this differently. However, currently, we’ve simply inherited the same “run” method, resulting in both students and athletes running in the same way, which is not what we expect!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xWNzxgNLn38Zr7mLH6N0bg.png" /></figure><p>We just copied and pasted the same running code, so all our subclasses are using the same running method. We might think, “We need a specific running class for athletes,” which sounds reasonable at first. However, this approach could lead us down a dangerous path. Let’s consider if we have another method, like “eat.” Would we need to implement a new class every time this occurs?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5R7gF4HXz2geWFCexFBZ6w.png" /><figcaption>inheritance hierarchy</figcaption></figure><p>As long as you want to share behavior horizontally (represented by the red arrows), there’s no way to do it without implementing new kinds of design pattern.</p><p>Let’s just jump into the solution. We will be using Interfaces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RzATVyKxxSEw2cyRv_ea0w.png" /></figure><p>See, every person needs to run and talk. Also, students and babies usually act similarly in appearance (even though it might vary depending on the situation).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PUv9t4HgUNuBUS6HZTB7BA.png" /></figure><p>We’ve included SimpleTalk and SimpleRun and ensured they stick to the IRunBehaviour and ITalkBehaviour interfaces.</p><p>We just said, and person must have concrete Talk behaviour.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w8EsuWDPTAEoeNduKwsZZw.png" /></figure><p>Anything implementing ITalkBehaviour or IRunBehaviour must have specific talk or run behaviors. Instead of saying we have concrete and particular behavior (indicated by the green arrows).</p><p>As you can see, we can do the same for appearance. Let’s convert appearance to an interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bdU-CmZYA4DvUdQS1cnt3Q.png" /></figure><p>If the person has appearance behavior, it makes use of IAppearanceBehaviour. When we call the appearance method, whichever concrete appearance method is configured can be easily invoked.</p><p>So, as you can see, we don’t require subclasses such as baby, student, athlete, and so on. These are no longer named classes within the system. Instead, they represent specific configurations of instances of behaviors.</p><p>Let’s see it on code.</p><pre>public abstract class Person {<br>    ITalkBehaviour iTalkBehaviour;<br>    IRunBehaviour iRunBehaviour;<br>    IAppearanceBehaviour iAppearanceBehaviour;<br><br>    public Person(ITalkBehaviour iTalkBehaviour,<br>                  IRunBehaviour iRunBehaviour,<br>                  IAppearanceBehaviour iAppearanceBehaviour){<br>        this.iTalkBehaviour=iTalkBehaviour;<br>        this.iRunBehaviour=iRunBehaviour;<br>        this.iAppearanceBehaviour=iAppearanceBehaviour;<br>    }<br><br>    public void talk(){<br>        this.iTalkBehaviour.talk();<br>    }<br><br>    public void run(){<br>        this.iRunBehaviour.run();<br>    }<br>    <br>    public void appearance(){<br>        this.iAppearance.appear();<br>    }<br>}</pre><p>So, you’re passing a behavior, and then you execute that behavior within the class. When we simplify everything, we end up with something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KhXYFhA8Ni3myRNjHGvduA.png" /></figure><p>The client has an IBehavior that can be implemented by many concrete behaviors. The execution in the client class, which stands for the execution of the run method in IBehavior, encapsulates the Strategy Pattern. Things were initially complicated due to the variety of different types and methods.</p><h4>Sources</h4><ul><li><a href="https://refactoring.guru/design-patterns/strategy">https://refactoring.guru/design-patterns/strategy</a></li><li><a href="https://www.geeksforgeeks.org/strategy-pattern-set-1/">https://www.geeksforgeeks.org/strategy-pattern-set-1/</a></li><li><a href="https://www.cs.unc.edu/~stotts/GOF/hires/pat5ifso.htm">https://www.cs.unc.edu/~stotts/GOF/hires/pat5ifso.htm</a></li><li>Christopher Okhravi Design Patterns — Strategy Pattern</li><li>Chatgpt</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ef81cbc8a15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enums in Java]]></title>
            <link>https://medium.com/@barisalgun/enums-in-java-8ade8de0d257?source=rss-3a27323cdf8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ade8de0d257</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[type-safety]]></category>
            <category><![CDATA[readability]]></category>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[oop]]></category>
            <dc:creator><![CDATA[Berkay Baris Algun]]></dc:creator>
            <pubDate>Fri, 09 Feb 2024 18:05:55 GMT</pubDate>
            <atom:updated>2024-02-09T19:49:14.224Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*Lfeh_c7b51BefsHrQ4ppnw.png" /><figcaption>Java Enums</figcaption></figure><h3>Introduction</h3><p>Let’s keep things simple and see why and when we use enums in Java.</p><p>Enums are commonly used for fixed values like the days of the week, seasons, colors, and other unchanging categories. Also enums provide <strong><em>type safety</em></strong>, meaning that a variable of an enum type can only be assigned one of the predefined values. This helps prevent accidental assignment of invalid values that might occur by accidentally assigning an invalid value.</p><h4>Defining Enums</h4><p>To create enums, we need to use <strong><em>enum </em></strong><em>keyword instead of class, interface or record class types.</em></p><p>For instance, this is a typical Java class.</p><pre>public class TypicalClass{<br>   //rest of the code<br>}</pre><p>and this is a typical enum class.</p><pre>public enum Enums{<br>    // rest of the code<br>}</pre><p>As you can observe, only difference in syntax side is just changing the type of the class.</p><p>Now, let’s build our first enum class for our CoffeeShop and play with it. Let’s add our enums as coffee types, constructor and variables.</p><pre>    ESPRESSO(30, &quot;Prepared under high pressure in a very short time.&quot;),<br>    AMERICANO(100, &quot;Espresso with added hot water, resulting in a larger volume.&quot;),<br>    LATTE(150, &quot;Espresso topped with steamed milk and a bit of milk foam.&quot;),<br>    CAPPUCCINO(150, &quot;Espresso with equal amounts of steamed milk and milk foam on top.&quot;);<br><br>    <br>    private final int ml;<br>    private final String description;<br><br>   private CoffeeType(int ml, String description) {<br>    this.ml = ml;<br>    this.description = description;<br>    }<br><br>    public int getMl() {<br>        return ml;<br>    }<br><br>    public String getDescription() {<br>        return description;<br>    }</pre><p>In order to use these enums let’s consider overriding toString method. The toString() method defines how an enum value is represented as a string. Overriding this method allows us to control the displayed output when printing or logging enum values. For those wondering why and how to do it I also provide a video feel free to checkout:</p><pre>@Override<br>    public String toString() {<br>        return this.name() + &quot; (&quot; + this.ml + &quot;ml): &quot; + this.description;<br>    }</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FGvbdMwfjB98%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DGvbdMwfjB98&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FGvbdMwfjB98%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/69a985d4965d035b60af99cc790eba87/href">https://medium.com/media/69a985d4965d035b60af99cc790eba87/href</a></iframe><p>For the last part I added a method to calculate the price with switch method.</p><pre>public double calculatePrice() {<br>        switch (this) {<br>            case ESPRESSO:<br>                return 7;<br>            case AMERICANO:<br>                return 8;<br>            case LATTE:<br>                return 10;<br>            case CAPPUCCINO:<br>                return 11;<br>            default:<br>                throw new AssertionError(&quot;Unknown coffee: &quot; + this);<br>        }<br>    }</pre><h4>How to use and access enum values:</h4><p>Most important thing is you don’t create new enum values with the “new” keyword like you do for a class. Instead, you use the already given constants by their names. For example:</p><pre>CoffeeType myCoffee=CoffeeType.LATTE;</pre><h4>Accessing Enum Properties and Methods</h4><p>You can access the properties and methods of an enum value just like you would with an object. For instance, to get the description of myCoffee, you would do:</p><pre>String description = myCoffee.getDescription();</pre><p>And to print the milliliters (ml) and calculate the price:</p><pre>System.out.println(&quot;Volume: &quot; + myCoffee.getMl() + &quot;ml&quot;);<br>double price = myCoffee.calculatePrice();<br>System.out.println(&quot;Price: $&quot; + price);</pre><h4>Iterating Over Enum Values</h4><p>If you need to loop through every possible value of an enum, you can accomplish this by utilizing the values() method. This method provides an array containing all the enum constants, arranged in the order they were declared.</p><pre>for (CoffeeType coffee : CoffeeType.values()) {<br>    System.out.println(coffee + &quot; costs $&quot; + coffee.calculatePrice());<br>}</pre><p>When we execute this code, output will be like the one in below. Don’t forget that we override the toString() method above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*Usmd1bRTvFvPHlciteWuLQ.png" /><figcaption>Output</figcaption></figure><h4>Comparing Enum Values</h4><p>You can compare enum values using == or .equals(). Since enums are singleton instances, == is safe for comparing enum values:</p><pre>if (myCoffee == CoffeeType.ESPRESSO) {<br>    System.out.println(&quot;It&#39;s an espresso.&quot;);<br>}</pre><h4>Advantages of Using Enums</h4><ul><li><strong>Type Safety</strong>: Enums provide type safety by limiting the possible values that can be assigned to a variable.</li><li><strong>Readability</strong>: Using meaningful names with enums improves code readability.</li><li><strong>Switch Support</strong>: Enums seamlessly integrate with switch statements, making control flows clear and concise.</li><li><strong>Enhanced Behaviors</strong>: Enums can contain fields, methods, and constructors, making them more powerful than simple constants.</li></ul><h4>Conclusion</h4><p>Enums in Java are a very useful tool that do many important jobs, making them a key part of the language, especially when you’re working with a group of constant values that don’t change.</p><p><em>CoffeeType Enum Class</em></p><pre>public enum CoffeeType {<br>    ESPRESSO(30, &quot;Prepared under high pressure in a very short time.&quot;),<br>    AMERICANO(100, &quot;Espresso with added hot water, resulting in a larger volume.&quot;),<br>    LATTE(150, &quot;Espresso topped with steamed milk and a bit of milk foam.&quot;),<br>    CAPPUCCINO(150, &quot;Espresso with equal amounts of steamed milk and milk foam on top.&quot;);<br><br>    private final int ml;<br>    private final String description;<br><br>    CoffeeType(int ml, String description) {<br>        this.ml = ml;<br>        this.description = description;<br>    }<br><br>    public int getMl() {<br>        return ml;<br>    }<br><br>    public String getDescription() {<br>        return description;<br>    }<br><br>    @Override<br>    public String toString() {<br>        return this.name() + &quot; (&quot; + this.ml + &quot;ml): &quot; + this.description;<br>    }<br><br>    public double calculatePrice() {<br>        switch (this) {<br>            case ESPRESSO:<br>                return 7;<br>            case AMERICANO:<br>                return 8;<br>            case LATTE:<br>                return 10;<br>            case CAPPUCCINO:<br>                return 11;<br>            default:<br>                throw new AssertionError(&quot;Unknown coffee: &quot; + this);<br>        }<br>    }<br>}</pre><p><em>Main Class</em></p><pre>public class Main {<br>    public static void main(String[] args) {<br><br>        //Accessing Enum Properties and Methods<br>        CoffeeType myCoffee=CoffeeType.LATTE;<br><br><br><br>        //Iterating Over Enum Values<br>        for (CoffeeType coffee:CoffeeType.values()){<br>            System.out.println(coffee +&quot; costs $&quot;+coffee.calculatePrice());<br>        }<br><br>        //Comparing Enum and Values<br>        if (myCoffee == CoffeeType.ESPRESSO) {<br>            System.out.println(&quot;It&#39;s an espresso.&quot;);<br>        }<br>    }<br><br>}</pre><h4>Postscript</h4><p>Access the Source Code on GitHub: If you’re interested in exploring the source code used in this article, you can find it all on my GitHub repository. Feel free to review, fork, or contribute to the code as needed. Visit <a href="https://github.com/berkaybarisalgun/Java-Enums-Practice">Github </a>to access.</p><h4>Resources</h4><ul><li><a href="https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html">https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html</a></li><li><a href="https://ioflood.com/blog/java-enum-with-values/">https://ioflood.com/blog/java-enum-with-values/</a></li><li>Chatgpt 4</li><li>Google Gemini(Advanced)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ade8de0d257" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pagination in Spring Boot]]></title>
            <link>https://medium.com/@barisalgun/spring-boot-pagination-524083e699fc?source=rss-3a27323cdf8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/524083e699fc</guid>
            <category><![CDATA[jpa]]></category>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-framework]]></category>
            <dc:creator><![CDATA[Berkay Baris Algun]]></dc:creator>
            <pubDate>Sat, 30 Sep 2023 19:08:37 GMT</pubDate>
            <atom:updated>2023-10-01T06:32:50.069Z</atom:updated>
            <content:encoded><![CDATA[<h4>What is Pagination?</h4><p>source code for this article: <a href="https://github.com/berkaybarisalgun/Pagination-Example"><em>Pagination Example</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*16Ej1s1jySts4ey6Pe4S_g.png" /></figure><p>Check the image below. Did you recognize it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NwlrN_3JBZ3FppUTvZRf3A.png" /><figcaption>Pagination Examples</figcaption></figure><p>As we all can observe, these are the pages that are divided for handling large datasets. Roughly speaking, this is <strong>PAGINATION!</strong></p><p>Now, let’s take a look at how we can implement this in our Spring Boot project.</p><h4>Implementation</h4><p>Since we will be implementing via jpa we have to add jpa dependency to our <em>pom.xml</em></p><pre>&lt;dependency&gt;<br> &lt;groupId&gt;jakarta.persistence&lt;/groupId&gt;<br> &lt;artifactId&gt;jakarta.persistence-api&lt;/artifactId&gt;<br> &lt;version&gt;3.1.0&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>Let’s create our <strong><em>Student</em></strong><em> </em>model</p><pre>@Entity /* <br>        This class is marked as an Entity,<br>        which means it will be mapped to a database table.<br>        */    <br>@Table(name = &quot;student&quot;)<br>@Getter<br>@Setter<br>@AllArgsConstructor<br>@NoArgsConstructor<br>public class Student {<br><br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private int id;<br><br>    @Column(name = &quot;first_name&quot;)<br>    private String firstName;<br><br>    @Column(name = &quot;last_name&quot;)<br>    private String lastName;<br><br>    @Column(name = &quot;gender&quot;)<br>    private Character gender;<br><br>}</pre><p>Since this topic is not related to pagination, I won’t provide any further explanation.</p><p>Establish a <strong><em>Student Repository</em></strong></p><pre>public interface StudentRepository extends JpaRepository&lt;Student,Integer&gt; {}<br>/*<br>Please note that JpaRepository also inherits from <br>&#39;PagingAndSortingRepository,&#39; so we could extend it as well.<br>*/</pre><p><strong><em>JpaRepository</em></strong> is the primary tool that aids us in utilizing Pageable, so keep that in mind.</p><p>Establish a <strong><em>Student Service</em></strong></p><pre>@Service<br>/*<br> This class is marked as a Service, <br>which is typically used in the Spring Framework.<br>*/<br>@AllArgsConstructor<br>public class StudentService {<br>    private final StudentRepository repository;<br><br>    public Page&lt;Student&gt; getAllStudents(Pageable pageable){<br>        return repository.findAll(pageable);<br>    }<br>}</pre><p>As you can see, using <strong><em>Pageable </em></strong>as a parameter in our code is a good practice when working with large datasets as it improves presentation efficiency.</p><p>Establish a <strong><em>Student Controller</em></strong></p><pre>@RestController<br>/*<br> This class is marked as a RestController, <br>indicating that it handles HTTP requests<br>*/<br>@RequiredArgsConstructor<br>public class StudentController {<br>    private final StudentService service;<br><br>    @GetMapping(&quot;/students&quot;)<br>    public Page&lt;Student&gt; getItems(@RequestParam(name = &quot;page&quot;, defaultValue = &quot;0&quot;) int page,<br>                                  @RequestParam(name = &quot;size&quot;, defaultValue = &quot;10&quot;) int size) {<br>        Pageable pageable = PageRequest.of(page, size);<br>        return service.getAllStudents(pageable);<br>    }<br>}</pre><p>Within the class, you&#39;ll find a method labeled with the annotation @GetMapping(&quot;/students&quot;).</p><p>This method handles HTTP GET requests to the /studentsendpoint. When a user makes a GET request to this endpoint, this method is executed.</p><p>The method takes two parameters, both annotated with @RequestParam:</p><ul><li>page: This parameter is used to specify the page number and has a default value of 0 if not provided.</li><li>size: This parameter is used to specify the number of items per page and has a default value of 10 if not provided.</li></ul><p><strong><em>Main Class</em></strong></p><p>I’ve provided mock data in the main class to ensure reliable tests. Nevertheless, it’s important to keep in mind that this might not be sufficient.</p><pre>@SpringBootApplication<br>public class PaginationExampleApplication {<br><br> public static void main(String[] args) {<br>  SpringApplication.run(PaginationExampleApplication.class, args);<br> }<br><br> @Bean<br> public CommandLineRunner loadData(StudentRepository StudentRepository){<br>  return args-&gt;{<br>   Student student=new Student();<br>   student.setFirstName(&quot;Baris&quot;);<br>   student.setLastName(&quot;Algun&quot;);<br>   student.setGender(&#39;M&#39;);<br>   <br>   Student student1=new Student();<br>   student1.setFirstName(&quot;Cristiano&quot;);<br>   student1.setLastName(&quot;Ronaldo&quot;);<br>   student1.setGender(&#39;M&#39;);<br>   <br>   Student student2=new Student();<br>   student2.setFirstName(&quot;Maria&quot;);<br>   student2.setLastName(&quot;Sharapova&quot;);<br>   student2.setGender(&#39;F&#39;);<br>   <br>   Student student3=new Student();<br>   student3.setFirstName(&quot;Virginia&quot;);<br>   student3.setLastName(&quot;Woolf&quot;);<br>   student3.setGender(&#39;F&#39;);<br>   <br>   Student student4=new Student();<br>   student4.setFirstName(&quot;Orhan&quot;);<br>   student4.setLastName(&quot;Pamuk&quot;);<br>   student4.setGender(&#39;M&#39;);<br>   <br>   Student student5=new Student();<br>   student5.setFirstName(&quot;Stephen&quot;);<br>   student5.setLastName(&quot;Curry&quot;);<br>   student5.setGender(&#39;M&#39;);<br>   <br>   Student student6=new Student();<br>   student6.setFirstName(&quot;Lebron&quot;);<br>   student6.setLastName(&quot;James&quot;);<br>   student6.setGender(&#39;M&#39;);<br>   <br>   Student student7=new Student();<br>   student7.setFirstName(&quot;Marie&quot;);<br>   student7.setLastName(&quot;Curie&quot;);<br>   student7.setGender(&#39;F&#39;);<br><br><br>   StudentRepository.save(student);<br>   StudentRepository.save(student1);<br>   StudentRepository.save(student2);<br>   StudentRepository.save(student3);<br>   StudentRepository.save(student4);<br>   StudentRepository.save(student5);<br>   StudentRepository.save(student6);<br>   StudentRepository.save(student7);<br><br><br>  };<br> }<br><br>}</pre><h4>Postscript</h4><p>Access the Source Code on GitHub: If you’re interested in exploring the source code used in this article, you can find it all on my GitHub repository. Feel free to review, fork, or contribute to the code as needed. Visit <a href="https://github.com/berkaybarisalgun/Pagination-Example">Github </a>to access.</p><p>Additional information about application.properties . Don’t Forget to Configure Your application.properties: Before deploying your application, remember to configure your application.properties file with the appropriate database settings to ensure a seamless connection to your database. Also I used MySql so feel free to use any of database that you want.</p><p><strong><em>application.properties</em></strong></p><pre>spring.datasource.driver-class-name=com.mysql.jdbc.Driver<br>spring.datasource.url=jdbc:mysql://localhost:3306/example<br>spring.datasource.username=root<br>spring.datasource.password=admin<br><br>spring.jpa.hibernate.ddl-auto=create-drop<br>logging.level.org.hibernate.SQL=DEBUG<br>logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE</pre><ul><li>Mention that proper testing, validation and error handling of the pagination implementation are essential before deploying it to production. I just provided basic understanding of <strong><em>pagination</em></strong>.</li></ul><h4>Resources</h4><ul><li><a href="https://www.baeldung.com/spring-data-jpa-pagination-sorting">https://www.baeldung.com/spring-data-jpa-pagination-sorting</a></li><li><a href="https://www.bezkoder.com/spring-boot-pagination-filter-jpa-pageable/">https://www.bezkoder.com/spring-boot-pagination-filter-jpa-pageable</a></li><li><a href="https://www.youtube.com/watch?v=Wa0GQwWwzJE&amp;ab_channel=JavaTechie">https://www.youtube.com/watch?v=Wa0GQwWwzJE</a></li><li>Chatgpt</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=524083e699fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why do we need to override the equals and hashCode methods in Java?]]></title>
            <link>https://medium.com/@barisalgun/why-do-we-need-to-override-the-equals-and-hashcode-methods-in-java-50c31d6a2ce8?source=rss-3a27323cdf8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/50c31d6a2ce8</guid>
            <category><![CDATA[hashing]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[hashcode]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[equals]]></category>
            <dc:creator><![CDATA[Berkay Baris Algun]]></dc:creator>
            <pubDate>Tue, 29 Aug 2023 08:02:28 GMT</pubDate>
            <atom:updated>2023-08-29T08:02:28.720Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*ZEuDb5AblryuEvHdKJmXFA.png" /></figure><p>Have you ever tried comparing two objects that have the same characteristics? It’s possible that this led to an issue, even when both objects had the same characteristics. Let’s look at an example of this problem and try to understand how we can solve it.</p><p><strong>!!! Since I won’t be going deep, this article will only cover why we need to override the </strong><strong>equalsand </strong><strong>hashCodemethods, not how to do it. I’ll also provide resources for those interested in more detailed information on how to do it. !!!</strong></p><pre>public class Book {<br>    private String title;<br>    private String author;<br><br>    public Book(String title, String author) {<br>        this.title = title;<br>        this.author = author;<br>    }<br>}</pre><p>Check this Book class we just made, which has two attributes: title and author. Now, if we create two objects with the exact same title and author, and compare them, what do we expect to see? Let’s find out.</p><pre>public class Main {<br> public static void main(String[] args) {<br>  Book book1 = new Book(&quot;Crime and Punishment&quot;, &quot;Dostoyevski&quot;);<br>  Book book2 = new Book(&quot;Crime and Punishment&quot;, &quot;Dostoyevski&quot;);<br><br> System.out.println(book1.equals(book2));<br> }<br>}</pre><p>What do you think the output will be?<br>we would expect to see true but the answer is <strong>false.</strong></p><p>Now, let’s configure our Book class and check the output again.</p><pre> <br>    @Override<br>    public boolean equals(Object obj) {<br>        if (this == obj) return true;<br>        if (obj == null || getClass() != obj.getClass()) return false;<br>        Book book = (Book) obj;<br>        return Objects.equals(title, book.title) &amp;&amp;<br>               Objects.equals(author, book.author);<br>    }</pre><p>I’ve just added this equalsmethod to my class .Now, let’s re-run the application and see if anything has changed!</p><pre>public class Book {<br>    private String title;<br>    private String author;<br><br>    public Book(String title, String author) {<br>        this.title = title;<br>        this.author = author;<br>    }<br>    <br>    <br>    @Override<br>    public boolean equals(Object obj) {<br>        if (this == obj) return true;<br>        if (obj == null || getClass() != obj.getClass()) return false;<br>        Book book = (Book) obj;<br>        return Objects.equals(title, book.title) &amp;&amp;<br>               Objects.equals(author, book.author);<br>    }<br>}</pre><p>Here’s the Book class after we added the equals method. After executing the main class, we can observe that falsehas changed to <strong>true</strong>.</p><p>Many of us now get why we should change the equalsmethod. But now comes the main question: Why do we also need to override the hashCodemethod at the same time? Let’s look at an example.</p><pre>public class Main {<br> public static void main(String[] args) {<br>  Book book1 = new Book(&quot;The Gambler&quot;, &quot;Dostoyevsky&quot;);<br>  Book book2 = new Book(&quot;The Gambler&quot;, &quot;Dostoyevsky&quot;);<br><br>  Set&lt;Book&gt; bookSet = new HashSet&lt;&gt;();<br><br>  bookSet.add(book1);<br><br>  System.out.println(bookSet.contains(book2));<br> }<br>}</pre><p>In this code example, we create a bookSet which is a set and add the book1 object to it. Then we check if the book2 object is contained within the set. We would expect the result to be true because book1 and book2 have the same content. However, the output will show as false.</p><blockquote>The reason for this issue is that we did not correctly override the hashCode() method. Java collections first look at the hashCode values when searching for objects and then use the equals() method to compare the contents. Since we didn&#39;t override the hashCode() method correctly, different hashCode values are generated for book1 and book2. This leads to incorrect results when searching within the collection.</blockquote><p>Now, let’s add the hashCodemethod to our Book class and check again.</p><pre>@Override<br>    public int hashCode() {<br>        return Objects.hash(title, author);<br>    }</pre><p>Now, we can see that the output will be <strong>true.</strong></p><blockquote>In conclusion, correctly overriding the equals() and hashCode() methods together ensures that you can use your objects in collections accurately.</blockquote><p>Joshua Bloch says on Effective Java:</p><blockquote><em>You must override hashCode() in every class that overrides equals(). Failure to do so will result in a violation of the general contract for Object.hashCode(), which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable.</em></blockquote><h4>Book class:</h4><pre>public class Book {<br> private String title;<br> private String author;<br><br> public Book(String title, String author) {<br>  this.title = title;<br>  this.author = author;<br> }<br><br> @Override<br> public boolean equals(Object obj) {<br>  if (this == obj)<br>   return true;<br>  if (obj == null || getClass() != obj.getClass())<br>   return false;<br>  Book book = (Book) obj;<br>  return Objects.equals(title, book.title) &amp;&amp; Objects.equals(author, book.author);<br> }<br><br> @Override<br> public int hashCode() {<br>  return Objects.hash(title, author);<br> }<br><br>}</pre><h4>Main class:</h4><pre>public class Main {<br> public static void main(String[] args) {<br>  Book book1 = new Book(&quot;The Gambler&quot;, &quot;Dostoyevsky&quot;);<br>  Book book2 = new Book(&quot;The Gambler&quot;, &quot;Dostoyevsky&quot;);<br><br>  Set&lt;Book&gt; bookSet = new HashSet&lt;&gt;();<br><br>  bookSet.add(book1);<br><br>  System.out.println(bookSet.contains(book2));<br> }<br>}</pre><h4>For further information about <strong>how to do it</strong></h4><ul><li><a href="https://www.youtube.com/watch?v=8i1D-lbTKdw">https://www.youtube.com/watch?v=8i1D-lbTKdw</a></li><li><a href="https://www.baeldung.com/java-equals-hashcode-contracts">https://www.baeldung.com/java-equals-hashcode-contracts</a></li></ul><h3>Resources:</h3><ul><li><a href="https://stackoverflow.com/questions/2265503/why-do-i-need-to-override-the-equals-and-hashcode-methods-in-java">https://stackoverflow.com/questions/2265503/why-do-i-need-to-override-the-equals-and-hashcode-methods-in-java</a></li><li><a href="https://crunchify.com/how-to-override-equals-and-hashcode-method-in-java/">https://crunchify.com/how-to-override-equals-and-hashcode-method-in-java/</a></li><li>Chatgpt</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50c31d6a2ce8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OOP 4 Principles]]></title>
            <link>https://medium.com/@barisalgun/oop-4-principles-721448dc811e?source=rss-3a27323cdf8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/721448dc811e</guid>
            <category><![CDATA[encapsulation]]></category>
            <category><![CDATA[polymorphism]]></category>
            <category><![CDATA[abstraction]]></category>
            <category><![CDATA[inheritance]]></category>
            <category><![CDATA[oop]]></category>
            <dc:creator><![CDATA[Berkay Baris Algun]]></dc:creator>
            <pubDate>Fri, 25 Aug 2023 12:23:46 GMT</pubDate>
            <atom:updated>2023-08-28T04:52:49.735Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*zNTQXswnHTnnuaguTHP7LA.png" /></figure><p>Before I begin this article, I must mention that it has a unique aspect based on my experiences. It might sound confusing, but once you hear the story behind it, you will give me credit. :) Lately, I have been applying to many companies in order to secure an internship, which has resulted in numerous rejections. However, one company found my application valuable and invited me for an interview. Even though it wasn’t my first interview, I still felt a bit stressed. During the interview, they asked me a question related to the principles I had learned, and unfortunately, I failed to answer it completely. It was strange because I often use these concepts when I code or work on projects, but I hadn’t focused on the specific terms. I could have simply sat down on my couch and complained to myself, doing nothing about it. Instead, I felt it was more daring to address this topic by writing an article. Now that you know the story behind this, gear up because we are about to delve into the question that tripped me up!</p><p>Let’s get started with the 4 principles’ names:</p><h4>ABSTRACTION</h4><h4>INHERITANCE</h4><h4>POLYMORPHISM</h4><h4>ENCAPSULATION</h4><p>Before we delve into each one, let’s explore why we need these concepts. OOP concepts help us design software in a structured way. They make it easier to organize, reuse, and scale code. This leads to software that is easier to understand, maintain, and improve, resulting in more reliable and efficient development.</p><h3>ABSTRACTION</h3><p>Abstraction is a way to simplify complex systems by breaking them down into manageable parts that are easier to understand and use. It helps you focus on the important aspects while hiding unnecessary details, making your code more organized and easier to work with. I think it will be easier to understand with the code example I will give.</p><pre>abstract class Product {<br>        private String name;<br>        private double price;<br>    <br>        public Product(String name, double price) {<br>            this.name = name;<br>            this.price = price;<br>        }<br>    <br>        public abstract void display();<br>    <br>        public String getName() {<br>            return name;<br>        }<br>    <br>        public double getPrice() {<br>            return price;<br>        }<br>    }</pre><p>In this example, the abstract class Product represents a product in a market. It has two attributes: ‘name’ and ‘price’. It also declares an abstract method display().</p><pre>class Grocery extends Product {<br>        public Grocery(String name, double price) {<br>            super(name, price);<br>        }<br>    <br>        public void display() {<br>            System.out.println(&quot;Grocery - Name: &quot; + getName() + &quot;, Price: $&quot; + getPrice());<br>        }<br>    }</pre><p>In this example, the Product class is an abstract class, so it cannot be directly instantiated. However, the concrete classes Grocery can be instantiated by providing their specific details and calling their display() method to show the product information.</p><h4>OUTPUT:</h4><p>Grocery - Name: Apple, Price: $1.99</p><p>As a conclusion <em>abstraction</em> is a basic idea in object-oriented programming (OOP) that helps you create abstract classes with abstract methods. You can’t directly create objects from abstract classes, but they act as a template for making specific classes that inherit from them.</p><h3>INHERITANCE</h3><p>Inheritance lets you create a class based on another class. It’s like building a family tree of classes where they all have things in common, like attributes and methods. The following code is a code that gives an example of inheritance.</p><pre>abstract class Product {<br>        private String name;<br>        private double price;<br>    <br>        public Product(String name, double price) {<br>            this.name = name;<br>            this.price = price;<br>        }<br>    <br>        public abstract void display();<br>    <br>        public String getName() {<br>            return name;<br>        }<br>    <br>        public double getPrice() {<br>            return price;<br>        }<br>    }</pre><p>We define a parent class called Product that represents a generic product in a grocery store. It has two instance variables: name and price.</p><pre>// Parent class representing a product<br>    class Product {<br>        protected String name;<br>        protected double price;<br>    <br>        public Product(String name, double price) {<br>            this.name = name;<br>            this.price = price;<br>        }<br>    <br>        public void display() {<br>            System.out.println(&quot;Product: &quot; + name);<br>            System.out.println(&quot;Price: $&quot; + price);<br>        }<br>    }<br>    <br>    // Child class representing a grocery product<br>    class GroceryProduct extends Product {<br>        private String expirationDate;<br>    <br>        public GroceryProduct(String name, double price, String expirationDate) {<br>            super(name, price);<br>            this.expirationDate = expirationDate;<br>        }<br>    <br>        @Override<br>        public void display() {<br>            super.display();<br>            System.out.println(&quot;Expiration Date: &quot; + expirationDate);<br>        }<br>    }<br>    <br>    public class InheritanceExample {<br>        public static void main(String[] args) {<br>            Product product = new Product(&quot;Generic Product&quot;, 9.99);<br>            GroceryProduct groceryProduct = new GroceryProduct(&quot;Apple&quot;, 1.99, &quot;2023-06-30&quot;);<br>    <br>            product.display();<br>            System.out.println();<br>            groceryProduct.display();<br>        }<br>    }</pre><p>The ‘Product’ class has a constructor Product(String name, double price) that takes the name and price of the product as parameters and initializes the corresponding instance variables.</p><p>The code demonstrates the concept of <em>inheritance</em>, where the child class (GroceryProduct) inherits properties and methods from the parent class (Product). It showcases how the child class can extend the functionality of the parent class by adding its own attributes and behaviors. In this case, the child class adds the expirationDate attribute and overrides the display() method to include it in the output.</p><h3>POLYMORPHISM</h3><p>Polymorphism is like a programming trick that lets you treat different objects as if they were the same type. It’s useful because you can write code that works with different things in a similar way, making your code more versatile and easier to update.</p><pre>class Product {<br>    private String name;<br>    private double price;<br><br>    public Product(String name, double price) {<br>        this.name = name;<br>        this.price = price;<br>    }<br><br>    public void getInfo() {<br>        System.out.println(&quot;Product Name: &quot; + name);<br>        System.out.println(&quot;Price: $&quot; + price);<br>    }<br>}<br><br>class Grocery extends Product {<br>    private String expirationDate;<br><br>    public Grocery(String name, double price, String expirationDate) {<br>        super(name, price);<br>        this.expirationDate = expirationDate;<br>    }<br><br>    @Override<br>    public void getInfo() {<br>        super.getInfo();<br>        System.out.println(&quot;Expiration Date: &quot; + expirationDate);<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        Product product1 = new Product(&quot;Notebook&quot;, 899.99);<br>        Grocery grocery1 = new Grocery(&quot;Milk&quot;, 2.49, &quot;2023-08-30&quot;);<br>    }<br>}</pre><p>In this example, the “Product” class holds the basic attributes of a product, while the “Grocery” class extends “Product” and adds an expiration date. Both classes override the getInfo method to print their respective information.</p><h3>ENCAPSULATION</h3><p>Encapsulation is like putting your stuff in a backpack. You keep your things safe inside, and if someone needs something from your backpack, they ask you for it. They can’t just take things directly. In programming, it means packaging data and the actions you can do with that data together in a neat package. Other parts of the code have to ask nicely (use methods) to get or change the stuff inside, rather than messing with it directly. This keeps things organized and secure.</p><pre>class Product {<br>    private String name;<br>    private double price;<br><br>    public Product(String name, double price) {<br>        this.name = name;<br>        this.price = price;<br>    }<br><br>    public String getName() {<br>        return name;<br>    }<br><br>    public double getPrice() {<br>        return price;<br>    }<br><br>    public void setName(String name) {<br>        this.name = name;<br>    }<br><br>    public void setPrice(double price) {<br>        if (price &gt;= 0) {<br>            this.price = price;<br>        }<br>    }<br>}<br><br>class Grocery extends Product {<br>    private String expirationDate;<br><br>    public Grocery(String name, double price, String expirationDate) {<br>        super(name, price);<br>        this.expirationDate = expirationDate;<br>    }<br><br>    public String getExpirationDate() {<br>        return expirationDate;<br>    }<br><br>    public void setExpirationDate(String expirationDate) {<br>        this.expirationDate = expirationDate;<br>    }<br>}</pre><p>In this example, the attributes name and price are encapsulated within the &quot;<em>Product</em>&quot; class. They are made private, and getter and setter methods are provided to access and modify them, respectively. The same goes for the &quot;Grocery&quot; class, which extends the &quot;Product&quot; class and adds the expirationDate attribute.</p><h3>Resources</h3><ul><li><a href="https://khalilstemmler.com/articles/object-oriented/programming/4-principles/">https://khalilstemmler.com/articles/object-oriented/programming/4-principles/</a></li><li><a href="https://www.indeed.com/career-advice/career-development/what-is-object-oriented-programming">https://www.indeed.com/career-advice/career-development/what-is-object-oriented-programming</a></li><li><a href="https://www.freecodecamp.org/news/object-oriented-programming-concepts-21bb035f7260/">https://www.freecodecamp.org/news/object-oriented-programming-concepts-21bb035f7260/</a></li><li>Chatgpt</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=721448dc811e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>