<?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 Sarvar Musazade on Medium]]></title>
        <description><![CDATA[Stories by Sarvar Musazade on Medium]]></description>
        <link>https://medium.com/@sarvar55mszde?source=rss-4e7b1393b87c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uGe0xI8fnKRD93jcow6L6w.jpeg</url>
            <title>Stories by Sarvar Musazade on Medium</title>
            <link>https://medium.com/@sarvar55mszde?source=rss-4e7b1393b87c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 09:34:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sarvar55mszde/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[Concurrency Explained from Scratch — Part 1]]></title>
            <link>https://medium.com/@sarvar55mszde/concurrency-explained-from-scratch-part-1-37011fb1e118?source=rss-4e7b1393b87c------2</link>
            <guid isPermaLink="false">https://medium.com/p/37011fb1e118</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[cpu]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[threads]]></category>
            <dc:creator><![CDATA[Sarvar Musazade]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 21:39:05 GMT</pubDate>
            <atom:updated>2026-07-23T21:39:05.525Z</atom:updated>
            <content:encoded><![CDATA[<h3>Before We Talk About Threads, Understand the Computer</h3><blockquote>Most developers start learning concurrency by creating threads. The real question isn’t “How do threads work?” — it’s “Why do threads exist in the first place?”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3lm2PMhEdARLnMVTlyXzfQ.png" /></figure><h3>Introduction</h3><p>Concurrency is one of the most important concepts in modern software development. Whether you’re building a web application, a game engine, a database, or a distributed system, you’ll eventually encounter it.</p><p>However, many developers begin their journey by learning APIs such as Thread, ExecutorService, async, or synchronized. While these are valuable tools, they don&#39;t explain the fundamental problem they were designed to solve.</p><p>Before we talk about threads, locks, or asynchronous programming, we need to understand how a computer executes programs.</p><p>This article intentionally avoids Java and focuses on the underlying concepts that every software engineer should understand.</p><p>By the end of this article, you’ll clearly understand:</p><ul><li>What concurrency really means</li><li>Why concurrency exists</li><li>The difference between a program and a process</li><li>How an operating system starts an application</li><li>Why threads became necessary</li></ul><p>This is the first article in a series that gradually builds toward Java Concurrency.</p><h3>What Is Concurrency?</h3><p>One of the biggest misconceptions among developers is thinking that <strong>Concurrency</strong> and <strong>Parallelism</strong> are the same thing.</p><p>They are closely related, but they solve different problems.</p><p><strong>Concurrency</strong> is about managing multiple tasks during the same period of time.</p><p><strong>Parallelism</strong> is about executing multiple tasks at exactly the same time.</p><p>Although these definitions sound simple, they’re much easier to understand through an everyday example.</p><h3>A Restaurant Analogy</h3><p>Imagine a restaurant with only <strong>one waiter</strong> and <strong>four tables</strong>.</p><p>The waiter takes an order from the first table.</p><p>Before that table receives its food, the waiter walks to the second table and takes another order.</p><p>Then the third.</p><p>Then the fourth.</p><p>After that, the waiter returns to the first table with the food.</p><p>Throughout this entire process, the waiter continuously switches between tasks.</p><p>He isn’t serving all four tables simultaneously.</p><p>Instead, he’s making progress on multiple tasks by constantly moving from one to another.</p><p>This is <strong>Concurrency</strong>.</p><p>Now imagine the same restaurant, but this time there are <strong>four waiters</strong>.</p><p>Each waiter serves one table independently.</p><p>Now the work is literally happening at the same time.</p><p>This is <strong>Parallelism</strong>.</p><h3>Concurrency</h3><blockquote><em>Managing multiple tasks efficiently, even if only one task executes at any given moment.</em></blockquote><h3>Parallelism</h3><blockquote><em>Executing multiple tasks at the exact same time using multiple processing units.</em></blockquote><p>Understanding this distinction is critical because many programming languages — including Java — support concurrency even on machines that have only a single CPU core.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qE9Y9nwHiXGdTKsGt77Ymg.png" /></figure><h3>Why Do We Need Concurrency?</h3><p>Now let’s ask a more important question.</p><p><strong>Why was concurrency invented?</strong></p><p>Why don’t computers simply execute one task after another?</p><p>The answer is simple.</p><p>Because real-world software rarely performs only one task.</p><p>Imagine an e-commerce platform.</p><p>At this exact moment, hundreds or even thousands of users are:</p><ul><li>Logging into their accounts</li><li>Searching for products</li><li>Uploading profile pictures</li><li>Adding items to shopping carts</li><li>Completing payments</li><li>Writing reviews</li></ul><p>If the server processed these requests strictly one by one, every new customer would have to wait until the previous customer completely finished.</p><p>The application would quickly become unusable.</p><p>Modern software must handle many independent activities efficiently.</p><p>Concurrency is the solution to this problem.</p><p>It allows a system to make progress on multiple tasks instead of blocking everything behind a single operation.</p><h3>Before Understanding Processes, Understand Programs</h3><p>Most tutorials jump directly into explaining processes.</p><p>However, a process begins with something even more fundamental:</p><p>A <strong>program</strong>.</p><p>A program is simply a collection of instructions stored on disk.</p><p>For example:</p><pre>chrome.exe<br>spotify.exe<br>idea64.exe<br>photoshop.exe</pre><p>All of these are programs.</p><p>At this point, none of them are actually running.</p><p>They’re just files.</p><p>Inside those files are machine instructions, resources, metadata, and other information.</p><p>But they consume no CPU time.</p><p>They execute no instructions.</p><p>They perform no work.</p><p>Think of a program as a cookbook.</p><p>The recipes exist.</p><p>The instructions are written.</p><p>But no meal is being prepared.</p><p>The program is passive.</p><p>Nothing happens until someone starts it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cxWuqsYylouDZy5_2i0yfg.png" /></figure><h3>What Is a Process?</h3><p>The moment you launch a program, the operating system transforms it into a <strong>process</strong>.</p><p>This is where the interesting part begins.</p><p>The operating system performs several important tasks.</p><p>It:</p><ul><li>Allocates memory</li><li>Loads executable code into memory</li><li>Creates internal data structures</li><li>Assigns a unique Process ID (PID)</li><li>Opens required resources</li><li>Prepares the process for execution</li></ul><p>Only after these steps can the CPU begin executing instructions.</p><p>A process is therefore <strong>a running instance of a program</strong>.</p><p>Unlike a program, a process is active.</p><p>It has resources.</p><p>It owns memory.</p><p>It consumes CPU time.</p><p>It interacts with the operating system.</p><h3>What Does a Process Own?</h3><p>Every process has its own isolated environment.</p><p>Typically, a process owns:</p><ul><li>Its own virtual memory</li><li>Heap memory</li><li>One or more stacks</li><li>Open files</li><li>Network connections</li><li>Security information</li><li>Environment variables</li><li>Operating system resources</li></ul><p>This isolation is one of the reasons why applications generally don’t interfere with one another.</p><p>If one process crashes, the operating system can often terminate only that process while allowing others to continue running.</p><h3>One Program, Multiple Processes</h3><p>An important detail that surprises many beginners is that <strong>one program can create multiple processes</strong>.</p><p>For example, you might open Google Chrome several times.</p><p>Although every window comes from the same executable file, the operating system may create multiple independent processes.</p><p>Each process has:</p><ul><li>Its own memory</li><li>Its own resources</li><li>Its own execution state</li></ul><p>They all originate from the same program, but they are completely separate while running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XMaimfu10kPBZsX0kxJ5pw.png" /></figure><h3>If We Already Have Processes, Why Do We Need Threads?</h3><p>At this point, you might wonder:</p><blockquote><em>“If a process can already execute code, why did operating systems introduce threads?”</em></blockquote><p>This is one of the most important questions in computer science.</p><p>Imagine a modern web browser.</p><p>At the same time, it needs to:</p><ul><li>Download data from the internet</li><li>Render the user interface</li><li>Execute JavaScript</li><li>Decode images</li><li>Play videos</li><li>Respond to keyboard and mouse events</li></ul><p>If all of these responsibilities were handled through a single execution path, the browser would frequently become unresponsive.</p><p>For example, downloading a large file could temporarily freeze the entire interface.</p><p>Clearly, this isn’t acceptable.</p><p>Operating systems needed a more flexible way to execute multiple independent activities inside a single process.</p><p>That solution is the <strong>thread</strong>.</p><p>We’ll explore threads in detail in the next article.</p><h3>Key Takeaways</h3><p>Before learning Java concurrency, it’s essential to understand the foundation on which it is built.</p><p>In this article, we learned that:</p><ul><li>Concurrency is about managing multiple tasks efficiently.</li><li>Parallelism is about executing multiple tasks simultaneously.</li><li>A program is a passive file stored on disk.</li><li>A process is a running instance of a program.</li><li>Every process owns its own resources and memory.</li><li>Threads were introduced to allow multiple execution paths inside a single process.</li></ul><p>Understanding these concepts first will make every future concurrency topic significantly easier.</p><h3>What’s Next?</h3><p>In <strong>Part 2</strong>, we’ll answer some of the most common questions developers have about threads:</p><ul><li>What exactly is a thread?</li><li>Why can one process have multiple threads?</li><li>What resources do threads share?</li><li>Why does every thread have its own stack?</li><li>How does the operating system schedule threads?</li><li>How does the CPU decide which thread runs next?</li></ul><p>Once we understand threads, we’ll be ready to explore how Java builds its concurrency model on top of these operating system concepts.</p><blockquote><strong><em>Series Roadmap</em></strong></blockquote><ul><li>✅ Part 1 — Before We Talk About Threads, Understand the Computer</li><li>⏳ Part 2 — Program vs Process vs Thread</li><li>⏳ Part 3 — Inside the CPU: Cores, Cache, Registers, and Execution</li><li>⏳ Part 4 — CPU-Bound vs I/O-Bound Workloads</li><li>⏳ Part 5 — Context Switching Explained</li><li>⏳ Part 6 — Finally… Java Threads</li></ul><p>📸 I also share software architecture diagrams, Java internals, and backend engineering content on Instagram: **@the.code.architect** See you in the next article!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37011fb1e118" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java’s Invisible Tax: The Performance Cost You’re Paying Without Knowing It]]></title>
            <link>https://medium.com/@sarvar55mszde/javas-invisible-tax-the-performance-cost-you-re-paying-without-knowing-it-cda95dcc5ec0?source=rss-4e7b1393b87c------2</link>
            <guid isPermaLink="false">https://medium.com/p/cda95dcc5ec0</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[effective]]></category>
            <dc:creator><![CDATA[Sarvar Musazade]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 19:21:42 GMT</pubDate>
            <atom:updated>2026-07-23T19:21:42.784Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A closer look at Effective Java, Item 6: the word “new” isn’t as innocent as it looks.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*91Dep96XZQNWLIzBpLSJPw.png" /></figure><h3>Take a minute and look at this code</h3><pre>for (int i = 0; i &lt; 1_000_000; i++) {<br>    String s = new String(&quot;hello&quot;);<br>}</pre><p>How many times did this loop run? A million. How many &quot;hello&quot; strings did you actually need? <strong>Just one.</strong></p><p>But the JVM created 999,999 extra objects for you. None of them were used. All of them became garbage the moment they were born, waiting for the Garbage Collector to clean them up.</p><p>This is the essence of Item 6 in Joshua Bloch’s <em>Effective Java</em>: <strong>“Avoid creating unnecessary objects.”</strong></p><p>Sounds simple, right? But that one sentence is at the root of countless “why is our app suddenly slow, why is GC running so often” debugging sessions in production.</p><h3>The theory: why isn’t creating an object “free”?</h3><p>Every new call in Java triggers:</p><ul><li><strong>Memory allocation on the heap</strong></li><li><strong>Object initialization</strong> (constructor runs, fields get set)</li><li><strong>Work for the Garbage Collector</strong> — finding and cleaning up an object once it’s no longer used isn’t free either</li></ul><p>Creating a single object takes microseconds — it doesn’t matter on its own. But repeat that “insignificant” cost inside a loop, or on every single request to a REST API handling thousands of calls per second, and it adds up into a real performance problem.</p><p>Picture it visually: on one side, a single object built once and reused again and again. On the other, objects rebuilt on every request and torn down immediately, flooding the GC queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PYzXl3J3_VwCgNPrbxtU3g.png" /></figure><h3>Classic mistakes: 3 things almost everyone has done once</h3><h3>1. Creating a String with new</h3><pre>// ❌ Bad: creates a brand-new object every time<br>String s1 = new String(&quot;hello&quot;);</pre><pre>// ✅ Good: reuses the same reference from the String pool<br>String s2 = &quot;hello&quot;;</pre><p>Java already keeps string literals in a <strong>String Pool</strong> and reuses them. new String(...) deliberately bypasses this mechanism and creates an unnecessary duplicate.</p><h3>2. The autoboxing trap</h3><pre>// ❌ Bad: a new Long object is created on every addition<br>Long sum = 0L;<br>for (long i = 0; i &lt; 1_000_000_000; i++) {<br>    sum += i; // unboxing + boxing happens every single time<br>}</pre><pre>// ✅ Good: use the primitive type<br>long sum = 0L;<br>for (long i = 0; i &lt; 1_000_000_000; i++) {<br>    sum += i;<br>}</pre><p>Using long instead of Long looks like a minor detail, but across a billion iterations the difference becomes measurable in minutes, not milliseconds.</p><h3>3. Recreating heavyweight objects inside a loop or method</h3><pre>// ❌ Bad: the regex gets recompiled on every call<br>public boolean isValidEmail(String email) {<br>    return email.matches(&quot;^[A-Za-z0-9+_.-]+@(.+)$&quot;);<br>}</pre><p>Every call to String.matches() triggers a Pattern.compile() behind the scenes. Compiling a regex is far more expensive than a simple string comparison. Run this line once and it&#39;s harmless — but call it thousands of times per second on an API endpoint, and it becomes a real bottleneck.</p><h3>The practice: how do you actually fix this?</h3><pre>// ✅ Good: the Pattern is created once and reused forever<br>private static final Pattern EMAIL_PATTERN =<br>        Pattern.compile(&quot;^[A-Za-z0-9+_.-]+@(.+)$&quot;);</pre><pre>public boolean isValidEmail(String email) {<br>    return EMAIL_PATTERN.matcher(email).matches();<br>}</pre><p>This mirrors exactly what Effective Java recommends as a general principle: <strong>pre-create immutable, reusable objects as </strong><strong>static final fields instead of rebuilding them every time.</strong></p><p>The same logic applies to:</p><ul><li>SimpleDateFormat / DateTimeFormatter instances</li><li>Fixed collections (List.of(...), Map.of(...))</li><li>Heavy configuration objects (like an ObjectMapper)</li></ul><h3>Real-world example: email validation in a Spring Boot service</h3><p>Say you’re building a user registration service. On every signup request, you validate the email format.</p><p><strong>Before (common, “it works but it’s slow” version):</strong></p><pre>@Service<br>public class UserRegistrationService {</pre><pre>    public void register(String email, String password) {<br>        if (!email.matches(&quot;^[A-Za-z0-9+_.-]+@(.+)$&quot;)) {<br>            throw new IllegalArgumentException(&quot;Invalid email&quot;);<br>        }<br>        // registration logic...<br>    }<br>}</pre><p>If this service handles 10 requests a day, you’ll never notice anything. But at 500,000 signups a day, recompiling the regex on every single request quietly burns CPU time you didn’t need to spend.</p><p><strong>After (aligned with Effective Java, Item 6):</strong></p><pre>@Service<br>public class UserRegistrationService {</pre><pre>    private static final Pattern EMAIL_PATTERN =<br>            Pattern.compile(&quot;^[A-Za-z0-9+_.-]+@(.+)$&quot;);</pre><pre>    public void register(String email, String password) {<br>        if (!EMAIL_PATTERN.matcher(email).matches()) {<br>            throw new IllegalArgumentException(&quot;Invalid email&quot;);<br>        }<br>        // registration logic...<br>    }<br>}</pre><p>A one-line change. But now:</p><ul><li>The regex is compiled <strong>once</strong>, at application startup.</li><li>Every request just reuses the already-compiled Pattern.</li><li>Under high traffic, CPU usage and GC pressure both drop noticeably.</li></ul><p>If you want to see this for yourself, write a small JMH (Java Microbenchmark Harness) benchmark comparing both versions — regex compilation is expensive enough that the difference shows up even on a single request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*laC6gmi8keTHAKIqO8JJZg.png" /></figure><h3>So should you optimize everything?</h3><p>No — and this balance is something Joshua Bloch is careful to point out in the same item. Avoiding unnecessary object creation doesn’t mean <strong>avoiding every expensive operation</strong>. Micro-optimizing a rarely-called method at the cost of readability, when performance isn’t even a concern there, is usually wasted effort.</p><p>The rule of thumb:</p><ul><li>🔁 <strong>On a hot path — inside a loop or high-traffic code</strong> → think about reusing objects.</li><li>🐌 <strong>On a rarely-executed, non-performance-critical path</strong> → prioritize readability, don’t chase micro-optimizations.</li></ul><h3>Key takeaways</h3><ul><li>Every new call isn&#39;t free — it means heap allocation plus GC work.</li><li>Don’t recreate expensive, immutable objects like String, Pattern, or SimpleDateFormat inside loops or methods; create them once as static final.</li><li>Autoboxing (Long, Integer, etc.) is a hidden cost in tight loops; use primitive types where you can.</li><li>Optimization isn’t needed everywhere — focus on hot code paths, keep readability everywhere else.</li></ul><p>Next time you spot a new in your code, ask yourself: <em>&quot;Do I really need a fresh instance every time, or can I create this once and reuse it?&quot;</em></p><p>That one question can save you hours of production debugging before you’ve even shipped the code.</p><p><em>This piece covers Item 6 — “Avoid creating unnecessary objects” — from Joshua Bloch’s Effective Java. Coming up next in the series: Builder Pattern, Immutability, and Generics.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cda95dcc5ec0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enforce Noninstantiability With a Private Constructor — Effective Java Item 4]]></title>
            <link>https://medium.com/@sarvar55mszde/enforce-noninstantiability-with-a-private-constructor-effective-java-item-4-afd9c4b58964?source=rss-4e7b1393b87c------2</link>
            <guid isPermaLink="false">https://medium.com/p/afd9c4b58964</guid>
            <category><![CDATA[effective-java]]></category>
            <category><![CDATA[utilities]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Sarvar Musazade]]></dc:creator>
            <pubDate>Wed, 27 May 2026 12:27:47 GMT</pubDate>
            <atom:updated>2026-05-27T12:27:47.555Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone! Today we are going to learn one of the shortest but most misunderstood items in Effective Java. It is about a class that should never be instantiated — and how to make sure nobody ever does it by accident.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*00vwfzSHCARwWrA14XI_LQ.png" /></figure><h3>The Story — A Utility Class</h3><p>You are building a project. You need a bunch of helper methods — things that do not belong to any specific object. Methods like:</p><pre>// Convert Celsius to Fahrenheit<br>// Validate an email format<br>// Format a price with currency symbol<br>// Check if a string is blank or null</pre><p><strong>These methods do not need any state.</strong> <strong>They do not need to be part of an object.</strong> They are just standalone tools.</p><p>So you create a utility class:</p><pre>public class StringUtils {<br>public static boolean isBlank(String value) {<br>        return value == null || value.trim().isEmpty();<br>    }<br>    public static String capitalize(String value) {<br>        if (isBlank(value)) return value;<br>        return Character.toUpperCase(value.charAt(0)) + value.substring(1);<br>    }<br>    public static String truncate(String value, int maxLength) {<br>        if (value == null) return null;<br>        return value.length() &lt;= maxLength ? value : value.substring(0, maxLength) + &quot;...&quot;;<br>    }<br>}</pre><p>You use it like this:</p><pre>String name = StringUtils.capitalize(&quot;john&quot;);      // &quot;John&quot;<br>boolean empty = StringUtils.isBlank(&quot;  &quot;);          // true<br>String preview = StringUtils.truncate(&quot;Hello World&quot;, 5); // &quot;Hello...&quot;</pre><p>Clean. Static methods. No instance needed.</p><p>But there is a problem hiding here. Can you spot it?</p><h3>The Problem — Anyone Can Do This</h3><pre>StringUtils utils = new StringUtils();</pre><p>This compiles. It runs. It creates an object.</p><p>But that object is <strong>completely useless</strong>. StringUtils <strong>has no fields, no state, no instance methods. </strong>Creating an instance of it makes zero sense — it is like buying a toolbox just to look at it without using any tools.</p><p>Worse, your IDE might even suggest it:</p><pre>StringUtils utils = new StringUtils();<br>utils.isBlank(&quot;test&quot;);   // This compiles — but isBlank is static!<br>                         // You are calling a static method on an instance.<br>                         // Misleading and confusing.</pre><p>This confuses readers of your code. It suggests StringUtils is supposed to be instantiated and used as an object. It is not.</p><h3>Why Does Java Allow This?</h3><p>Because <strong>Java automatically provides a default no-argument constructor</strong> if you do not define any constructor yourself.</p><pre>// What you wrote:<br>public class StringUtils {<br>    public static boolean isBlank(String value) { ... }<br>}</pre><pre>// What the compiler generates invisibly:<br>public class StringUtils {</pre><pre>    public StringUtils() {}  // ← added by the compiler automatically<br>                             // public! anyone can call it!</pre><pre>    public static boolean isBlank(String value) { ... }<br>}</pre><p>You never asked for a constructor. The compiler added one anyway. And because it is public, anyone can instantiate your class — even though that was never your intention.</p><p><em>Effective Java</em> points this out clearly:</p><blockquote>“A default constructor is generated only if a class contains no explicit constructors, so a class can be made noninstantiable by including a private constructor.”</blockquote><h3>The Naive Fix That Does Not Work — abstract</h3><p>Your first instinct might be to make the class abstract:</p><pre>public abstract class StringUtils {<br>    public static boolean isBlank(String value) { ... }<br>}</pre><p>This prevents direct instantiation:</p><pre>StringUtils utils = new StringUtils(); // ❌ compile error — cannot instantiate abstract class</pre><p>But it invites a different problem:</p><pre>public class MyStringUtils extends StringUtils {<br>    // empty subclass — just to get around the abstract restriction<br>}</pre><pre>MyStringUtils utils = new MyStringUtils(); // ✅ compiles and runs!</pre><p>Someone can subclass your utility class, create an instance of the subclass, and get around your restriction entirely. Making a class abstract does not enforce noninstantiability — it only delays it.</p><p>It also sends the wrong message. abstract usually means: <em>&quot;I am designed to be subclassed.&quot;</em> But a utility class should never be subclassed. Putting abstract on it misleads other developers into thinking inheritance is intended.</p><h3>The Correct Fix — Private Constructor</h3><p>The right solution is simple. Add a constructor yourself — and make it private:</p><pre>public class StringUtils {<br>// ✅ Private constructor - prevents instantiation<br>    private StringUtils() {<br>        throw new AssertionError(&quot;StringUtils is a utility class and cannot be instantiated&quot;);<br>    }<br>    public static boolean isBlank(String value) {<br>        return value == null || value.trim().isEmpty();<br>    }<br>    public static String capitalize(String value) {<br>        if (isBlank(value)) return value;<br>        return Character.toUpperCase(value.charAt(0)) + value.substring(1);<br>    }<br>    public static String truncate(String value, int maxLength) {<br>        if (value == null) return null;<br>        return value.length() &lt;= maxLength ? value : value.substring(0, maxLength) + &quot;...&quot;;<br>    }<br>}</pre><p>Now:</p><pre>StringUtils utils = new StringUtils();<br>// ❌ Compile error: StringUtils() has private access</pre><p>Nobody can instantiate it. Not from outside the class, not from a subclass. The private constructor does two things at once:</p><p><strong>It blocks direct instantiation</strong> — new StringUtils() is a compile error outside the class.</p><p><strong>It blocks subclassing</strong> — every constructor in a subclass must call super(). But super() would reach the private constructor in StringUtils, which is inaccessible. So no subclass can be created either.</p><pre>public class MyStringUtils extends StringUtils {<br>// ❌ Compile error: StringUtils() has private access<br>// Cannot call super() — the only constructor is private<br>}</pre><h3>Why the AssertionError?</h3><p>You might wonder: if the constructor is private, nobody outside can call it. Why throw an AssertionError?</p><p>Because someone <strong>inside</strong> the class could accidentally call it. For example, another static method inside StringUtils that does new StringUtils(). Or a future developer who adds instance logic without thinking.</p><p>The AssertionError is a safety net for that case. If anyone inside the class ever tries to instantiate it — even by mistake — they see a clear message immediately:</p><pre>java.lang.AssertionError: StringUtils is a utility class and cannot be instantiated</pre><p>No ambiguity. No silent bug. The intent is clear.</p><h3>Real Examples You Already Know</h3><p>This pattern is everywhere in Java’s standard library. You just never noticed it before.</p><pre>// java.lang.Math — all static, never instantiated<br>public final class Math {<br>    private Math() {}  // ← private constructor, no body, no error message<br>    <br>    public static double sqrt(double a) { ... }<br>    public static double pow(double a, double b) { ... }<br>    public static int abs(int a) { ... }<br>    // ...<br>}</pre><pre>// java.util.Arrays — all static utility methods<br>public class Arrays {<br>    private Arrays() {}<br>    <br>    public static void sort(int[] a) { ... }<br>    public static &lt;T&gt; List&lt;T&gt; asList(T... a) { ... }<br>    // ...<br>}</pre><pre>// java.util.Collections — all static utility methods<br>public class Collections {<br>    private Collections() {}<br>    <br>    public static &lt;T&gt; List&lt;T&gt; unmodifiableList(List&lt;T&gt; list) { ... }<br>    public static void shuffle(List&lt;?&gt; list) { ... }<br>    // ...<br>}</pre><p>Every one of them uses a private constructor. Not because they needed one — but because they needed to prevent one from being created automatically.</p><h3>Your Own Real-World Examples</h3><p>Let’s see a few more realistic utility classes from a typical Spring Boot project.</p><h3>Example 1 — DateUtils</h3><pre>public final class DateUtils {<br>private DateUtils() {<br>        throw new AssertionError(&quot;DateUtils cannot be instantiated&quot;);<br>    }<br>    public static boolean isWeekend(LocalDate date) {<br>        DayOfWeek day = date.getDayOfWeek();<br>        return day == DayOfWeek.SATURDAY || day == DayOfWeek.SUNDAY;<br>    }<br>    public static long daysBetween(LocalDate from, LocalDate to) {<br>        return ChronoUnit.DAYS.between(from, to);<br>    }<br>    public static String formatForDisplay(LocalDateTime dateTime) {<br>        return dateTime.format(DateTimeFormatter.ofPattern(&quot;dd MMM yyyy, HH:mm&quot;));<br>    }<br>}</pre><p>Usage:</p><pre>boolean isWeekend = DateUtils.isWeekend(LocalDate.now());<br>long days = DateUtils.daysBetween(LocalDate.of(2025, 1, 1), LocalDate.now());<br>String label = DateUtils.formatForDisplay(LocalDateTime.now());</pre><h3>Example 2 — ValidationUtils</h3><pre>public final class ValidationUtils {<br>private ValidationUtils() {<br>        throw new AssertionError(&quot;ValidationUtils cannot be instantiated&quot;);<br>    }<br>    public static boolean isValidEmail(String email) {<br>        if (email == null) return false;<br>        return email.matches(&quot;^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$&quot;);<br>    }<br>    public static boolean isValidPhoneNumber(String phone) {<br>        if (phone == null) return false;<br>        return phone.matches(&quot;^\\+?[0-9]{7,15}$&quot;);<br>    }<br>    public static boolean isStrongPassword(String password) {<br>        if (password == null || password.length() &lt; 8) return false;<br>        boolean hasUpper   = password.chars().anyMatch(Character::isUpperCase);<br>        boolean hasLower   = password.chars().anyMatch(Character::isLowerCase);<br>        boolean hasDigit   = password.chars().anyMatch(Character::isDigit);<br>        return hasUpper &amp;&amp; hasLower &amp;&amp; hasDigit;<br>    }<br>}</pre><p>Usage:</p><pre>if (!ValidationUtils.isValidEmail(request.getEmail())) {<br>    throw ApiException.validationError(Map.of(&quot;email&quot;, &quot;Invalid email format&quot;));<br>}<br>if (!ValidationUtils.isStrongPassword(request.getPassword())) {<br>    throw ApiException.validationError(Map.of(&quot;password&quot;, &quot;Password is too weak&quot;));<br>}</pre><h3>Example 3 — JsonUtils</h3><pre>public final class JsonUtils {<br> private static final ObjectMapper MAPPER = new ObjectMapper();<br>    private JsonUtils() {<br>        throw new AssertionError(&quot;JsonUtils cannot be instantiated&quot;);<br>    }<br>    public static String toJson(Object object) {<br>        try {<br>            return MAPPER.writeValueAsString(object);<br>        } catch (JsonProcessingException e) {<br>            throw new IllegalArgumentException(&quot;Cannot serialize to JSON: &quot; + object, e);<br>        }<br>    }<br>    public static &lt;T&gt; T fromJson(String json, Class&lt;T&gt; type) {<br>        try {<br>            return MAPPER.readValue(json, type);<br>        } catch (JsonProcessingException e) {<br>            throw new IllegalArgumentException(&quot;Cannot deserialize JSON: &quot; + json, e);<br>        }<br>    }<br>}</pre><p>Usage:</p><pre>String json    = JsonUtils.toJson(user);<br>User   user    = JsonUtils.fromJson(json, User.class);</pre><p>Notice MAPPER is a private static final field — one shared instance. If JsonUtils could be instantiated, every instance would have its own MAPPER. But because it cannot be instantiated, there is exactly one MAPPER for the entire application. This is another benefit of enforcing noninstantiability.</p><h3>The final Keyword on the Class</h3><p>You will notice the examples above use public final class. The final keyword on a class prevents subclassing completely — at the compiler level, regardless of constructor visibility.</p><p>Should you always add final to utility classes?</p><pre>private constructor alone:<br>  ✅ Prevents instantiation<br>  ✅ Prevents subclassing (because super() is inaccessible)<br>  ⚠️  The &quot;final&quot; intent is enforced at runtime, not compile time</pre><pre>private constructor + final:<br>  ✅ Prevents instantiation<br>  ✅ Prevents subclassing — at compile time, with a clear error message<br>  ✅ Communicates intent immediately to anyone reading the class</pre><p>Add final. It costs nothing. It communicates that this class is a closed, finished utility — not a base for inheritance.</p><h3>❗ Common Mistakes</h3><p><strong>1. Relying on abstract to prevent instantiation</strong> abstract prevents direct instantiation but allows subclassing. Anyone can create a subclass and instantiate that. It also sends the wrong signal — abstract means &quot;designed for inheritance,&quot; which is the opposite of what a utility class is.</p><p><strong>2. Not adding the AssertionError</strong> A private constructor with no body is legal and stops outsiders. But if someone inside the class ever calls new StringUtils() by mistake, nothing tells them why it is wrong. The AssertionError makes the intent crystal clear.</p><p><strong>3. Adding instance methods to a utility class</strong> If a class has a private constructor for noninstantiability, it should have no instance methods. Instance methods on a noninstantiable class make no sense — they can never be called on an instance. If you find yourself adding instance methods, reconsider whether the class should be a utility class at all.</p><p><strong>4. Forgetting the Javadoc comment</strong> The private constructor surprises developers who have not seen this pattern before. A one-line comment removes all confusion:</p><pre>// Utility class — do not instantiate<br>private StringUtils() {<br>    throw new AssertionError(&quot;StringUtils cannot be instantiated&quot;);<br>}</pre><p><strong>5. Making utility classes stateful</strong> If your utility class has mutable static fields, multiple threads accessing it can cause race conditions. Utility classes should be stateless — only static methods, no mutable static state. If you need state, use a @Service or @Component bean instead.</p><h3>💡 Practical Tips</h3><ul><li>Always add final to utility classes alongside the private constructor. Two layers of protection, zero extra cost.</li><li>Name your utility classes clearly — StringUtils, DateUtils, FileUtils, ValidationUtils. The Utils suffix signals to every developer that this class is a toolbox, not an object.</li><li>Keep utility methods truly stateless. If a method needs configuration or mutable state, it belongs in a Spring-managed bean — not a static utility class.</li><li>In Spring Boot projects, prefer Spring beans over utility classes for anything that needs external dependencies (database, config, other services). Use utility classes only for pure logic that depends on nothing external.</li></ul><h3>Summary</h3><p>Every Java class without an explicit constructor gets a public default constructor for free — added silently by the compiler. For utility classes full of static methods, this default constructor is unwanted and misleading.</p><p>Making the class abstract does not solve the problem. It prevents direct instantiation but allows subclassing — anyone can create an empty subclass and instantiate that instead.</p><p>The correct solution is a single private constructor with a descriptive AssertionError. This prevents instantiation from outside the class and prevents subclassing entirely — because every subclass constructor must call super(), which is now inaccessible. Adding final to the class declaration reinforces this intent at the compiler level.</p><p>The Java standard library does this in Math, Arrays, Collections, and many others. It is a small pattern — one constructor, one line — but it makes your class&#39;s intent unambiguous to every developer who reads it.</p><p><em>Found this useful? Hit the clap button 👏.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afd9c4b58964" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Core — IoC, Dependency Injection, IoC Container, and ApplicationContext]]></title>
            <link>https://medium.com/@sarvar55mszde/spring-core-ioc-dependency-injection-ioc-container-and-applicationcontext-134fd2754393?source=rss-4e7b1393b87c------2</link>
            <guid isPermaLink="false">https://medium.com/p/134fd2754393</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[ioc-container]]></category>
            <category><![CDATA[beans]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Sarvar Musazade]]></dc:creator>
            <pubDate>Sat, 23 May 2026 16:52:19 GMT</pubDate>
            <atom:updated>2026-05-23T16:52:19.185Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone! Today we are going to learn the heart of Spring Framework. Not just what these words mean — but why they exist, what problems they solve, and how they work together. Every concept will be shown with real code, from the pain of doing it manually to the elegance of letting Spring handle it. ☕</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*pLV4eqQyq5Ft1YZ9HuuyfA.png" /></figure><h3>Part 1 — The World Without Spring</h3><p>Before we touch Spring at all, let’s build something real. From scratch. The way you would do it without any framework.</p><h3>The Story — A Simple Order System</h3><p>You are building an order system. When a user places an order, you need to:</p><ul><li>Save it to a database (via OrderRepository)</li><li>Send a confirmation email (via EmailService)</li><li>Record it for analytics (via AnalyticsService)</li></ul><p>You write these classes:</p><pre>// Sends emails<br>public class EmailService {<br>    public void sendConfirmation(String email, String orderId) {<br>        System.out.println(&quot;Sending email to &quot; + email + &quot; for order &quot; + orderId);<br>    }<br>}</pre><pre>// Records analytics<br>public class AnalyticsService {<br>    public void record(String orderId, double amount) {<br>        System.out.println(&quot;Recording sale: &quot; + orderId + &quot; — $&quot; + amount);<br>    }<br>}</pre><pre>// Saves orders to database<br>public class OrderRepository {<br>    public void save(Order order) {<br>        System.out.println(&quot;Saving order: &quot; + order.getId());<br>    }<br>}</pre><pre>// The main service — uses all three above<br>public class OrderService {<br>    private EmailService     emailService;<br>    private AnalyticsService analyticsService;<br>    private OrderRepository  orderRepository;<br><br>public void placeOrder(Order order) {<br>        orderRepository.save(order);<br>        emailService.sendConfirmation(order.getUserEmail(), order.getId());<br>        analyticsService.record(order.getId(), order.getAmount());<br>    }<br>}</pre><p>Now in main(), you wire everything together:</p><pre>public class Main {<br>    public static void main(String[] args) {<br>    // You create every object manually<br>        EmailService     emailService     = new EmailService();<br>        AnalyticsService analyticsService = new AnalyticsService();<br>        OrderRepository  orderRepository  = new OrderRepository();<br>        // You manually give OrderService its dependencies<br>        OrderService orderService = new OrderService();<br>        orderService.setEmailService(emailService);<br>        orderService.setAnalyticsService(analyticsService);<br>        orderService.setOrderRepository(orderRepository);<br>        // Now you can use it<br>        Order order = new Order(&quot;ord-1&quot;, &quot;john@example.com&quot;, 99.99);<br>        orderService.placeOrder(order);<br>    }<br>}</pre><p>This works. But now let’s talk about what is actually wrong here.</p><h3>Problem 1 — You Are the Assembly Line</h3><p>Look at main(). It is doing three things at once:</p><ul><li>Creating objects</li><li>Connecting objects to each other</li><li>Running business logic</li></ul><p>As your application grows, main() becomes a monster:</p><pre>public static void main(String[] args) {<br>    // Creating dozens of objects...<br>    DatabaseConfig   dbConfig        = new DatabaseConfig(&quot;localhost&quot;, 5432);<br>    ConnectionPool   connectionPool  = new ConnectionPool(dbConfig, 10);<br>    UserRepository   userRepository  = new UserRepository(connectionPool);<br>    OrderRepository  orderRepository = new OrderRepository(connectionPool);<br>    EmailConfig      emailConfig     = new EmailConfig(&quot;smtp.gmail.com&quot;, 587);<br>    EmailService     emailService    = new EmailService(emailConfig);<br>    AnalyticsService analyticsService = new AnalyticsService();<br>    PaymentGateway   paymentGateway  = new PaymentGateway(&quot;api-key-123&quot;);<br>    OrderService     orderService    = new OrderService(<br>        orderRepository, emailService, analyticsService, paymentGateway<br>    );<br>    UserService      userService     = new UserService(userRepository, emailService);<br>    // ... and it goes on forever<br>}</pre><p>You are now a human dependency wiring machine. And this is not even a big application.</p><h3>Problem 2 — OrderService Knows Too Much</h3><p>Look at the original OrderService:</p><pre>public class OrderService {<br>    public void placeOrder(Order order) {<br>        // OrderService creates its own dependencies!<br>        EmailService emailService = new EmailService();<br>        emailService.sendConfirmation(order.getUserEmail(), order.getId());<br>    }<br>}</pre><p>Or even worse — some developers put the new keyword right inside the service:</p><pre>public class OrderService {<br>    // Hardcoded dependency — created inside the class<br>    private EmailService emailService = new EmailService();<br>}</pre><p>Now OrderService is responsible for both <strong>using</strong> EmailService and <strong>creating</strong> it. These are two completely different responsibilities. And this creates a serious problem.</p><h3>Problem 3 — Impossible to Test</h3><p>Imagine you want to write a test for OrderService. You do not want to actually send real emails during testing. But because OrderService creates new EmailService() internally, you cannot replace it with a fake one.</p><pre>// You want to test just the order logic — no real emails<br>@Test<br>public void testPlaceOrder() {<br>    OrderService orderService = new OrderService();<br>    // ❌ Can&#39;t replace EmailService with a mock<br>    // ❌ Every test run sends real emails to real people<br>    // ❌ Tests depend on email server being available<br>    orderService.placeOrder(new Order(...));<br>}</pre><p>Your test is now fragile, slow, and sends spam. All because OrderService created its own dependency.</p><h3>Problem 4 — Change Ripples Everywhere</h3><p>EmailService needs a configuration object now:</p><pre>public class EmailService {<br>    private EmailConfig config;<br> public EmailService(EmailConfig config) {   // constructor changed!<br>        this.config = config;<br>    }<br>}</pre><p>Now every single class that does new EmailService() is broken:</p><pre>// ❌ Compile error everywhere<br>private EmailService emailService = new EmailService();<br>//                                  ^^^^^^^^^^^^^^^^^<br>// Constructor EmailService() doesn&#39;t exist anymore</pre><p>You have to find every place in your codebase that creates EmailService and fix it. In a large project, this could be dozens of files.</p><h3>The Root Cause of All These Problems</h3><p>Every problem above comes from the same mistake:</p><p><strong>Classes are creating their own dependencies.</strong></p><p>OrderService should not know how to create EmailService. It should just <em>receive</em> a ready-to-use EmailService and call it.</p><p>This insight is what <strong>Dependency Injection</strong> and <strong>Inversion of Control</strong> are all about.</p><h3>Part 2 — Inversion of Control (IoC)</h3><h3>What Does “Control” Mean?</h3><p>In the broken code above, OrderService is in control:</p><pre>Normal flow (without IoC):<br>OrderService decides:<br>  ✦ &quot;I need an EmailService&quot;<br>  ✦ &quot;I will create it myself&quot;<br>  ✦ &quot;I will choose which implementation to use&quot;<br>  ✦ new EmailService()</pre><p>OrderService has full control over what it depends on and how it gets created.</p><p><strong>IoC flips this:</strong></p><pre>Inverted flow (with IoC):<br>OrderService says:<br>  ✦ &quot;I need something that can send emails&quot;<br>  ✦ &quot;I don&#39;t know who will give it to me&quot;<br>  ✦ &quot;I don&#39;t care how it was created&quot;<br>  ✦ &quot;Someone else will provide it&quot;</pre><pre>Someone else (the framework) decides:<br>  ✦ which EmailService implementation to use<br>  ✦ when to create it<br>  ✦ how to configure it<br>  ✦ who gets the same instance</pre><p>The control over dependency creation is <strong>inverted</strong> — from the class itself to an external authority.</p><pre>BEFORE IoC:<br>┌──────────────────────────────────────┐<br>│           OrderService               │<br>│                                      │<br>│  &quot;I am in control&quot;                   │<br>│  EmailService e = new EmailService() │<br>│  analyticsService = new Analytics()  │<br>│  orderRepo = new OrderRepository()   │<br>└──────────────────────────────────────┘</pre><pre>AFTER IoC:<br>┌──────────────────────────────────────┐<br>│           OrderService               │<br>│                                      │<br>│  &quot;I just need these things.          │<br>│   Please give them to me.&quot;           │<br>│                                      │<br>│  private EmailService     email;     │<br>│  private AnalyticsService analytics; │<br>│  private OrderRepository  repo;      │<br>└──────────────────────────────────────┘<br>         ▲           ▲           ▲<br>         │           │           │<br>         └───────────┴───────────┘<br>               Spring provides<br>               all of these</pre><p>IoC is a <strong>principle</strong> — a design philosophy. It says: <em>“Don’t create your dependencies. Ask for them.”</em></p><p>Dependency Injection is how that principle is implemented in practice.</p><h3>Part 3 — Dependency Injection (DI)</h3><p><strong>Dependency Injection</strong> means: someone outside your class creates the dependencies and hands them to your class.</p><p>The word <em>inject</em> means to push something in from outside.</p><p>There are three ways to inject dependencies:</p><h3>Way 1 — Constructor Injection</h3><p>Dependencies are passed through the constructor. This is the <strong>recommended</strong> way in Spring.</p><pre>public class OrderService {<br>    private final EmailService     emailService;<br>    private final AnalyticsService analyticsService;<br>    private final OrderRepository  orderRepository;<br>// All dependencies come IN through the constructor<br>    // OrderService does not create anything<br>    public OrderService(<br>        EmailService emailService,<br>        AnalyticsService analyticsService,<br>        OrderRepository orderRepository<br>    ) {<br>        this.emailService     = emailService;<br>        this.analyticsService = analyticsService;<br>        this.orderRepository  = orderRepository;<br>    }<br>    public void placeOrder(Order order) {<br>        orderRepository.save(order);<br>        emailService.sendConfirmation(order.getUserEmail(), order.getId());<br>        analyticsService.record(order.getId(), order.getAmount());<br>    }<br>}</pre><p>Notice:</p><ul><li>Fields are final — they cannot change after construction</li><li>The constructor makes required dependencies obvious — you cannot create OrderService without them</li><li>OrderService has zero new keywords for its dependencies</li></ul><pre>Constructor Injection diagram:</pre><pre>  EmailService ──────────────────────────────┐<br>                                             ▼<br>  AnalyticsService ──────────────► OrderService(email, analytics, repo)<br>                                             ▲<br>  OrderRepository ───────────────────────────┘</pre><pre>Dependencies are pushed IN at construction time.</pre><h3>Way 2 — Setter Injection</h3><p>Dependencies are provided via setter methods after construction.</p><pre>public class OrderService {<br>    private EmailService     emailService;<br>    private AnalyticsService analyticsService;<br>// Setters - Spring calls these after creating the object<br>    public void setEmailService(EmailService emailService) {<br>        this.emailService = emailService;<br>    }<br>    public void setAnalyticsService(AnalyticsService analyticsService) {<br>        this.analyticsService = analyticsService;<br>    }<br>}</pre><p>When to use setter injection: for <strong>optional</strong> dependencies. If a dependency can be null and the class can still function without it, setter injection makes sense.</p><p>When NOT to use: for required dependencies. Nothing stops you from forgetting to call the setter — and then your object is broken silently.</p><h3>Way 3 — Field Injection</h3><p>Spring injects the dependency directly into the field using reflection. No constructor, no setter.</p><pre>public class OrderService {<br>@Autowired   // ← Spring injects this directly<br>    private EmailService emailService;<br>    @Autowired<br>    private AnalyticsService analyticsService;<br>}</pre><p>This looks like the simplest option. And it is — but it has problems:</p><ul><li>Fields cannot be final — object is mutable</li><li>You cannot write a test without using Spring (reflection-based injection only works when Spring runs it)</li><li>Hidden dependencies — looking at the class, you cannot tell what it needs just from the constructor</li></ul><p><strong>Use constructor injection everywhere for required dependencies.</strong> Spring’s own documentation recommends it. Field injection is convenient but fragile.</p><h3>DI Without Spring — Manual Injection</h3><p>Before we see how Spring does DI, let’s do it manually. This is what Spring does internally — it just does it automatically for you.</p><pre>// Manual DI — you create everything and inject it yourself<br>public class Main {<br>    public static void main(String[] args) {<br>// Step 1: Create dependencies first<br>        EmailService     emailService     = new EmailService();<br>        AnalyticsService analyticsService = new AnalyticsService();<br>        OrderRepository  orderRepository  = new OrderRepository();<br>        // Step 2: Inject them via constructor<br>        OrderService orderService = new OrderService(<br>            emailService,<br>            analyticsService,<br>            orderRepository<br>        );<br>        // Step 3: Use the assembled object<br>        orderService.placeOrder(new Order(&quot;ord-1&quot;, &quot;john@example.com&quot;, 99.99));<br>    }<br>}</pre><p>This is correct. OrderService does not create anything. Dependencies are injected from outside.</p><p>But you are still doing this manually. In a real application with hundreds of classes, this main() method becomes unmanageable again.</p><p>This is exactly the problem the <strong>IoC Container</strong> solves.</p><h3>Part 4 — The IoC Container</h3><p>The IoC Container is Spring’s brain. It is a giant automated dependency wiring machine.</p><p>You tell it: <em>“Here are my classes. Here are the rules.”</em></p><p>It handles everything else:</p><ul><li>Creating instances in the right order</li><li>Injecting dependencies automatically</li><li>Managing object lifecycles</li><li>Making objects available wherever they are needed</li></ul><pre>Without IoC Container:<br>You create 50 objects manually.<br>You wire them together manually.<br>You manage their lifecycles manually.<br></pre><pre>With IoC Container:<br>┌──────────────────────────────────────────────────────┐<br>│                   IoC CONTAINER                      │<br>│                                                      │<br>│  Reads your configuration/annotations                │<br>│  Creates objects in the right order                  │<br>│  Injects dependencies automatically                  │<br>│  Manages lifecycle (init, destroy)                   │<br>│                                                      │<br>│  ┌─────────────┐   ┌─────────────┐                  │<br>│  │ OrderService│   │ EmailService│                   │<br>│  │  (ready)    │   │  (ready)    │  ... 48 more      │<br>│  └─────────────┘   └─────────────┘                  │<br>└──────────────────────────────────────────────────────┘</pre><pre>You just ask: &quot;Give me OrderService.&quot;<br>Container gives you a fully assembled, ready-to-use object.</pre><p>The objects the IoC container manages are called <strong>Beans</strong>.</p><h3>Part 5 — Beans</h3><p>A <strong>Bean</strong> is simply an object that Spring creates, configures, and manages.</p><p>Not every object in your application is a bean — only the ones you register with the container.</p><pre>Regular Java object:       Bean (Spring-managed object):<br>────────────────────       ────────────────────────────────<br>new EmailService()         Spring creates it<br>You manage it              Spring manages it<br>No DI                      DI happens automatically<br>No lifecycle hooks         @PostConstruct / @PreDestroy work<br>Dies when GC collects it   Controlled lifecycle</pre><p>How do you tell Spring which classes are beans? With annotations:</p><pre>@Component          // generic bean — use when nothing else fits<br>@Service            // bean that holds business logic<br>@Repository         // bean that talks to database<br>@Controller         // bean that handles HTTP requests<br>@RestController     // @Controller + @ResponseBody combined<br>@Configuration      // bean that defines other beans</pre><p>These annotations all do the same thing at the container level — they all register the class as a bean. The different names are just conventions that communicate <em>intent</em> to other developers.</p><pre>// This class is registered as a bean in the container<br>@Service<br>public class EmailService {<br>public void sendConfirmation(String email, String orderId) {<br>        System.out.println(&quot;Sending email to &quot; + email);<br>    }<br>}</pre><pre>@Service<br>public class OrderService {<br>private final EmailService emailService;<br>    // Spring sees this constructor and injects EmailService automatically<br>    public OrderService(EmailService emailService) {<br>        this.emailService = emailService;<br>    }<br>    public void placeOrder(Order order) {<br>        emailService.sendConfirmation(order.getUserEmail(), order.getId());<br>    }<br>}</pre><pre>@Repository<br>public class OrderRepository {<br>    public void save(Order order) {<br>        System.out.println(&quot;Saving order: &quot; + order.getId());<br>    }<br>}</pre><p>Now the container knows about all three. It creates them, wires them together, and stores them — all automatically.</p><h3>Part 6 — Bean Scope</h3><p>By default, Spring creates <strong>one instance</strong> of each bean and reuses it everywhere. This is called <strong>Singleton</strong> scope.</p><pre>First request for OrderService:<br>Container: &quot;I don&#39;t have one yet. Creating...&quot; → creates the bean.</pre><pre>Second request for OrderService:<br>Container: &quot;I already have one. Here it is.&quot; → returns same instance.</pre><pre>Third request for OrderService:<br>Container: returns same instance again.</pre><pre>Result: One OrderService object shared across the entire application.</pre><p>This is correct behavior for stateless service classes. OrderService has no user-specific data — every user can safely share the same instance.</p><p>But sometimes you need a fresh object for each request. Spring supports multiple scopes:</p><pre>// One instance for the entire application (default)<br>@Scope(&quot;singleton&quot;)<br>@Service<br>public class OrderService { ... }<br><br>// New instance every time someone asks for this bean<br>@Scope(&quot;prototype&quot;)<br>@Component<br>public class ReportBuilder { ... }<br><br>// One instance per HTTP request (web applications only)<br>@Scope(&quot;request&quot;)<br>@Component<br>public class ShoppingCart { ... }<br><br>// One instance per HTTP session (web applications only)<br>@Scope(&quot;session&quot;)<br>@Component<br>public class UserPreferences { ... }</pre><pre>Singleton scope:<br>Request 1 ──► Container ──► OrderService (instance A)<br>Request 2 ──► Container ──► OrderService (instance A) ← same!<br>Request 3 ──► Container ──► OrderService (instance A) ← same!<br></pre><pre>Prototype scope:<br>Request 1 ──► Container ──► ReportBuilder (instance A)<br>Request 2 ──► Container ──► ReportBuilder (instance B) ← new!<br>Request 3 ──► Container ──► ReportBuilder (instance C) ← new!</pre><h3>Part 7 — ApplicationContext</h3><p>ApplicationContext is the actual implementation of the IoC container in Spring. It is the object you interact with when you want to get beans, configure the container, or trigger lifecycle events.</p><pre>IoC Container (the concept)<br>        │<br>        │  implemented by<br>        ▼<br>ApplicationContext (the actual Spring interface)<br>        │<br>        │  has many implementations, for example:<br>        ▼<br>AnnotationConfigApplicationContext   ← for plain Java apps<br>ClassPathXmlApplicationContext       ← for XML config (old style)<br>AnnotationConfigServletWebServerApplicationContext ← for Spring Boot web apps</pre><p>In a plain Java application, you create it yourself:</p><pre>import org.springframework.context.annotation.AnnotationConfigApplicationContext;<br>  public class Main {<br>    public static void main(String[] args) {<br>// Step 1: Create the container and tell it where to find your beans<br>        AnnotationConfigApplicationContext context =<br>            new AnnotationConfigApplicationContext(AppConfig.class);<br>// Step 2: Ask the container for a bean by type<br>        OrderService orderService = context.getBean(OrderService.class);<br>// Step 3: Use it - it is fully wired and ready<br>        orderService.placeOrder(new Order(&quot;ord-1&quot;, &quot;john@example.com&quot;, 99.99));<br>// Step 4: Close the container when done (triggers cleanup)<br>        context.close();<br>    }<br></pre><p>In a Spring Boot application, the context is created for you automatically when the app starts. You never write new AnnotationConfigApplicationContext(...) — Spring Boot does it internally and hands you a fully ready container.</p><h3>What AppConfig Looks Like</h3><p>You need to tell the container where to scan for beans. @Configuration and @ComponentScan do this:</p><pre>@Configuration<br>@ComponentScan(basePackages = &quot;com.example&quot;)<br>public class AppConfig {<br>    // Spring will scan everything inside com.example<br>    // and register all @Component, @Service, @Repository, etc. as beans<br>}</pre><p>Or you can define beans manually using @Bean methods:</p><pre>@Configuration<br>public class AppConfig {<br>// This method creates a bean and registers it in the container<br>    @Bean<br>    public EmailService emailService() {<br>        return new EmailService();<br>    }<br>    // Spring sees that OrderService needs EmailService<br>    // and automatically passes the bean from above<br>    @Bean<br>    public OrderService orderService(EmailService emailService) {<br>        return new OrderService(emailService);<br>    }<br>}</pre><p>@Bean methods give you full control over object creation — useful when configuring third-party libraries that you cannot annotate with @Component.</p><h3>Part 8 — The Full Picture</h3><p>Let’s see how all four concepts connect:</p><pre>┌─────────────────────────────────────────────────────────────────────┐<br>│                         IoC CONTAINER                               │<br>│                      (ApplicationContext)                           │<br>│                                                                     │<br>│  1. Reads @ComponentScan / @Configuration                           │<br>│  2. Finds all @Service, @Repository, @Component classes             │<br>│  3. Creates beans in the right order                                │<br>│  4. Injects dependencies (Dependency Injection)                     │<br>│  5. Stores beans and serves them on demand                          │<br>│                                                                     │<br>│   ┌─────────────────────────────────────────────────────────────┐   │<br>│   │                      Bean Registry                          │   │<br>│   │                                                             │   │<br>│   │  &quot;emailService&quot;     → EmailService     (singleton)          │   │<br>│   │  &quot;orderRepository&quot;  → OrderRepository  (singleton)          │   │<br>│   │  &quot;orderService&quot;     → OrderService     (singleton, wired)   │   │<br>│   │  &quot;analyticsService&quot; → AnalyticsService (singleton)          │   │<br>│   │                                                             │   │<br>│   └─────────────────────────────────────────────────────────────┘   │<br>│                                                                     │<br>└─────────────────────────────────────────────────────────────────────┘<br>          ▲                                      │<br>          │ registers itself                     │ provides beans<br>          │                                      ▼<br>  @Service OrderService              Your code asks for beans:<br>  @Service EmailService              context.getBean(OrderService.class)<br>  @Repository OrderRepository        Or Spring injects them via @Autowired<br>  @Service AnalyticsService          or constructor injection</pre><h3>Part 9 — Now With Spring (The Full Before/After)</h3><p>Let’s rewrite the entire example using Spring. Compare it to what we had before.</p><p><strong>Before Spring — you did everything manually:</strong></p><pre>public class Main {<br>    public static void main(String[] args) {<br>        // You create everything<br>        EmailService     emailService     = new EmailService();<br>        AnalyticsService analyticsService = new AnalyticsService();<br>        OrderRepository  orderRepository  = new OrderRepository();<br>// You wire everything<br>        OrderService orderService = new OrderService(<br>            emailService, analyticsService, orderRepository<br>        );<br>        // You use it<br>        orderService.placeOrder(new Order(&quot;ord-1&quot;, &quot;john@example.com&quot;, 99.99));<br>    }<br>}</pre><p><strong>After Spring — declare beans and let Spring handle everything:</strong></p><pre><br>// 1. Mark your classes as beans<br>@Service<br>public class EmailService {<br>    public void sendConfirmation(String email, String orderId) {<br>        System.out.println(&quot;Sending email to &quot; + email + &quot; for order &quot; + orderId);<br>    }<br>}<br>@Service<br>public class AnalyticsService {<br>    public void record(String orderId, double amount) {<br>        System.out.println(&quot;Recording sale: &quot; + orderId + &quot; - $&quot; + amount);<br>    }<br>}<br>@Repository<br>public class OrderRepository {<br>    public void save(Order order) {<br>        System.out.println(&quot;Saving order: &quot; + order.getId());<br>    }<br>}<br>@Service<br>public class OrderService {<br>    private final EmailService     emailService;<br>    private final AnalyticsService analyticsService;<br>    private final OrderRepository  orderRepository;<br>    // Spring sees this constructor and injects everything automatically<br>    public OrderService(<br>        EmailService emailService,<br>        AnalyticsService analyticsService,<br>        OrderRepository orderRepository<br>    ) {<br>        this.emailService     = emailService;<br>        this.analyticsService = analyticsService;<br>        this.orderRepository  = orderRepository;<br>    }<br>    public void placeOrder(Order order) {<br>        orderRepository.save(order);<br>        emailService.sendConfirmation(order.getUserEmail(), order.getId());<br>        analyticsService.record(order.getId(), order.getAmount());<br>    }<br>}</pre><pre>// 2. Configuration — tell Spring where to look<br>@Configuration<br>@ComponentScan(&quot;com.example&quot;)<br>public class AppConfig {}</pre><pre>// 3. main() — just start the container and get your bean<br>public class Main {<br>    public static void main(String[] args) {<br>        var context = new AnnotationConfigApplicationContext(AppConfig.class);<br>OrderService orderService = context.getBean(OrderService.class);<br>        orderService.placeOrder(new Order(&quot;ord-1&quot;, &quot;john@example.com&quot;, 99.99));<br>        context.close();<br>    }<br>}</pre><p>main() went from 10 lines of wiring to 3 lines of intention. Every class is clean. Every dependency is explicit. Nothing is hidden.</p><h3>Part 10 — Testing Is Now Easy</h3><p>Remember how impossible testing was before? Now look:</p><pre>// Before Spring: impossible to mock EmailService<br>@Test<br>public void testPlaceOrder() {<br>    OrderService orderService = new OrderService(); // ❌ no way to inject a mock<br>}<br></pre><pre>// After Spring + constructor injection: testing is trivial<br>@Test<br>public void testPlaceOrder() {<br>    // Create mocks for all dependencies<br>    EmailService     mockEmail     = mock(EmailService.class);<br>    AnalyticsService mockAnalytics = mock(AnalyticsService.class);<br>    OrderRepository  mockRepo      = mock(OrderRepository.class);</pre><pre>    // Inject mocks via constructor — no Spring needed for unit tests<br>    OrderService orderService = new OrderService(<br>        mockEmail, mockAnalytics, mockRepo<br>    );</pre><pre>    // Test business logic in isolation<br>    Order order = new Order(&quot;ord-1&quot;, &quot;john@example.com&quot;, 99.99);<br>    orderService.placeOrder(order);</pre><pre>    // Verify the right methods were called<br>    verify(mockRepo).save(order);<br>    verify(mockEmail).sendConfirmation(&quot;john@example.com&quot;, &quot;ord-1&quot;);<br>    verify(mockAnalytics).record(&quot;ord-1&quot;, 99.99);<br>}</pre><p>Constructor injection makes your code testable without any mocking framework magic. You just pass in your fakes through the constructor.</p><h3>Part 11 — Bean Lifecycle</h3><p>Spring does not just create beans and forget them. It manages their entire lifecycle.</p><pre>BEAN LIFECYCLE:<br>═══════════════════════════════════════════════════════════════</pre><pre>  1. Container starts<br>         │<br>  2. Spring scans for @Component / reads @Configuration<br>         │<br>  3. Creates bean instance (calls constructor)<br>         │<br>  4. Injects dependencies<br>         │<br>  5. Calls @PostConstruct method (if defined)<br>         │<br>         │  ← bean is alive and being used here<br>         │<br>  6. Application runs...<br>         │<br>  7. Container shuts down<br>         │<br>  8. Calls @PreDestroy method (if defined)<br>         │<br>  9. Bean is destroyed</pre><pre>═══════════════════════════════════════════════════════════════</pre><pre>@Service<br>public class DatabaseConnectionPool {<br>private List&lt;Connection&gt; pool;<br>    // Called by Spring AFTER constructor and DI are done<br>    @PostConstruct<br>    public void init() {<br>        System.out.println(&quot;Initializing connection pool...&quot;);<br>        this.pool = new ArrayList&lt;&gt;();<br>        for (int i = 0; i &lt; 10; i++) {<br>            pool.add(createConnection());<br>        }<br>        System.out.println(&quot;Pool ready with 10 connections.&quot;);<br>    }<br>    // Called by Spring BEFORE the bean is destroyed<br>    @PreDestroy<br>    public void cleanup() {<br>        System.out.println(&quot;Closing all connections...&quot;);<br>        pool.forEach(Connection::close);<br>        System.out.println(&quot;All connections closed.&quot;);<br>    }<br>    public Connection getConnection() {<br>        return pool.remove(0);<br>    }<br>}</pre><p>Output when the application starts and stops:</p><pre>Initializing connection pool...<br>Pool ready with 10 connections.</pre><pre>... application runs ...</pre><pre>Closing all connections...<br>All connections closed.</pre><p>@PostConstruct is perfect for setup that needs injected dependencies — because it runs after DI is complete. @PreDestroy is perfect for releasing resources (file handles, network connections, thread pools).</p><h3>Part 12 — @Autowired vs Constructor Injection</h3><p>You will see @Autowired everywhere in the wild. Let&#39;s understand it vs constructor injection.</p><pre>// ❌ Field injection with @Autowired — avoid for required dependencies<br>@Service<br>public class OrderService {<br>@Autowired<br>    private EmailService emailService;      // injected via reflection<br>    @Autowired<br>    private OrderRepository orderRepository;<br>}</pre><pre>// ✅ Constructor injection — recommended always<br>@Service<br>public class OrderService {<br>private final EmailService    emailService;<br>    private final OrderRepository orderRepository;<br>    public OrderService(EmailService emailService, OrderRepository orderRepository) {<br>        this.emailService    = emailService;<br>        this.orderRepository = orderRepository;<br>    }<br>}</pre><p><strong>Note:</strong> In Spring 4.3+, if a class has exactly one constructor, @Autowired on it is optional. Spring detects and uses it automatically. So the constructor injection above needs zero Spring annotations on OrderService — it is pure Java.</p><h3>@Qualifier — When You Have Multiple Implementations</h3><p>What if you have two EmailService implementations — one real, one for testing?</p><pre>public interface EmailService {<br>    void sendConfirmation(String email, String orderId);<br>}</pre><pre>@Service(&quot;smtpEmailService&quot;)<br>public class SmtpEmailService implements EmailService {<br>    public void sendConfirmation(String email, String orderId) {<br>        // send real email via SMTP<br>    }<br>}</pre><pre>@Service(&quot;mockEmailService&quot;)<br>public class MockEmailService implements EmailService {<br>    public void sendConfirmation(String email, String orderId) {<br>        System.out.println(&quot;Fake email to: &quot; + email);  // no real email sent<br>    }<br>}</pre><p>Spring does not know which one to inject into OrderService. You tell it with @Qualifier:</p><pre>@Service<br>public class OrderService {<br>private final EmailService emailService;<br>    public OrderService(@Qualifier(&quot;smtpEmailService&quot;) EmailService emailService) {<br>        this.emailService = emailService;<br>    }<br>}</pre><p>Or with @Primary — mark one implementation as the default:</p><pre>@Service<br>@Primary    // ← use this one by default when there are multiple candidates<br>public class SmtpEmailService implements EmailService { ... }</pre><h3>Quick Reference</h3><pre>SPRING CORE GLOSSARY<br>════════════════════════════════════════════════════════════════</pre><pre>IoC (Inversion of Control)<br>  The principle: don&#39;t create your dependencies.<br>  Ask for them. Let someone else manage their creation.</pre><pre>Dependency Injection (DI)<br>  The implementation of IoC.<br>  Dependencies are &quot;injected&quot; into your class from outside.<br>  Three ways: constructor (best), setter (optional deps), field (avoid)</pre><pre>IoC Container<br>  Spring&#39;s engine. Creates beans, injects dependencies,<br>  manages lifecycles. You register beans; it handles the rest.</pre><pre>ApplicationContext<br>  The actual Java interface/implementation of the IoC container.<br>  AnnotationConfigApplicationContext for plain Java.<br>  Auto-created by Spring Boot in web apps.</pre><pre>Bean<br>  Any object created and managed by the Spring IoC container.<br>  Marked with @Component, @Service, @Repository, @Controller, etc.</pre><pre>@Component        General-purpose bean<br>@Service          Business logic layer<br>@Repository       Data access layer (also translates DB exceptions)<br>@Controller       HTTP request handler<br>@Configuration    Defines other beans via @Bean methods</pre><pre>@Autowired        Asks Spring to inject a dependency<br>@Qualifier        Specifies which bean to inject when multiple exist<br>@Primary          Marks the default bean when multiple exist<br>@Scope            Controls how many instances are created<br>@PostConstruct    Runs after DI is complete (initialization)<br>@PreDestroy       Runs before bean is destroyed (cleanup)</pre><pre>Singleton scope   One instance per container (default)<br>Prototype scope   New instance every time<br>Request scope     One instance per HTTP request<br>Session scope     One instance per HTTP session</pre><pre>════════════════════════════════════════════════════════════════</pre><h3>Summary</h3><p>We started with a system where every class created its own dependencies. Tests were impossible. Changes broke everything. main() was a wiring nightmare.</p><p><strong>Inversion of Control</strong> said: stop letting classes create their own dependencies. Flip the control — let something external decide what gets created and when.</p><p><strong>Dependency Injection</strong> is how that works in practice. Dependencies are pushed into your class from outside — through the constructor, a setter, or a field. Constructor injection is always the right default: dependencies are explicit, the object is always complete, and testing becomes trivial.</p><p><strong>The IoC Container</strong> is Spring’s engine that automates all of this. You declare which classes are beans. Spring reads your configuration, creates every bean in the right order, injects dependencies automatically, and manages their entire lifecycle from startup to shutdown.</p><p><strong>ApplicationContext</strong> is the actual implementation of that container. In Spring Boot, it starts automatically when your application starts. You never wire objects manually again.</p><p>Together, these four concepts are the reason Spring code is clean, testable, and maintainable at scale. Every other Spring feature — Spring MVC, Spring Data, Spring Security — is built on top of this foundation.</p><p><em>Found this useful? Hit the clap button 👏.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=134fd2754393" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Serialization — How readObject Works Internally]]></title>
            <link>https://medium.com/@sarvar55mszde/java-serialization-how-readobject-works-internally-7f223f4e6dea?source=rss-4e7b1393b87c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f223f4e6dea</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[effective-java]]></category>
            <category><![CDATA[singleton-design-pattern]]></category>
            <category><![CDATA[java-serialization]]></category>
            <dc:creator><![CDATA[Sarvar Musazade]]></dc:creator>
            <pubDate>Mon, 18 May 2026 16:06:54 GMT</pubDate>
            <atom:updated>2026-05-18T16:06:54.533Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone! Today we are going to learn one of the most misunderstood corners of Java — how readObject actually works under the hood. Not just how to use it. How the JVM reconstructs a full object from raw bytes, without ever calling a constructor. I bet this will change how you think about object creation in Java forever. ☕</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*uRtlKekDf5XYXGTequpBdg.png" /></figure><h3>The Story — Magic That Hides a Lot of Danger</h3><p>You have a User object. You want to save it to a file and load it back later. You add implements Serializable. You write two lines. It works.</p><pre>// Save<br>ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(&quot;user.ser&quot;));<br>out.writeObject(user);</pre><pre>// Load<br>ObjectInputStream in = new ObjectInputStream(new FileInputStream(&quot;user.ser&quot;));<br>User user = (User) in.readObject();</pre><p>Simple. But the moment you ask <em>“what actually happens inside </em><em>readObject?&quot;</em> — you open a rabbit hole that goes very deep.</p><p>How does Java reconstruct the object? It does not call the constructor. So how does the object get created at all? What JVM mechanism makes this possible? And what happens to singletons — objects that are supposed to have exactly one instance — when you deserialize them?</p><p>Let’s find out. Step by step.</p><h3>Step 1 — What Serialization Actually Produces</h3><p>When you call writeObject(user), Java does not just dump field values into a file. It writes a structured binary format.</p><p>Let’s look at a simple class first:</p><pre>import java.io.Serializable;<br><br>public class User implements Serializable {<br>    private static final long serialVersionUID = 1L;<br>    private String name;<br>    private String email;<br>    private int    age;<br>    public User(String name, String email, int age) {<br>        this.name  = name;<br>        this.email = email;<br>        this.age   = age;<br>    }<br>}</pre><p>When you serialize new User(&quot;John&quot;, &quot;john@example.com&quot;, 30), the byte stream contains:</p><pre>0xAC 0xED         ← Magic number — &quot;this is Java serialization&quot;<br>0x00 0x05         ← Protocol version 5<br>class descriptor  ← Full class name: &quot;com.example.User&quot;<br>serialVersionUID  ← 1L (your version number)<br>field list        ← name:String, email:String, age:int<br>field values      ← &quot;John&quot;, &quot;john@example.com&quot;, 30</pre><p>The stream carries not just the data, but the full shape of the class — its name, its serialVersionUID, and the name and type of every serialized field. This is how readObject knows how to reconstruct it on the other end.</p><h3>Step 2 — The Big Question: How Is the Object Created Without a Constructor?</h3><p>Here is the fundamental question. You have a byte stream. You want a User object. Normally you call new User(...). But during deserialization, the constructor is <strong>never called</strong>.</p><p>Prove it yourself:</p><pre>public class User implements Serializable {<br>    private static final long serialVersionUID = 1L;<br>    private String name;<br>    private String email;<br>    public User(String name, String email) {<br>        System.out.println(&quot;Constructor called!&quot;);  // ← watch this<br>        this.name  = name;<br>        this.email = email;<br>    }<br>}</pre><pre>// Serialize<br>User original = new User(&quot;John&quot;, &quot;john@example.com&quot;);<br>// Output: &quot;Constructor called!&quot;<br><br>ByteArrayOutputStream baos = new ByteArrayOutputStream();<br>new ObjectOutputStream(baos).writeObject(original);<br>// Deserialize<br>ObjectInputStream in = new ObjectInputStream(<br>    new ByteArrayInputStream(baos.toByteArray())<br>);<br>User restored = (User) in.readObject();<br>// Output: nothing - constructor was NOT called</pre><p>The constructor printed its message when we created the original object. It printed nothing during deserialization. The object was reconstructed — but never constructed. So how?</p><h3>Step 3 — The JVM Secret: sun.misc.Unsafe</h3><p>The JVM uses an internal class called sun.misc.Unsafe (or jdk.internal.misc.Unsafe in newer Java versions). This class gives direct, low-level access to memory — bypassing all normal Java safety rules.</p><p>One of its methods is allocateInstance(Class&lt;?&gt; cls). It allocates raw memory for an object on the heap — without calling any constructor, without running any initializers, without setting any field values.</p><p>The object simply appears in memory. All fields are at their default values: null for objects, 0 for numbers, false for booleans.</p><pre>// This is what the JVM does internally during deserialization.<br>// You should NEVER do this in your own code — it is shown here only to explain the mechanism.<br>import sun.misc.Unsafe;<br>import java.lang.reflect.Field;<br>public class UnsafeDemo {<br>    public static void main(String[] args) throws Exception {<br>        // Get the Unsafe instance via reflection<br>        Field f = Unsafe.class.getDeclaredField(&quot;theUnsafe&quot;);<br>        f.setAccessible(true);<br>        Unsafe unsafe = (Unsafe) f.get(null);<br>        // Allocate a User object WITHOUT calling any constructor<br>        User user = (User) unsafe.allocateInstance(User.class);<br><br>        System.out.println(user);         // User object exists...<br>        System.out.println(user.name);    // ...but name is null<br>        System.out.println(user.email);   // ...email is null<br>        System.out.println(user.age);     // ...age is 0<br>    }<br>}</pre><p>This is the skeleton of what ObjectInputStream does under the hood. It allocates the raw memory, then fills in the fields by reading values from the byte stream one by one — using the field descriptors it read from the stream header.</p><p>The result: a fully populated object, reconstructed entirely from bytes, with no constructor ever called.</p><h3>Step 4 — The Full readObject Lifecycle</h3><p>Now let’s put all the steps together. When you call in.readObject(), the JVM goes through this exact sequence:</p><pre>Step 1 — Read stream header<br>         Reads 0xACED magic + protocol version.<br>         Verifies this is a valid Java serialization stream.<br>Step 2 - Read class descriptor<br>         Reads the class name: &quot;com.example.User&quot;<br>         Reads the serialVersionUID: 1L<br>         Reads the field list: name(String), email(String), age(int)<br>Step 3 - Resolve the class<br>         Finds the User.class in the current JVM&#39;s class loader.<br>         Checks: does the serialVersionUID in the stream match the one in the loaded class?<br>         If not → InvalidClassException.<br>Step 4 - Allocate the object<br>         Calls Unsafe.allocateInstance(User.class)<br>         Raw memory allocated. No constructor. All fields null/0.<br>Step 5 - Restore field values<br>         Reads each field value from the stream.<br>         Injects values directly into memory using Unsafe.putObject / putInt / etc.<br>Step 6 - Call readObject() if defined<br>         If the class defines a private readObject(ObjectInputStream) method,<br>         call it now. This is where custom deserialization logic runs.<br>Step 7 - Call readResolve() if defined<br>         If the class defines a readResolve() method,<br>         call it. The returned object REPLACES the deserialized one.<br>         This is how singletons protect themselves. (More on this below.)<br>Step 8 - Return the object<br>         The fully restored object is returned to the caller.</pre><p>The key insight: <strong>he object exists at Step 4 — before any of its fields are set. It is a shell. </strong>The JVM fills it in at Step 5. Only after that does any custom logic run.</p><h3>Step 5 — What Happens With Superclasses?</h3><p>Here is an important rule that most developers do not know.</p><p>For serializable classes, the no-arg constructor of the first <strong>non-serializable</strong> supertype is called. For serializable classes themselves, field initializers and constructors are not executed during deserialization.</p><p>Let’s see this with an example:</p><pre>// Non-serializable superclass<br>public class Animal {<br>   protected String species;<br>   public Animal() {<br>        System.out.println(&quot;Animal constructor called!&quot;);<br>        this.species = &quot;Unknown&quot;;<br>    }<br>}<br>// Serializable subclass<br>public class Dog extends Animal implements Serializable {<br>    private static final long serialVersionUID = 1L;<br>    private String name;<br>    public Dog(String name) {<br>        System.out.println(&quot;Dog constructor called!&quot;);<br>        this.name = name;<br>    }<br>}</pre><pre>Dog original = new Dog(&quot;Rex&quot;);<br>// Output:<br>//   Animal constructor called!<br>//   Dog constructor called!<br><br>// ... serialize Dog to bytes ...<br>Dog restored = (Dog) in.readObject();<br>// Output:<br>//   Animal constructor called!   ← non-serializable superclass DOES run<br>// Dog constructor NOT called     ← serializable subclass does NOT</pre><p>Animal&#39;s constructor runs because Animal is not serializable. The JVM cannot restore its state from the stream, so it must initialize it through the constructor. Dog&#39;s constructor does not run because Dog is serializable — its state is restored directly from the stream.</p><p>This has a serious consequence: <strong>any validation or invariant enforcement in </strong><strong>Dog&#39;s constructor is completely skipped during deserialization.</strong></p><h3>Step 6 — Custom readObject: Taking Control</h3><p>You can define a private readObject method to run your own logic during deserialization. The JVM calls it at Step 6 — after the object&#39;s fields have been filled in by default deserialization.</p><pre>public class User implements Serializable {<br>    private static final long serialVersionUID = 1L;<br>    private String name;<br>    private String email;<br>    private int    age;<br>    public User(String name, String email, int age) {<br>        validate(name, email, age);     // validation runs during normal construction<br>        this.name  = name;<br>        this.email = email;<br>        this.age   = age;<br>    }<br>    // ✅ Custom readObject - validation runs during deserialization too<br>    private void readObject(ObjectInputStream in)<br>            throws IOException, ClassNotFoundException {<br>        in.defaultReadObject();         // Step 1: restore all fields normally<br>        // Step 2: now validate them - just like the constructor would<br>        validate(this.name, this.email, this.age);<br>    }<br>    private void validate(String name, String email, int age) {<br>        if (name == null || name.isBlank())<br>            throw new IllegalArgumentException(&quot;Name cannot be blank&quot;);<br>        if (email == null || !email.contains(&quot;@&quot;))<br>            throw new IllegalArgumentException(&quot;Invalid email: &quot; + email);<br>        if (age &lt; 0 || age &gt; 150)<br>            throw new IllegalArgumentException(&quot;Invalid age: &quot; + age);<br>    }<br>}</pre><p>Without readObject, an attacker can craft a malicious byte stream that creates a User with an empty name, an invalid email, or a negative age — bypassing every check in your constructor. The custom readObject closes that gap.</p><p><strong>Real-world example — why this matters:</strong></p><p>Imagine you have a Range class that enforces start &lt; end:</p><pre>public class Range implements Serializable {<br>    private static final long serialVersionUID = 1L;<br>    private final int start;<br>    private final int end;<br>    public Range(int start, int end) {<br>        if (start &gt;= end)<br>            throw new IllegalArgumentException(&quot;start must be less than end&quot;);<br>        this.start = start;<br>        this.end   = end;<br>    }<br>    // ❌ No custom readObject - an attacker can craft:<br>    //    start = 100, end = 1<br>    //    This passes deserialization even though it violates the class invariant!<br>}<br>private void readObject(ObjectInputStream in)<br>        throws IOException, ClassNotFoundException {<br>    in.defaultReadObject();<br>    // Same check as the constructor - enforced during deserialization too<br>    if (start &gt;= end)<br>        throw new InvalidObjectException(<br>            &quot;start(&quot; + start + &quot;) must be less than end(&quot; + end + &quot;)&quot;<br>        );<br>}</pre><p>Fix it:</p><p>Now the invariant holds whether the object was created normally or from a byte stream.</p><h3>Step 7 — The transient Keyword</h3><p>Fields marked transient are excluded from serialization. They are not written to the stream. During deserialization, they receive their default values (null, 0, false).</p><pre>public class UserSession implements Serializable {<br>    private static final long serialVersionUID = 1L;<br>    private String userId;<br>    private String username;<br>    private transient String passwordHash;   // ← never serialized<br>    private transient Connection dbConnection; // ← cannot be serialized anyway<br>    private transient long loginTime;    // ← meaningless after restore<br>    public UserSession(String userId, String username, String passwordHash) {<br>        this.userId       = userId;<br>        this.username     = username;<br>        this.passwordHash = passwordHash;<br>        this.loginTime    = System.currentTimeMillis();<br>    }<br>    // Restore transient fields manually after deserialization<br>    private void readObject(ObjectInputStream in)<br>            throws IOException, ClassNotFoundException {<br>        in.defaultReadObject();         // restores userId, username<br>        // Restore transient fields to safe defaults<br>        this.passwordHash = null;       // do not restore - too sensitive<br>        this.loginTime    = System.currentTimeMillis();  // reset to now<br>        this.dbConnection = null;       // caller must re-connect<br>    }<br>}</pre><p>Use transient for:</p><ul><li>Sensitive data (passwords, tokens, keys) — never write them to a stream</li><li>Non-serializable fields (database connections, threads, file handles) — cannot be serialized</li><li>Derived or cached values that can be recomputed — no reason to store them</li></ul><h3>Step 8 — serialVersionUID: What Happens If You Forget It?</h3><p>Every serializable class has a serialVersionUID. If you do not declare one, Java computes one automatically — based on the class name, implemented interfaces, and the signatures of all fields and methods.</p><p>The problem: this auto-generated UID changes every time you change the class.</p><pre>// Version 1 — you serialize this<br>public class User implements Serializable {<br>    private String name;<br>    private String email;<br>    // auto-generated serialVersionUID = 123456789L (hypothetical)<br><br>// Version 2 - you add a field and try to deserialize Version 1 data<br>public class User implements Serializable {<br>    private String name;<br>    private String email;<br>    private int    age;   // ← new field<br>    // auto-generated serialVersionUID = 987654321L (changed!)<br>}<br>}</pre><pre>java.io.InvalidClassException: User; local class incompatible:<br>stream classdesc serialVersionUID = 123456789,<br>local class serialVersionUID = 987654321</pre><p>The JVM sees two different UIDs and refuses to deserialize. Your saved data is now unreadable.</p><p><strong>Always declare serialVersionUID explicitly:</strong></p><pre>public class User implements Serializable {<br>    private static final long serialVersionUID = 1L;  // ← locked forever<br>    // ...<br>}</pre><p>With an explicit UID, you control compatibility yourself. Adding a new field with a default value is safe — older data just leaves the new field at its default. If you make a breaking structural change, you bump the UID to 2L deliberately.</p><h3>Step 9 — The Singleton Problem</h3><p>This is where things get really serious.</p><p>A singleton is a class that is supposed to have exactly one instance in the JVM. You make the constructor private, you hold the one instance in a static field, and you access it through a static method.</p><pre>public class AppConfig implements Serializable {<br>    private static final long serialVersionUID = 1L;<br>    private static final AppConfig INSTANCE = new AppConfig();<br>    private String databaseUrl = &quot;jdbc:postgresql://localhost/mydb&quot;;<br>    private AppConfig() {}<br>    public static AppConfig getInstance() {<br>        return INSTANCE;<br>    }<br>}</pre><p>Now serialize and deserialize it:</p><pre>AppConfig original = AppConfig.getInstance();</pre><pre>// Serialize<br>ByteArrayOutputStream baos = new ByteArrayOutputStream();<br>new ObjectOutputStream(baos).writeObject(original);</pre><pre>// Deserialize<br>AppConfig restored = (AppConfig) new ObjectInputStream(<br>    new ByteArrayInputStream(baos.toByteArray())<br>).readObject();</pre><pre>// Are they the same object?<br>System.out.println(original == restored);   // ❌ false<br>System.out.println(original.hashCode());    // 2125039532<br>System.out.println(restored.hashCode());    // 381259350 — a NEW instance!</pre><p>During deserialization, Java creates a new instance of the class without calling the constructor — using mechanisms like sun.misc.Unsafe.allocateInstance(). This means that if an object of a singleton class is serialized and then deserialized, a new instance of that class can be created, violating the singleton rule.</p><p>Your singleton guarantee is broken. There are now two AppConfig instances in the JVM. Any code that changed original does not see the same state in restored. This is a silent, hard-to-detect bug.</p><h3>Step 10 — readResolve: The Fix for Singletons</h3><p>Java provides a hook called readResolve(). It runs at Step 7 of the deserialization lifecycle — after the object has been reconstructed from the stream. Whatever readResolve() returns <strong>replaces</strong> the deserialized object entirely.</p><pre>public class AppConfig implements Serializable {<br>    private static final long serialVersionUID = 1L;<br>    private static final AppConfig INSTANCE = new AppConfig();<br>    private String databaseUrl = &quot;jdbc:postgresql://localhost/mydb&quot;;<br>    private AppConfig() {}<br>    public static AppConfig getInstance() {<br>        return INSTANCE;<br>    }<br>    // ✅ Called by JVM after deserialization<br>    // The returned object REPLACES whatever was deserialized<br>    private Object readResolve() {<br>        return INSTANCE;    // throw away the new object, return the real singleton<br>    }<br>}</pre><pre>AppConfig original = AppConfig.getInstance();<br>// Serialize + Deserialize<br>// ... same code as before ...<br>AppConfig restored = (AppConfig) in.readObject();<br>System.out.println(original == restored);   // ✅ true - same object!</pre><p>The JVM creates the new AppConfig instance at Step 4, fills its fields at Step 5 — and then calls readResolve() at Step 7. readResolve() says: &quot;ignore this new object, return the real singleton.&quot; The new object is discarded and garbage collected.</p><h3>Step 11 — The readResolve Attack (And Why transient Matters)</h3><p>There is a subtle attack against readResolve. If your singleton has non-transient object reference fields, an attacker can steal a reference to the deserialized object before readResolve discards it.</p><pre>// ❌ VULNERABLE — non-transient object field<br>public class AppConfig implements Serializable {<br>    private static final long serialVersionUID = 1L;<br>    private static final AppConfig INSTANCE = new AppConfig();<br>    private String[] allowedRoles = {&quot;admin&quot;, &quot;user&quot;};  // ← non-transient!<br>    private AppConfig() {}<br>    public static AppConfig getInstance() { return INSTANCE; }<br>    private Object readResolve() { return INSTANCE; }<br>}</pre><p>If a singleton contains a non-transient object reference field, the contents of this field will be deserialized before the singleton’s readResolve method is run. This allows a carefully crafted stream to steal a reference to the originally deserialized singleton at the time the contents of the object reference field are deserialized.</p><p>The fix: mark all object reference fields transient:</p><pre>// ✅ SAFE — all object fields are transient<br>public class AppConfig implements Serializable {<br>    private static final long serialVersionUID = 1L;<br>    private static final AppConfig INSTANCE = new AppConfig();<br>    private transient String[] allowedRoles = {&quot;admin&quot;, &quot;user&quot;};  // ← transient!<br>    private AppConfig() {<br>        this.allowedRoles = new String[]{&quot;admin&quot;, &quot;user&quot;};<br>    }<br>    public static AppConfig getInstance() { return INSTANCE; }<br>    private Object readResolve() { return INSTANCE; }<br>}</pre><p>With transient, the field is not written to the stream at all. There is nothing for the attacker to exploit. When readResolve discards the new object, it takes nothing sensitive with it.</p><h3>Step 12 — The Best Solution: Enum Singleton</h3><p>All of the above — readResolve, transient fields, the attack risk — disappears completely if you use an <strong>enum singleton</strong>.</p><p><em>Effective Java</em> recommends this as the best singleton implementation. Java guarantees at the JVM level that each enum constant is created exactly once. Serialization of enums is handled specially: only the enum constant’s name is written to the stream, and during deserialization, the existing constant is looked up by name instead of creating a new instance.</p><pre>public enum AppConfig {<br>    INSTANCE;<br>    private final String databaseUrl = &quot;jdbc:postgresql://localhost/mydb&quot;;<br>    public String getDatabaseUrl() { return databaseUrl; }<br>}</pre><pre>AppConfig original = AppConfig.INSTANCE;<br>// Serialize + Deserialize<br>// ... same code as before ...<br>AppConfig restored = (AppConfig) in.readObject();<br>System.out.println(original == restored);   // ✅ true - ALWAYS. Guaranteed by JVM.</pre><p>No readResolve. No transient. No attack vector. The JVM handles everything.</p><p>This is exactly why <em>Effective Java</em> says the enum singleton is the preferred implementation in any modern Java codebase.</p><h3>The Full Picture</h3><pre>readObject() Lifecycle<br>──────────────────────────────────────────────────────────────────<br> 1. Read stream header        → verify magic number (0xACED)<br> 2. Read class descriptor     → class name, serialVersionUID, fields<br> 3. Resolve class             → find class in ClassLoader, check UID<br> 4. Allocate object           → Unsafe.allocateInstance() — no constructor!<br> 5. Restore field values      → read from stream, inject via Unsafe<br> 6. Call readObject()         → custom deserialization logic (if defined)<br> 7. Call readResolve()        → replace object (singleton protection)<br> 8. Return object             → caller receives fully restored object<br>──────────────────────────────────────────────────────────────────</pre><h3>❗ Common Mistakes</h3><p><strong>1. No custom </strong><strong>readObject — constructor validation is bypassed</strong> If your constructor enforces invariants and you do not replicate that logic in readObject, an attacker can deserialize invalid objects. Always add readObject with the same validation as the constructor.</p><p><strong>2. Forgetting </strong><strong>serialVersionUID</strong> Auto-generated UIDs change when you modify the class. Saved data becomes unreadable. Declare serialVersionUID explicitly on every serializable class.</p><p><strong>3. Implementing </strong><strong>Serializable on a singleton without </strong><strong>readResolve</strong> Deserialization creates a new instance. Your singleton is broken. Either add readResolve, make all fields transient, or — best of all — use an enum singleton.</p><p><strong>4. Forgetting </strong><strong>in.defaultReadObject() in custom </strong><strong>readObject</strong> Without this call, none of your fields are restored from the stream. All fields stay at their defaults (null, 0). Always call defaultReadObject() first in your readObject method.</p><p><strong>5. Not marking sensitive fields </strong><strong>transient</strong> Passwords, tokens, and connection handles have no business in a serialized stream. Mark them transient and restore them in readObject if needed.</p><h3>💡 Practical Tips</h3><ul><li>Treat readObject like a second constructor. Every invariant your constructor enforces should also be enforced in readObject.</li><li>Use InvalidObjectException (not IllegalArgumentException) when validation fails inside readObject. This is the semantically correct exception for deserialization failures.</li><li>Consider whether your class needs to be Serializable at all. If it does not cross process or network boundaries, do not implement it — you remove an entire class of security and consistency problems.</li><li>For any class that holds sensitive data, test deserialization explicitly in your test suite. Craft a byte stream manually and verify your readObject rejects it.</li><li>If you use modern serialization alternatives like Jackson (JSON), Protocol Buffers, or Kryo, most of these problems disappear. Java’s built-in serialization is powerful but carries significant hidden complexity.</li></ul><h3>Summary</h3><p>Java serialization is built on a mechanism most developers never see. The JVM uses Unsafe.allocateInstance() to create objects without calling any constructor, then injects field values directly into memory from the byte stream. readObject is the hook that lets you run custom logic after that injection. readResolve lets you replace the deserialized object entirely — which is how singletons protect themselves. And the enum singleton sidesteps all of this complexity by getting special treatment from the JVM serialization spec.</p><p>Understanding this lifecycle is not just academic. It is the difference between a system that is safe and correct — and one that silently creates broken objects, violates invariants, and opens security holes.</p><p><em>Found this useful? Hit the clap button 👏 and follow.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f223f4e6dea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Effective Java Item 2 — Consider a Builder When Faced With Many Constructor Parameters]]></title>
            <link>https://medium.com/@sarvar55mszde/effective-java-item-2-consider-a-builder-when-faced-with-many-constructor-parameters-05e897cf02e8?source=rss-4e7b1393b87c------2</link>
            <guid isPermaLink="false">https://medium.com/p/05e897cf02e8</guid>
            <category><![CDATA[desing-pattern]]></category>
            <category><![CDATA[javabean]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[effective-java]]></category>
            <dc:creator><![CDATA[Sarvar Musazade]]></dc:creator>
            <pubDate>Sat, 16 May 2026 18:57:21 GMT</pubDate>
            <atom:updated>2026-05-16T18:57:21.102Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone! Today we are going to learn one of the most practical lessons from Effective Java — the Builder pattern. But before we jump to the solution, we need to feel the pain first. Because without the pain, the solution makes no sense. ☕</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*Gok3w7f-1OMsHwcfidlDow.png" /></figure><h3>The Story — A User Registration Form</h3><p>You are building a user registration system. A user has many fields — some required, some optional.</p><p>Let’s say your User class looks like this:</p><pre>Required:<br>  - name<br>  - email</pre><pre>Optional:<br>  - phone<br>  - address<br>  - age<br>  - bio<br>  - website</pre><p>Simple enough. Now the question is — how do you let someone create a User object?</p><p>You have three options. Let’s go through each one, understand it fully, and understand why two of them fail.</p><h3>Option 1 — Telescoping Constructors</h3><p>The first instinct of most developers is to write constructors. One for required fields. Another for required + one optional. Another for required + two optionals. And so on.</p><p>This pattern is called the <strong>Telescoping Constructor pattern</strong>.</p><pre>public class User {<br>    // Required<br>    private final String name;<br>    private final String email;</pre><pre>    // Optional<br>    private final String phone;<br>    private final String address;<br>    private final int    age;<br>    private final String bio;<br>    private final String website;</pre><pre>    // Constructor 1 — only required fields<br>    public User(String name, String email) {<br>        this(name, email, &quot;&quot;);<br>    }</pre><pre>    // Constructor 2 — required + phone<br>    public User(String name, String email, String phone) {<br>        this(name, email, phone, &quot;&quot;);<br>    }</pre><pre>    // Constructor 3 — required + phone + address<br>    public User(String name, String email, String phone, String address) {<br>        this(name, email, phone, address, 0);<br>    }</pre><pre>    // Constructor 4 — required + phone + address + age<br>    public User(String name, String email, String phone, String address, int age) {<br>        this(name, email, phone, address, age, &quot;&quot;);<br>    }</pre><pre>    // Constructor 5 — required + phone + address + age + bio<br>    public User(String name, String email, String phone, String address, int age, String bio) {<br>        this(name, email, phone, address, age, bio, &quot;&quot;);<br>    }</pre><pre>    // Constructor 6 — all fields<br>    public User(String name, String email, String phone, String address, int age, String bio, String website) {<br>        this.name    = name;<br>        this.email   = email;<br>        this.phone   = phone;<br>        this.address = address;<br>        this.age     = age;<br>        this.bio     = bio;<br>        this.website = website;<br>    }<br>}</pre><p>Now imagine creating a User where you only know name, email, and website — but not phone, address, age, or bio.</p><p>Which constructor do you call? None of them fit exactly. So you call the full constructor and pass empty strings and zeros for the fields you don’t have:</p><pre>User user = new User(&quot;John&quot;, &quot;john@example.com&quot;, &quot;&quot;, &quot;&quot;, 0, &quot;&quot;, &quot;john.dev&quot;);</pre><p>This is terrible. Let’s count the problems.</p><h3>Problem 1 — What Do All These Values Mean?</h3><p>Look at this line:</p><pre>User user = new User(&quot;John&quot;, &quot;john@example.com&quot;, &quot;&quot;, &quot;&quot;, 0, &quot;&quot;, &quot;john.dev&quot;);</pre><p>What is the first &quot;&quot;? What is the second &quot;&quot;? What is 0? What is the third &quot;&quot;?</p><p>You cannot answer without counting parameters and checking the constructor signature. Every time you read this line — even if you wrote it yourself — you need to look it up.</p><p><em>Effective Java</em> is direct about this:</p><blockquote>“In short, the telescoping constructor pattern works, but it is hard to write client code when there are many parameters, and harder still to read it.”</blockquote><h3>Problem 2 — Parameters of the Same Type Next to Each Other</h3><p>Your constructor has many String parameters in a row:</p><pre>public User(String name, String email, String phone, String address, ...)</pre><p>The Java compiler sees them all as String. It cannot tell the difference. So this compiles perfectly:</p><pre>// ❌ name and email are swapped — compiler doesn&#39;t care<br>User user = new User(&quot;john@example.com&quot;, &quot;John&quot;, &quot;&quot;, &quot;&quot;, 0, &quot;&quot;, &quot;&quot;);</pre><p>No error. No warning. A silent bug that only shows up at runtime — or never, until a real user reports it.</p><h3>Problem 3 — Unwanted Fields Get Fake Values</h3><p>When you don’t have a value for a field, you pass &quot;&quot; or 0 or null. These fake values pollute your object. Your User now has a phone of &quot;&quot; — which is not the same as having no phone. It is a fake phone number. This causes problems later when you try to validate or display the data.</p><h3>Option 2 — JavaBeans Pattern</h3><p>The second approach is the <strong>JavaBeans pattern</strong>. Instead of one big constructor, you create the object with a no-argument constructor and then call setter methods one by one.</p><pre>public class User {<br>    // Required — but no longer enforced<br>    private String name;<br>    private String email;</pre><pre>    // Optional<br>    private String phone   = &quot;&quot;;<br>    private String address = &quot;&quot;;<br>    private int    age     = 0;<br>    private String bio     = &quot;&quot;;<br>    private String website = &quot;&quot;;</pre><pre>    // No-argument constructor<br>    public User() {}</pre><pre>    // Setters for every field<br>    public void setName(String name)       { this.name    = name; }<br>    public void setEmail(String email)     { this.email   = email; }<br>    public void setPhone(String phone)     { this.phone   = phone; }<br>    public void setAddress(String address) { this.address = address; }<br>    public void setAge(int age)            { this.age     = age; }<br>    public void setBio(String bio)         { this.bio     = bio; }<br>    public void setWebsite(String website) { this.website = website; }<br>}</pre><p>Creating a user now looks like this:</p><pre>User user = new User();<br>user.setName(&quot;John&quot;);<br>user.setEmail(&quot;john@example.com&quot;);<br>user.setWebsite(&quot;john.dev&quot;);</pre><p>This is immediately more readable. You can see exactly which field each value belongs to. And you only set the fields you actually have — no fake empty strings.</p><p>So is this the answer? Not quite. JavaBeans has its own serious problems.</p><h3>Problem 1 — The Object Is Broken During Construction</h3><p>With JavaBeans, you build the object across multiple lines. Between new User() and the last setter call, the object exists but is incomplete.</p><pre>User user = new User();<br>// ⚠️ user exists here — but name and email are null<br>// If something passes `user` to another method RIGHT HERE, it gets a broken object</pre><pre>user.setName(&quot;John&quot;);<br>// ⚠️ still broken — email is null</pre><pre>user.setEmail(&quot;john@example.com&quot;);<br>// ✅ finally complete</pre><p>In a multi-threaded application, another thread could pick up this half-constructed object and try to use it. The results are unpredictable.</p><p><em>Effective Java</em> describes this precisely:</p><blockquote>“A JavaBean may be in an inconsistent state partway through its construction. The class does not have the option of enforcing consistency merely by checking the validity of the constructor parameters.”</blockquote><h3>Problem 2 — Required Fields Are Not Enforced</h3><p>With a telescoping constructor, required fields are part of the constructor signature — the compiler guarantees you provide them.</p><p>With JavaBeans, name and email are just fields with setters. Nothing stops a developer from doing this:</p><pre>User user = new User();<br>user.setWebsite(&quot;john.dev&quot;);<br>// Forgot name and email — but this compiles and runs just fine</pre><p>You now have a User with no name and no email. You only discover this problem at runtime — maybe in production.</p><h3>Problem 3 — The Object Cannot Be Immutable</h3><p>With JavaBeans, every field needs a setter. Setters mean fields cannot be final. Fields that are not final can be changed at any time by any code that holds a reference to the object.</p><pre>User user = new User();<br>user.setName(&quot;John&quot;);<br>user.setEmail(&quot;john@example.com&quot;);</pre><pre>// ... 200 lines later, in some other class ...<br>user.setEmail(&quot;hacker@evil.com&quot;);  // ❌ nothing stops this</pre><p>Mutable shared objects are one of the most common sources of bugs in Java applications. Immutability removes this entire class of problems.</p><h3>Can We Fix JavaBeans With a freeze() Method?</h3><p>Some developers try to patch the mutability problem by adding a freeze() method. The idea is: once you are done setting fields, you call freeze() — and from that point, the object refuses any further changes.</p><pre>public class User {<br>    private String  name;<br>    private String  email;<br>    private String  phone   = &quot;&quot;;<br>    private boolean frozen  = false;   // ← tracks whether the object is locked</pre><pre>    public User() {}</pre><pre>    private void checkFrozen() {<br>        if (frozen) {<br>            throw new IllegalStateException(<br>                &quot;This User is frozen and cannot be modified&quot;<br>            );<br>        }<br>    }</pre><pre>    // Call this when you are done building the object<br>    public void freeze() {<br>        if (name == null || name.isBlank()) {<br>            throw new IllegalStateException(&quot;Name is required before freezing&quot;);<br>        }<br>        if (email == null || email.isBlank()) {<br>            throw new IllegalStateException(&quot;Email is required before freezing&quot;);<br>        }<br>        this.frozen = true;<br>    }</pre><pre>    public void setName(String name) {<br>        checkFrozen();               // ← throws if already frozen<br>        this.name = name;<br>    }</pre><pre>    public void setEmail(String email) {<br>        checkFrozen();<br>        this.email = email;<br>    }</pre><pre>    public void setPhone(String phone) {<br>        checkFrozen();<br>        this.phone = phone;<br>    }<br>}</pre><p>Usage would look like this:</p><pre>User user = new User();<br>user.setName(&quot;John&quot;);<br>user.setEmail(&quot;john@example.com&quot;);<br>user.setPhone(&quot;+1-555-1234&quot;);<br>user.freeze();                        // lock it — no more changes allowed</pre><pre>user.setPhone(&quot;+1-999-9999&quot;);         // ❌ throws IllegalStateException</pre><p>This looks like it solves the mutability problem. But it creates new problems that are worse.</p><p><strong>Problem A — freeze() is optional.</strong> Nothing forces the caller to call it. A developer can create a User, set some fields, pass it around — and never call freeze(). The object stays mutable forever and nobody notices until a bug appears.</p><p><strong>Problem B — The inconsistent state problem is still there.</strong> Between new User() and freeze(), the object is still partially constructed. Another thread can still pick it up mid-construction.</p><p><strong>Problem C — It adds complexity for no real gain.</strong> You now have a frozen flag, a checkFrozen() method, and runtime exceptions for something the compiler could have caught at compile time with a Builder. You traded a compile-time guarantee for a runtime check.</p><p><em>Effective Java</em> does not recommend this approach. It mentions it only to explain why it is insufficient. The freeze() pattern is an attempt to retrofit immutability onto a mutable design — and it never fully works. The Builder pattern achieves the same goal correctly, without any of these trade-offs.</p><h3>Why JavaBeans Is Still Used</h3><p>Despite these problems, JavaBeans is everywhere. The reason is frameworks.</p><p><strong>Spring</strong>, <strong>Hibernate</strong>, <strong>Jackson</strong>, and many other Java frameworks were built around the JavaBeans convention. They need a no-argument constructor and setters to work automatically.</p><p>For example, when Jackson deserialises JSON into a Java object:</p><pre>{ &quot;name&quot;: &quot;John&quot;, &quot;email&quot;: &quot;john@example.com&quot; }</pre><p>It calls new User() and then setName(&quot;John&quot;) and setEmail(&quot;john@example.com&quot;) — exactly the JavaBeans pattern.</p><p>So in practice, you will see JavaBeans most often on <strong>data transfer objects (DTOs)</strong> and <strong>entity classes</strong> that frameworks manage. For those cases, you often have no choice — the framework requires it.</p><p>But for domain objects that you control fully — objects that represent real business concepts — JavaBeans is rarely the right choice.</p><h3>Option 3 — The Builder Pattern</h3><p>The Builder pattern gives you the best of both worlds:</p><ul><li>The <strong>readability</strong> of JavaBeans (named, labelled fields)</li><li>The <strong>safety</strong> of telescoping constructors (required fields enforced, immutable result)</li></ul><p>The idea is simple. Instead of constructing the object directly, you construct a Builder object first. You set fields on the Builder. When you are ready, you call build() — and the Builder creates the final, complete, immutable object.</p><p>Let’s build it step by step.</p><h3>Step 1 — The Basic Structure</h3><pre>public class User {<br>    // All fields are final — the object is immutable after build()<br>    private final String name;      // required<br>    private final String email;     // required<br>    private final String phone;     // optional<br>    private final String address;   // optional<br>    private final int    age;       // optional<br>    private final String bio;       // optional<br>    private final String website;   // optional</pre><pre>    // Private constructor — only the Builder can call this<br>    private User(Builder builder) {<br>        this.name    = builder.name;<br>        this.email   = builder.email;<br>        this.phone   = builder.phone;<br>        this.address = builder.address;<br>        this.age     = builder.age;<br>        this.bio     = builder.bio;<br>        this.website = builder.website;<br>    }</pre><pre>    // The Builder lives inside User as a static nested class<br>    public static class Builder {<br>        // Required fields — set in the Builder constructor<br>        private final String name;<br>        private final String email;</pre><pre>        // Optional fields — sensible defaults<br>        private String phone   = &quot;&quot;;<br>        private String address = &quot;&quot;;<br>        private int    age     = 0;<br>        private String bio     = &quot;&quot;;<br>        private String website = &quot;&quot;;</pre><pre>        // Required fields are constructor parameters — cannot be skipped<br>        public Builder(String name, String email) {<br>            this.name  = name;<br>            this.email = email;<br>        }</pre><pre>        // Each optional field has its own setter that returns `this`<br>        public Builder phone(String phone) {<br>            this.phone = phone;<br>            return this;            // ← this enables method chaining<br>        }</pre><pre>        public Builder address(String address) {<br>            this.address = address;<br>            return this;<br>        }</pre><pre>        public Builder age(int age) {<br>            this.age = age;<br>            return this;<br>        }</pre><pre>        public Builder bio(String bio) {<br>            this.bio = bio;<br>            return this;<br>        }</pre><pre>        public Builder website(String website) {<br>            this.website = website;<br>            return this;<br>        }</pre><pre>        // build() creates the final User — complete and immutable<br>        public User build() {<br>            return new User(this);<br>        }<br>    }<br>}</pre><h3>Step 2 — Using the Builder</h3><p>Now look at how clean the call site is:</p><pre>// Required fields only<br>User user = new User.Builder(&quot;John&quot;, &quot;john@example.com&quot;)<br>    .build();</pre><pre>// Required + some optional fields<br>User user = new User.Builder(&quot;John&quot;, &quot;john@example.com&quot;)<br>    .website(&quot;john.dev&quot;)<br>    .build();</pre><pre>// All fields<br>User user = new User.Builder(&quot;John&quot;, &quot;john@example.com&quot;)<br>    .phone(&quot;+1-555-1234&quot;)<br>    .address(&quot;123 Main St&quot;)<br>    .age(30)<br>    .bio(&quot;Backend developer&quot;)<br>    .website(&quot;john.dev&quot;)<br>    .build();</pre><p>Every field is labelled. You can set only the fields you have. Required fields cannot be skipped. The object is complete and immutable the moment build() returns.</p><p><em>Effective Java</em> describes this clearly:</p><blockquote>“The Builder pattern simulates named optional parameters as found in Python and Scala.”</blockquote><h3>Step 3 — Adding Validation in build()</h3><p>The build() method is the perfect place to validate. You have all the values. You check them before creating the object. If something is wrong, you throw an exception — before the broken object ever exists.</p><pre>public User build() {<br>    // Validate required fields<br>    if (name == null || name.isBlank()) {<br>        throw new IllegalStateException(&quot;Name is required&quot;);<br>    }<br>    if (email == null || email.isBlank()) {<br>        throw new IllegalStateException(&quot;Email is required&quot;);<br>    }</pre><pre>    // Validate optional fields if provided<br>    if (age &lt; 0) {<br>        throw new IllegalArgumentException(&quot;Age cannot be negative&quot;);<br>    }</pre><pre>    return new User(this);<br>}</pre><p>With telescoping constructors, validation lives in the constructor — which makes complex multi-field validation messy. With JavaBeans, there is no single place to validate — the object is always partially constructed. With Builder, build() is the single, clean validation point.</p><h3>Connecting to Static Factory Methods</h3><p>You now know two tools: <strong>static factory methods</strong> (Item 1) and the <strong>Builder</strong> (Item 2).</p><p>These two tools work together, not against each other.</p><p>Static factory methods answer: <em>“How should callers create this type?”</em> The Builder answers: <em>“How do I construct this object when it has many parameters?”</em></p><p>Let’s combine them with two concrete factory methods — of() and builder() — each designed for a different situation.</p><h3>factory method 1 — of() for Quick, Fixed Creation</h3><p>Sometimes you know all the values upfront and you just want to create a User in one line. The of() factory method is perfect for this. It is short, it is named (following the <em>Effective Java</em> convention), and it hides the constructor.</p><pre>public class User {<br>    private final String name;<br>    private final String email;<br>    private final String phone;<br>    private final String website;</pre><pre>    private User(Builder builder) {<br>        this.name    = builder.name;<br>        this.email   = builder.email;<br>        this.phone   = builder.phone;<br>        this.website = builder.website;<br>    }</pre><pre>    // ✅ of() — for when you know all required fields upfront<br>    // Internally it still uses the Builder — callers don&#39;t see that<br>    public static User of(String name, String email) {<br>        return new Builder(name, email).build();<br>    }</pre><pre>    // ✅ builder() — for when you need optional fields too<br>    public static Builder builder(String name, String email) {<br>        return new Builder(name, email);<br>    }</pre><pre>    public static class Builder {<br>        private final String name;<br>        private final String email;<br>        private String phone   = &quot;&quot;;<br>        private String website = &quot;&quot;;</pre><pre>        public Builder(String name, String email) {<br>            this.name  = name;<br>            this.email = email;<br>        }</pre><pre>        public Builder phone(String phone) {<br>            this.phone = phone;<br>            return this;<br>        }</pre><pre>        public Builder website(String website) {<br>            this.website = website;<br>            return this;<br>        }</pre><pre>        public User build() {<br>            if (name == null || name.isBlank())  throw new IllegalStateException(&quot;Name is required&quot;);<br>            if (email == null || email.isBlank()) throw new IllegalStateException(&quot;Email is required&quot;);<br>            return new User(this);<br>        }<br>    }<br>}</pre><p>Now callers have two clean options:</p><pre>// Option A — of() when you only need required fields, right now<br>// Clean. Short. One line.<br>User admin = User.of(&quot;Admin&quot;, &quot;admin@example.com&quot;);</pre><pre>// Option B — builder() when you have optional fields to set<br>// Named, labelled, flexible. Reads like a sentence.<br>User john = User.builder(&quot;John&quot;, &quot;john@example.com&quot;)<br>    .phone(&quot;+1-555-1234&quot;)<br>    .website(&quot;john.dev&quot;)<br>    .build();</pre><p>Both go through the same Builder internally. The caller never needs to know that. of() is just a shortcut that covers the simple case. builder() covers everything else.</p><p><strong>Real world analogy:</strong> Think of of() as ordering a standard coffee — you say &quot;one espresso&quot; and it is done. Think of builder() as customising your order — &quot;oat milk, two shots, no sugar, extra hot.&quot; Both end up at the same coffee machine. You just use different entry points depending on how much you need to customise.</p><h3>Side by Side — All Three Approaches</h3><pre>// ❌ Telescoping Constructor — unreadable, fragile<br>User user = new User(&quot;John&quot;, &quot;john@example.com&quot;, &quot;&quot;, &quot;&quot;, 0, &quot;&quot;, &quot;john.dev&quot;);</pre><pre>// ⚠️ JavaBeans — readable but mutable and inconsistent during construction<br>User user = new User();<br>user.setName(&quot;John&quot;);<br>user.setEmail(&quot;john@example.com&quot;);<br>user.setWebsite(&quot;john.dev&quot;);</pre><pre>// ✅ Builder — readable, safe, immutable, validated<br>User user = User.builder(&quot;John&quot;, &quot;john@example.com&quot;)<br>    .website(&quot;john.dev&quot;)<br>    .build();</pre><h3>❗ Common Mistakes</h3><p><strong>1. Making Builder fields mutable in the final object</strong> If User has setters alongside the Builder, you lost immutability for nothing. Make all fields in User final. No setters. Ever.</p><p><strong>2. Forgetting to return </strong><strong>this in Builder setters</strong> Without return this, you cannot chain calls. Every setter in the Builder must return Builder.</p><p><strong>3. Putting required fields as Builder setters instead of the Builder constructor</strong> If name and email are Builder setters, a developer can call build() without setting them. Required fields belong in the Builder constructor — the compiler enforces them.</p><p><strong>4. Using a Builder for a class with two or three fields</strong> A Builder adds boilerplate. For a class with two fields, a simple constructor is cleaner. <em>Effective Java</em> suggests considering a Builder when you have <strong>four or more parameters</strong> — especially when several are optional.</p><p><strong>5. Not validating in </strong><strong>build()</strong> The whole point of build() is to be the single gate before the object exists. If you skip validation there, a broken object can be created and passed around silently.</p><h3>💡 Practical Tips</h3><ul><li>If you use <strong>Lombok</strong>, @Builder generates the entire pattern automatically. But understand the manual version first — it makes you a better developer and helps you debug when Lombok behaves unexpectedly.</li><li>Combine @Builder with @Value in Lombok to get an immutable class with a generated Builder in two annotations.</li><li>If your team uses Jackson for JSON, add @JsonDeserialize(builder = User.Builder.class) to tell Jackson to use the Builder during deserialisation instead of a no-arg constructor.</li><li>Use static factory method + Builder together when you want to hide the Builder class name from callers. User.builder(...) is nicer than new User.Builder(...).</li></ul><h3>📋 Summary</h3><p>We started with the <strong>telescoping constructor</strong> — the most common first attempt. It works, but it breaks down fast. Call sites become unreadable lines of positional values. Parameters of the same type sit next to each other and silently swap without the compiler noticing. Optional fields get filled with fake empty strings just to satisfy a constructor that doesn’t fit the situation.</p><p>Then we tried <strong>JavaBeans</strong>. It reads better — every field is named, every setter is explicit. But it introduces a different kind of danger. The object exists before it is complete. Required fields are no longer enforced. And because everything has a setter, nothing can ever be final — the object stays mutable forever. The freeze() workaround looks promising but only trades compile-time safety for a runtime exception that is easy to forget to trigger.</p><p>The <strong>Builder</strong> solves all of this. Required fields go into the Builder constructor — the compiler enforces them. Optional fields get their own named setter methods — no positional confusion, no fake empty values. build() is the single place where validation happens and the final immutable object is created. The object is never partially constructed. It either exists complete or it does not exist at all.</p><p>Adding of() alongside builder() gives callers two clean entry points. Use of() when you only need required fields and want one line. Use builder() when you need to set optional fields and want readable, labelled code. Both routes go through the same Builder internally. The caller never needs to know the difference.</p><p>The Builder pattern adds some boilerplate — that is the honest trade-off. But for any class with four or more fields, especially with optional ones, the boilerplate pays for itself immediately in readability, safety, and maintainability.</p><h3>What’s Next?</h3><p>We will look at how to write a singleton correctly in Java, why the naive approach is broken, and what the enum singleton is and why <em>Effective Java</em> recommends it above everything else.</p><p>See you in the next one. 🚀</p><p><em>Found this useful? Hit the clap button 👏 and follow for the next part — Singletons in Java, done right.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05e897cf02e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Static Factory Methods — The Disadvantages Nobody Talks About]]></title>
            <link>https://medium.com/@sarvar55mszde/static-factory-methods-the-disadvantages-nobody-talks-about-9b299464d8fd?source=rss-4e7b1393b87c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b299464d8fd</guid>
            <dc:creator><![CDATA[Sarvar Musazade]]></dc:creator>
            <pubDate>Fri, 15 May 2026 11:05:12 GMT</pubDate>
            <atom:updated>2026-05-15T11:05:12.980Z</atom:updated>
            <content:encoded><![CDATA[<p>We learned why static factory methods are powerful. But Effective Java is honest — it lists the disadvantages too. Let’s go through them, using our ApiException as the example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*7yUXYGmZzvVGzq1pUe53TA.png" /></figure><h3>Quick Recap</h3><p>In the last article, we transformed this:</p><pre>throw new ApiException(&quot;NOT_FOUND&quot;, &quot;User not found&quot;, 404);</pre><p>Into this:</p><pre>throw ApiException.userNotFound(&quot;id: &quot; + id);</pre><p>Clean. Safe. Readable. But this design comes with real trade-offs. Let’s be honest about them.</p><h3>Disadvantage 1 — Subclassing Becomes Impossible</h3><p>When you make the constructor private, nobody outside the class can extend it.</p><pre>public class ApiException extends RuntimeException {<br>    private ApiException(...) { ... }  // private constructor<br>}</pre><p>Now try this:</p><pre>// ❌ Compile error — ApiException() has private access<br>public class PaymentException extends ApiException {<br>    ...<br>}</pre><p>It fails. A private constructor means no subclass can call super(...) — which every subclass must do. So the class is effectively <strong>final</strong>, even without the final keyword.</p><p><strong>Is this a problem in practice?</strong></p><p>For ApiException — not really. You don&#39;t need PaymentException extends ApiException. You already have ApiException.paymentFailed(...). The factory method handles it.</p><p>But if a library ships a class with a private constructor, <em>you</em> can never extend it. You are stuck with whatever the library gives you. That is a real limitation for library authors.</p><p><em>Effective Java</em> actually considers this a partial advantage too — it encourages composition over inheritance. But it is still a constraint worth knowing.</p><h3>Disadvantage 2 — They Are Hard to Find in Documentation</h3><p>This is the most practical pain point day-to-day.</p><p>With a constructor, every IDE and documentation tool knows where to look. Javadoc puts all constructors in a Constructor Summary section. A developer opening your class for the first time goes straight there.</p><p>With static factory methods, there is no special section. Your factory methods sit mixed in with all other static methods:</p><pre>public class ApiException extends RuntimeException {</pre><pre>    public static ApiException unauthorized()           { ... }  // factory<br>    public static ApiException notFound(String msg)    { ... }  // factory<br>    public static ApiException userNotFound(String f)  { ... }  // factory<br>    public String getCode()                            { ... }  // getter<br>    public int getStatus()                             { ... }  // getter<br>    private static ApiException of(...)                { ... }  // internal helper<br>}</pre><p>A new developer opening this class asks: <em>“How do I create an ApiException?”</em></p><p>They scan the class. They see getCode(), getStatus(), of(), unauthorized(), notFound()... Nothing is labelled &quot;use this to create an instance.&quot; They have to read the whole class to understand the pattern.</p><p><strong>How to reduce this pain:</strong></p><p>Follow the standard naming conventions from <em>Effective Java</em> — of, from, valueOf, getInstance. Most experienced Java developers recognise these immediately as factory methods. And always write a clear Javadoc on the class itself:</p><pre>/**<br> * Represents an API error response.<br> *<br> * &lt;p&gt;Create instances using the static factory methods:<br> * &lt;pre&gt;<br> *   ApiException.unauthorized()<br> *   ApiException.notFound(&quot;User not found&quot;)<br> *   ApiException.validationError(errors)<br> * &lt;/pre&gt;<br> */<br>public class ApiException extends RuntimeException { ... }</pre><p>One paragraph. All the guidance a new developer needs.</p><h3>Constructor vs Static Factory Methods — Trade-Offs</h3><p>In Java, both constructors and static factory methods are used to create objects. At first glance, they seem interchangeable, but they lead to very different design decisions.</p><p>Understanding their trade-offs helps you design cleaner and more flexible APIs.</p><h3>Subclassing</h3><p>Constructors allow subclassing as long as they are accessible.</p><p>Static factory methods can prevent subclassing when constructors are hidden (for example, private). This is often used intentionally to control object creation.</p><h3>Discoverability</h3><p>Constructors are easy to find because IDEs and Javadoc highlight them automatically.</p><p>Static factory methods may be less obvious since they are regular static methods mixed with other logic.</p><h3>Naming</h3><p>Constructors are limited to the class name, which often lacks clarity.</p><p>Static factory methods allow meaningful names:</p><ul><li>User.createAdmin()</li><li>User.fromEmail()</li><li>User.anonymous()</li></ul><p>This improves readability and intent.</p><h3>Object Creation Control</h3><p>Constructors always create a new object.</p><p>Static factory methods can:</p><ul><li>return cached instances</li><li>reuse existing objects</li><li>or avoid creation entirely</li></ul><p>This can improve performance and memory usage.</p><h3>Encapsulation</h3><p>Constructors expose how objects are created.</p><p>Static factory methods hide implementation details, allowing internal changes without affecting the public API.</p><p>Found this useful? Hit the clap button 👏 and follow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b299464d8fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Static Factory Methods in Java — Effective Java , Explained With Real Code]]></title>
            <link>https://medium.com/@sarvar55mszde/static-factory-methods-in-java-effective-java-explained-with-real-code-3315ffb84496?source=rss-4e7b1393b87c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3315ffb84496</guid>
            <category><![CDATA[effective-java]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Sarvar Musazade]]></dc:creator>
            <pubDate>Fri, 15 May 2026 10:58:07 GMT</pubDate>
            <atom:updated>2026-05-15T10:58:38.031Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone! Today we are going to learn one of the most important lessons from Effective Java — Static Factory Methods. I bet you will understand it completely. Since we will learn everything by building a real exception class from scratch, step by step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*V2uzx0a3_PgV5x-Ia1I6bw.png" /></figure><h3>The Story — Your First Exception Class</h3><p>You are building a REST API. Something goes wrong — a user is not found, a password is wrong, a form has errors.</p><p>You need to throw an exception. Your first instinct:</p><pre>throw new RuntimeException(&quot;User not found&quot;);</pre><p>Simple. But your frontend team immediately asks:</p><blockquote>“Can you give us an HTTP status code? And a consistent error code string?”</blockquote><p>So you create your own exception class. Let’s build it together — and learn Effective Java Item 1 along the way.</p><h3>Version 0 — The Constructor Approach</h3><p>Most developers start here. They create a class with a constructor and expose it directly:</p><pre>public class ApiException extends RuntimeException {<br>    private final String code;<br>    private final int status;</pre><pre>    public ApiException(String code, String message, int status) {<br>        super(message);<br>        this.code   = code;<br>        this.status = status;<br>    }<br>}</pre><p>Now every time something goes wrong in a service, you write:</p><pre>// In UserService<br>throw new ApiException(&quot;NOT_FOUND&quot;, &quot;User not found&quot;, 404);</pre><pre>// In OrderService<br>throw new ApiException(&quot;NOT_FOUND&quot;, &quot;Order not found&quot;, 404);</pre><pre>// In AuthService<br>throw new ApiException(&quot;UNAUTHORIZED&quot;, &quot;You are not authorized&quot;, 401);</pre><p>This works. But there are serious problems hiding here. Let’s find them one by one.</p><h3>Problem 1 — Constructor Parameters Are Confusing</h3><p>Look at this constructor signature:</p><pre>public ApiException(String code, String message, int status)</pre><p>Two of the three parameters are String. Which comes first — code or message?</p><pre>// Is this right?<br>throw new ApiException(&quot;NOT_FOUND&quot;, &quot;User not found&quot;, 404);</pre><pre>// Or is this right?<br>throw new ApiException(&quot;User not found&quot;, &quot;NOT_FOUND&quot;, 404);</pre><p>The Java compiler accepts both. It cannot tell the difference — they are both strings. You have to look at the constructor definition every single time to be sure.</p><p><em>Effective Java</em> warns about exactly this:</p><blockquote>“Programmers have been known to get around this restriction by providing two constructors whose parameter lists differ only in the order of their parameter types. This is a really bad idea. The user of such an API will never be able to remember which constructor is which and will end up calling the wrong one by mistake.”</blockquote><p>This is a silent bug waiting to happen.</p><h3>Problem 2 — Magic Strings and Numbers Everywhere</h3><p>Every call site repeats the same raw strings and numbers:</p><pre>throw new ApiException(&quot;NOT_FOUND&quot;, &quot;User not found&quot;, 404);<br>throw new ApiException(&quot;NOT_FOUND&quot;, &quot;Order not found&quot;, 404);<br>throw new ApiException(&quot;NOT_FOUND&quot;, &quot;Product not found&quot;, 404);</pre><p>What if someone on your team types &quot;not_found&quot; instead of &quot;NOT_FOUND&quot;? The compiler will not stop them. Your API will return inconsistent error codes — and the frontend breaks silently.</p><p>What if the business decides to change the status code for not-found errors from 404 to 422? You have to find and update every single line across the entire codebase. You will miss some.</p><h3>Problem 3 — No Reuse for Identical Exceptions</h3><p>Some exceptions are always the same. UNAUTHORIZED is always status 401 with the message &quot;You are not authorized.&quot; There is no variation. Yet with raw constructors, every caller creates a brand new object every time:</p><pre>// Three different objects. All identical. All unnecessary.<br>throw new ApiException(&quot;UNAUTHORIZED&quot;, &quot;You are not authorized&quot;, 401);<br>throw new ApiException(&quot;UNAUTHORIZED&quot;, &quot;You are not authorized&quot;, 401);<br>throw new ApiException(&quot;UNAUTHORIZED&quot;, &quot;You are not authorized&quot;, 401);</pre><p><em>Effective Java</em> tells us:</p><blockquote>“It can greatly improve performance if equivalent objects are requested often, especially if they are expensive to create.”</blockquote><p>We are creating redundant objects for no reason.</p><h3>The Fix — Static Factory Methods (Effective Java Item 1)</h3><p>A <strong>static factory method</strong> is a static method that creates and returns an instance of the class. Instead of callers writing new ApiException(...), they call a named method like ApiException.notFound(...).</p><p>This one change solves all three problems above.</p><p>Let’s apply it now.</p><h3>Version 1 — Private Constructor + Static Factory Methods</h3><pre>public class ApiException extends RuntimeException {<br>    private final String code;<br>    private final int    status;</pre><pre>    // ✅ Constructor is PRIVATE — nobody can call new ApiException(...) directly<br>    private ApiException(String code, String message, int status) {<br>        super(message);<br>        this.code   = code;<br>        this.status = status;<br>    }</pre><pre>    // ✅ Named factory methods — self-explanatory, no parameter confusion<br>    public static ApiException notFound(String message) {<br>        return new ApiException(&quot;NOT_FOUND&quot;, message, 404);<br>    }</pre><pre>    public static ApiException unauthorized() {<br>        return new ApiException(&quot;UNAUTHORIZED&quot;, &quot;You are not authorized&quot;, 401);<br>    }</pre><pre>    public static ApiException forbidden() {<br>        return new ApiException(&quot;FORBIDDEN&quot;, &quot;You are not allowed&quot;, 403);<br>    }</pre><pre>    public static ApiException internalError(String message) {<br>        return new ApiException(&quot;INTERNAL_SERVER_ERROR&quot;, message, 500);<br>    }<br>}</pre><p>Now look at the call sites:</p><pre>// ✅ Before — confusing, fragile<br>throw new ApiException(&quot;NOT_FOUND&quot;, &quot;User not found&quot;, 404);</pre><pre>// ✅ After — clear, safe, no magic strings<br>throw ApiException.notFound(&quot;User not found&quot;);<br>throw ApiException.unauthorized();<br>throw ApiException.forbidden();</pre><p><strong>Problem 1 solved</strong> — no parameter confusion. notFound() takes only one parameter: the message. You cannot get the order wrong.</p><p><strong>Problem 2 solved</strong> — error codes and status numbers live in exactly one place — inside the factory method. Change it once and it changes everywhere.</p><p><strong>Problem 3 is next</strong> — let’s tackle repeated object creation.</p><h3>Advantage 1 — Methods Have Meaningful Names</h3><p>This is the first advantage <em>Effective Java</em> lists for static factory methods.</p><p>A constructor is always named after the class. new ApiException(...) tells you nothing about <em>what kind</em> of exception this is.</p><p>But a static factory method can have any name:</p><pre>ApiException.notFound(&quot;User not found&quot;)        // clearly a 404<br>ApiException.unauthorized()                     // clearly a 401<br>ApiException.validationError(errors)            // clearly a 400 with field errors<br>ApiException.internalError(&quot;Unexpected state&quot;)  // clearly a 500</pre><p>You can read these lines without looking at any documentation. The name carries the meaning.</p><p>You can also see this in the Java standard library:</p><pre>// What kind of date? Hard to tell from constructor alone.<br>new LocalDate(...)</pre><pre>// Crystal clear — factory methods tell the whole story.<br>LocalDate.now()<br>LocalDate.of(2024, 6, 15)<br>LocalDate.parse(&quot;2024-06-15&quot;)</pre><h3>Advantage 2 — Instance Caching (No Redundant Objects)</h3><p>This is the second advantage: static factory methods can return a cached instance instead of always creating a new one.</p><p>UNAUTHORIZED is always the same exception. Code &quot;UNAUTHORIZED&quot;, message &quot;You are not authorized&quot;, status 401. There is zero reason to allocate a new object every time someone hits a protected endpoint.</p><p>So we cache it:</p><pre>public class ApiException extends RuntimeException {<br>    private final String code;<br>    private final int    status;</pre><pre>    // ✅ Created once at class load time. Reused forever.<br>    private static final ApiException UNAUTHORIZED = new ApiException(<br>        &quot;UNAUTHORIZED&quot;,<br>        &quot;You are not authorized&quot;,<br>        401<br>    );</pre><pre>    private static final ApiException FORBIDDEN = new ApiException(<br>        &quot;FORBIDDEN&quot;,<br>        &quot;You are not allowed to perform this action&quot;,<br>        403<br>    );</pre><pre>    private ApiException(String code, String message, int status) {<br>        super(message);<br>        this.code   = code;<br>        this.status = status;<br>    }</pre><pre>    // ✅ Returns the SAME object every time — no new allocation<br>    public static ApiException unauthorized() {<br>        return UNAUTHORIZED;<br>    }</pre><pre>    public static ApiException forbidden() {<br>        return FORBIDDEN;<br>    }</pre><pre>    // ✅ These create new objects because the message varies<br>    public static ApiException notFound(String message) {<br>        return new ApiException(&quot;NOT_FOUND&quot;, message, 404);<br>    }</pre><pre>    public static ApiException internalError(String message) {<br>        return new ApiException(&quot;INTERNAL_SERVER_ERROR&quot;, message, 500);<br>    }<br>}</pre><p>This is the exact same pattern Java’s Boolean.valueOf() uses:</p><pre>// Boolean.valueOf() NEVER creates a new object.<br>// It always returns Boolean.TRUE or Boolean.FALSE — cached at class load time.<br>Boolean flag = Boolean.valueOf(true);   // returns Boolean.TRUE<br>Boolean flag = Boolean.valueOf(false);  // returns Boolean.FALSE</pre><p>In a high-traffic API, unauthorized() might be called thousands of times per minute. With caching, that is zero heap allocations. Without it, thousands of identical objects are created, garbage collected, and created again.</p><p><em>Effective Java</em> calls this <strong>instance control</strong> — the class controls exactly which instances exist and how many. creates an object. <strong>It can greatly improve performance if equivalent objects are requested often, especially if they are expensive to create.</strong></p><h3>Advantage 3 — Hiding Implementation Details</h3><p>This is the third advantage: factory methods do not have to return the exact class. They can return any subtype — or hide internal helper factories.</p><p>In our ApiException, look at the private of() helpers:</p><pre>private static ApiException of(String code, String message, int status) {<br>    return new ApiException(code, message, status, null);<br>}</pre><pre>private static ApiException of(String code, String message, int status, Map&lt;String, String&gt; errors) {<br>    return new ApiException(code, message, status, errors);<br>}</pre><p>These are private. Callers never see them. They exist only to remove duplication inside the class. The public factory methods call them internally:</p><pre>public static ApiException notFound(String message) {<br>    return of(&quot;NOT_FOUND&quot;, message, 404);            // calls private of()<br>}</pre><pre>public static ApiException validationError(Map&lt;String, String&gt; errors) {<br>    return of(&quot;VALIDATION_ERROR&quot;, &quot;Validation failed&quot;, 400, errors); // calls private of()<br>}</pre><p><em>Effective Java</em> explains this benefit:</p><blockquote>“It is not just the bulk of the API that is reduced but the conceptual weight — the number and difficulty of the concepts that programmers must master in order to use the API. The programmer knows that the returned object has precisely the API specified, so there is no need to read additional class documentation for the implementation class.”</blockquote><p>Your teammates only need to know the public factory methods. The internal details are invisible.</p><h3>Advantage 4 — Domain-Specific Methods</h3><p>Because factory methods can have any name, you can go one step further and add methods that are specific to your domain. Instead of generic notFound(), you add:</p><pre>// Domain-specific factory methods — read like sentences<br>public static ApiException userNotFound(String field) {<br>    return notFound(&quot;User not found with &quot; + field);<br>}</pre><pre>public static ApiException userAlreadyExists(String field) {<br>    return validationError(Map.of(field, &quot;User already exists with &quot; + field));<br>}</pre><p>Now your service layer reads like plain English:</p><pre>// UserService.java<br>public User findById(Long id) {<br>    return userRepository.findById(id)<br>        .orElseThrow(() -&gt; ApiException.userNotFound(&quot;id: &quot; + id));<br>}</pre><pre>public void register(RegisterRequest req) {<br>    if (userRepository.existsByEmail(req.getEmail())) {<br>        throw ApiException.userAlreadyExists(&quot;email&quot;);<br>    }<br>}</pre><p>No raw strings. No status codes. No parameter order to memorise. Each line says exactly what it means.</p><h3>The Final Version — Putting It All Together</h3><p>Here is the complete class, with every principle applied:</p><pre>public class ApiException extends RuntimeException {</pre><pre>    private final String              code;<br>    private final int                 status;<br>    private final Map&lt;String, String&gt; validationErrors;</pre><pre>    // --- Cached stateless instances (created once, reused forever) ---</pre><pre>    private static final ApiException UNAUTHORIZED = new ApiException(<br>        &quot;UNAUTHORIZED&quot;, &quot;You are not authorized&quot;, 401, null<br>    );</pre><pre>    private static final ApiException FORBIDDEN = new ApiException(<br>        &quot;FORBIDDEN&quot;, &quot;You are not allowed to perform this action&quot;, 403, null<br>    );</pre><pre>    // --- Private constructor — all creation goes through factory methods ---</pre><pre>    private ApiException(String code, String message, int status, Map&lt;String, String&gt; errors) {<br>        super(message);<br>        this.code             = code;<br>        this.status           = status;<br>        this.validationErrors = errors;<br>    }</pre><pre>    // --- Public factory methods — the only API callers ever see ---</pre><pre>    public static ApiException unauthorized() {<br>        return UNAUTHORIZED;                          // returns cached instance<br>    }</pre><pre>    public static ApiException forbidden() {<br>        return FORBIDDEN;                             // returns cached instance<br>    }</pre><pre>    public static ApiException notFound(String message) {<br>        return of(&quot;NOT_FOUND&quot;, message, 404);<br>    }</pre><pre>    public static ApiException internalError(String message) {<br>        return of(&quot;INTERNAL_SERVER_ERROR&quot;, message, 500);<br>    }</pre><pre>    public static ApiException validationError(Map&lt;String, String&gt; errors) {<br>        return of(&quot;VALIDATION_ERROR&quot;, &quot;Validation failed&quot;, 400, errors);<br>    }</pre><pre>    // --- Domain-specific convenience methods ---</pre><pre>    public static ApiException userNotFound(String field) {<br>        return notFound(&quot;User not found with &quot; + field);<br>    }</pre><pre>    public static ApiException userAlreadyExists(String field) {<br>        return validationError(Map.of(field, &quot;User already exists with &quot; + field));<br>    }</pre><pre>    // --- Private helpers — invisible to callers ---</pre><pre>    private static ApiException of(String code, String message, int status) {<br>        return new ApiException(code, message, status, null);<br>    }</pre><pre>    private static ApiException of(String code, String message, int status, Map&lt;String, String&gt; errors) {<br>        return new ApiException(code, message, status, errors);<br>    }</pre><pre>    // --- Getters ---</pre><pre>    public String getCode()                          { return code; }<br>    public int getStatus()                           { return status; }<br>    public Map&lt;String, String&gt; getValidationErrors() { return validationErrors; }<br>}</pre><h3>Before vs After — Side by Side</h3><pre>// ❌ BEFORE — constructor approach<br>throw new ApiException(&quot;NOT_FOUND&quot;, &quot;User not found&quot;, 404);<br>throw new ApiException(&quot;UNAUTHORIZED&quot;, &quot;You are not authorized&quot;, 401);<br>throw new ApiException(&quot;VALIDATION_ERROR&quot;, &quot;Validation failed&quot;, 400, errors);</pre><pre>// ✅ AFTER — static factory methods<br>throw ApiException.userNotFound(&quot;id: &quot; + id);<br>throw ApiException.unauthorized();<br>throw ApiException.validationError(errors);</pre><p>The after version is shorter, safer, and reads like a sentence.</p><h3>❗ Common Mistakes</h3><p><strong>1. Leaving the constructor public</strong> If new ApiException(...) is still public, teammates will use it — and bypass every factory method you built. Always make the constructor private.</p><p><strong>2. Caching exceptions that carry variable data</strong> UNAUTHORIZED is safe to cache because it never changes. But notFound(String message) must create a new object every time — the message is different each call.</p><p><strong>3. Naming factory methods like constructors</strong> ApiException.create(...) is no better than new ApiException(...). Use meaningful names: notFound, unauthorized, validationError.</p><p><strong>4. Skipping domain-specific methods</strong> ApiException.notFound(&quot;User not found with id: &quot; + id) is good. ApiException.userNotFound(&quot;id: &quot; + id) is better. The extra layer costs nothing and makes service code much easier to read.</p><p><strong>5. Repeating the same string in multiple factory methods</strong> &quot;NOT_FOUND&quot; should appear in exactly one place. If two methods both hardcode &quot;NOT_FOUND&quot;, they will drift apart over time. Use constants or delegate to a shared private of() method.</p><h3>💡 Summary — What Effective Java Item 1 Gives You</h3><p>Advantage What It Means in Practice <strong>Meaningful names</strong> unauthorized() beats new ApiException(&quot;UNAUTHORIZED&quot;, ..., 401) <strong>Instance caching</strong> UNAUTHORIZED and FORBIDDEN are created once, reused forever <strong>Hidden implementation</strong> Private of() helpers remove duplication without polluting the public API <strong>Domain language</strong> userNotFound(&quot;email&quot;) reads like a sentence, not a constructor call <strong>No parameter confusion</strong> Private constructor means you can never get the argument order wrong</p><p><em>Found this useful? Hit the clap button 👏 and follow.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3315ffb84496" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PostgreSQL Search — Part 1: Why LIKE and ILIKE Will Eventually Let You Down]]></title>
            <link>https://medium.com/@sarvar55mszde/postgresql-search-part-1-why-like-and-ilike-will-eventually-let-you-down-d500a99d6358?source=rss-4e7b1393b87c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d500a99d6358</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[index]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Sarvar Musazade]]></dc:creator>
            <pubDate>Wed, 06 May 2026 15:23:01 GMT</pubDate>
            <atom:updated>2026-05-06T15:23:01.421Z</atom:updated>
            <content:encoded><![CDATA[<p>You built a search feature in one afternoon. It worked perfectly. Then your app grew — and everything broke. Sound familiar? Let’s talk about why LIKE and ILIKE are a trap for growing apps, and what you should do instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*LBy73Rb0vFmd_hb35jBvKg.png" /></figure><h3>🧑‍💻 The Story — A Search Box That Hides a Time Bomb</h3><p>You just launched a blog platform. Users write posts. Other users want to search for them by title.</p><p>Simple enough. Your posts table looks like this:</p><pre>CREATE TABLE posts (<br>    id      SERIAL PRIMARY KEY,<br>    title   TEXT,<br>    content TEXT<br>);</pre><p>You add some data:</p><pre>INSERT INTO posts (title, content) VALUES<br>(&#39;How to make pancakes&#39;,           &#39;A delicious breakfast recipe...&#39;),<br>(&#39;How to make pizza from scratch&#39;,  &#39;The best homemade pizza...&#39;),<br>(&#39;How to make your bed properly&#39;,   &#39;A clean room starts here...&#39;),<br>(&#39;Learning PostgreSQL basics&#39;,      &#39;Database fundamentals...&#39;),<br>(&#39;Advanced SQL techniques&#39;,         &#39;For senior developers...&#39;);</pre><p>A user opens your app and types <strong>“how to make”</strong> in the search box.</p><p>You think: <em>“Easy — I’ll just filter by title.”</em></p><p>You Google it. You find LIKE and ILIKE. They look simple. You use them. The feature works.</p><p>Two months later, you regret it. Let’s understand why. 👇</p><h3>🔍 What is LIKE?</h3><p>LIKE is a SQL operator that searches for a <strong>pattern</strong> inside a text column.</p><p>Think of it like a basic text filter. You describe the shape of what you’re looking for, and LIKE finds rows that match that shape.</p><p>You use two wildcard characters:</p><p>Symbol Meaning % Any sequence of characters (including none) _ Exactly one character</p><h3>Example 1 — Find posts that start with “How to make”</h3><pre>SELECT title<br>FROM posts<br>WHERE title LIKE &#39;How to make%&#39;;</pre><p><strong>Result:</strong></p><pre>How to make pancakes<br>How to make pizza from scratch<br>How to make your bed properly</pre><p>✅ Works great. The % at the end means <em>&quot;anything can follow.&quot;</em></p><h3>Example 2 — Find posts that contain “SQL” anywhere</h3><pre>SELECT title<br>FROM posts<br>WHERE title LIKE &#39;%SQL%&#39;;</pre><p><strong>Result:</strong></p><pre>Learning PostgreSQL basics<br>Advanced SQL techniques</pre><p>✅ The % on both sides means <em>&quot;SQL can appear anywhere in the title.&quot;</em></p><h3>Example 3 — The _ wildcard (match exactly one character)</h3><pre>SELECT title<br>FROM posts<br>WHERE title LIKE &#39;How to make p_zzas&#39;;</pre><p>This matches &quot;How to make pizzas&quot; — but not &quot;How to make pancakes&quot;, because _ is <strong>exactly one</strong> character, not many.</p><p>This wildcard is rarely used in practice, but good to know.</p><h3>⚠️ The First Problem — LIKE is Case-Sensitive</h3><p>Here is where things break for real users.</p><p>Your user opens the app and types &quot;how to make&quot; — all lowercase. This is completely normal. Most people don&#39;t bother capitalising search queries.</p><pre>SELECT title<br>FROM posts<br>WHERE title LIKE &#39;how to make%&#39;;</pre><p><strong>Result:</strong></p><pre>(0 rows)</pre><p>❌ Nothing. Zero results.</p><p>Why? Because LIKE is <strong>case-sensitive</strong>. It sees &quot;how&quot; and &quot;How&quot; as two completely different words. Your titles start with a capital &quot;H&quot;, so nothing matches.</p><p>This will frustrate your users. They typed the right words — and got nothing back.</p><h3>🔍 What is ILIKE? (The Case-Insensitive Fix)</h3><p>ILIKE is PostgreSQL&#39;s case-insensitive version of LIKE. It works identically, except it doesn&#39;t care about uppercase or lowercase.</p><blockquote><em>💡 Note: </em><em>ILIKE is a PostgreSQL-specific feature. It does not exist in standard SQL or in databases like MySQL.</em></blockquote><pre>SELECT title<br>FROM posts<br>WHERE title ILIKE &#39;how to make%&#39;;</pre><p><strong>Result:</strong></p><pre>How to make pancakes<br>How to make pizza from scratch<br>How to make your bed properly</pre><p>✅ Now it works — no matter how the user typed it.</p><h3>More ILIKE Examples</h3><pre>-- User types &quot;PIZZA&quot; (all caps)<br>SELECT title FROM posts WHERE title ILIKE &#39;%pizza%&#39;;<br>-- Result: How to make pizza from scratch</pre><pre>-- User types &quot;pOsTgReSQL&quot; (random case)<br>SELECT title FROM posts WHERE title ILIKE &#39;%postgresql%&#39;;<br>-- Result: Learning PostgreSQL basics</pre><p>ILIKE handles all of these cleanly. For a small app, this feels like the perfect solution.</p><p>And it is — until your data grows.</p><h3>😬 The Second Problem — Performance</h3><p>For a while, everything is fine. Your blog has 500 posts. Search is instant. Users are happy.</p><p>Then your app goes viral. 🎉</p><p>You now have <strong>500,000 posts</strong>.</p><p>Users start complaining:</p><blockquote>“Why does search take 5 seconds?”<em> </em>“The app is broken!”</blockquote><p>You open your database and run EXPLAIN ANALYZE — a PostgreSQL command that shows you exactly how a query is executed and how long it takes:</p><pre>EXPLAIN ANALYZE<br>SELECT title<br>FROM posts<br>WHERE title ILIKE &#39;%how to make%&#39;;</pre><p>You see this:</p><pre>Seq Scan on posts  (cost=0.00..12543.00 rows=500000 ...)<br>  Filter: (title ~~* &#39;%how to make%&#39;)<br>  Rows Removed by Filter: 499,850<br>Planning Time: 0.1 ms<br>Execution Time: 4823.7 ms  ← 💀 nearly 5 seconds</pre><p>The key word here is <strong>Seq Scan</strong> — Sequential Scan.</p><p>It means PostgreSQL is opening every single row, reading the title, and checking if it matches. All 500,000 of them. One by one.</p><p><strong>Analogy:</strong> Imagine you’re looking for a word in a book — but instead of using the index at the back, you read every single page from start to finish. That’s exactly what a sequential scan does.</p><h3>🤔 “Can I Just Add an Index?”</h3><p>This is the first thing every developer tries. You add a standard B-Tree index on the title column:</p><pre>CREATE INDEX idx_posts_title ON posts (title);</pre><p>You run the query again. Still slow. 😕</p><p>Here’s why:</p><p>A B-Tree index works like a <strong>sorted dictionary</strong>. It can quickly jump to words that <strong>start with</strong> a specific letter or prefix. For example, a search like &#39;How to make%&#39; (no leading %) could potentially use this index.</p><p>But the moment your pattern has a <strong>leading </strong><strong>%</strong> — like &#39;%how to make%&#39; — the database has no idea where to start looking. The match could appear at any position in any title. So it ignores the index completely and does a full table scan anyway.</p><p>And with ILIKE, there&#39;s another layer of pain: even a &#39;How to make%&#39; pattern won&#39;t use a standard B-Tree index properly, because the index stores values in their original case — it doesn&#39;t know how to handle case-insensitive comparisons.</p><p>So adding a plain index doesn’t help here.</p><h3>❗ Common Mistakes Developers Make</h3><p>Here are the most common traps developers fall into with LIKE and ILIKE:</p><p><strong>1. Using LIKE in production without testing on large data</strong> It works perfectly on your dev machine with 100 rows. You deploy. Six months later, the database has 200,000 rows and search crawls to a halt.</p><p><strong>2. Thinking a standard index will fix the problem</strong> As explained above, a B-Tree index does not help with leading % wildcards or ILIKE.</p><p><strong>3. Adding </strong><strong>LOWER() as a workaround instead of ILIKE</strong> Some developers write WHERE LOWER(title) LIKE LOWER(&#39;%search%&#39;). This works but is even slower — PostgreSQL has to call the LOWER() function on every single row.</p><p><strong>4. Using ILIKE for multi-word search without thinking about word order</strong> ILIKE &#39;%pizza make%&#39; will NOT find &quot;How to make pizza&quot; — because the words are in a different order. ILIKE matches exact substrings, not individual words.</p><p><strong>5. Not monitoring slow queries</strong> PostgreSQL has a built-in tool called pg_stat_statements that logs slow queries. Most developers don&#39;t enable it — and they only discover the ILIKE problem when users are already complaining.</p><h3>💡 Practical Tips</h3><ul><li>Always test your search queries with EXPLAIN ANALYZE before going to production.</li><li>If your dataset is small (under ~10,000 rows) and you use prefix search (&#39;word%&#39;), LIKE/ILIKE with an index is fine.</li><li>If you need ILIKE with a leading %, plan for an upgrade path early. Either <strong>pg_trgm</strong> (for fuzzy/partial search) or <strong>Full-Text Search</strong> (for natural language search) will serve you much better at scale.</li><li>Use ILIKE over manual LOWER() tricks — it&#39;s cleaner and the performance is the same.</li></ul><h3>🔍 LIKE vs ILIKE (Quick)</h3><ul><li><strong>Case-sensitive</strong> → LIKE ✅ | ILIKE ❌</li><li><strong>Standard SQL</strong> → LIKE ✅ | ILIKE ❌ (PostgreSQL only)</li><li><strong>Small data</strong> → Both fast ✅</li><li><strong>Large data</strong> → Both slow ⚠️</li><li><strong>Index usage</strong> → LIKE (no leading % only) | ILIKE (rare)</li><li><strong>Understands words?</strong> → ❌ No</li><li><strong>Relevance ranking?</strong> → ❌ No</li></ul><h3>🔜 What’s Next?</h3><p>LIKE and ILIKE are great for getting started — but they don&#39;t scale, and they have no intelligence about language.</p><p>In the next parts of this series, we’ll fix both problems:</p><ul><li><strong>Part 2 — PostgreSQL Trigrams (</strong><strong>pg_trgm):</strong> Make ILIKE-style search fast at any scale — plus handle typos like &quot;postgress&quot; finding &quot;PostgreSQL&quot;</li><li><strong>Part 3 — Full-Text Search (</strong><strong>to_tsvector, </strong><strong>to_tsquery):</strong> Build a real search engine inside PostgreSQL, with language awareness and result ranking</li></ul><p>By the end of the series, you’ll know exactly which tool fits your use case — and you’ll never ship a slow search feature again. 🚀</p><p><em>Found this useful? Hit the clap button 👏 and follow for Part 2 — dropping soon.</em></p><p><a href="https://niallburkley.com/blog/index-columns-for-like-in-postgres/">https://niallburkley.com/blog/index-columns-for-like-in-postgres/</a></p><p><a href="https://dev.to/tdournet/how-to-optimise-postgresql-like-and-ilike-queries-494i">https://dev.to/tdournet/how-to-optimise-postgresql-like-and-ilike-queries-494i</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d500a99d6358" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is a CPU, and What Does it Do?]]></title>
            <link>https://medium.com/@sarvar55mszde/what-is-a-cpu-and-what-does-it-do-a1ee3ce7a100?source=rss-4e7b1393b87c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1ee3ce7a100</guid>
            <category><![CDATA[cpu]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[cores]]></category>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[os]]></category>
            <dc:creator><![CDATA[Sarvar Musazade]]></dc:creator>
            <pubDate>Tue, 24 Sep 2024 10:16:37 GMT</pubDate>
            <atom:updated>2024-09-28T08:46:03.853Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*1BlN23LZx7D-bSLA1ddJPQ.png" /></figure><p><strong>A Journey into the Amazing World of CPU 🧠💻🍳<br></strong>Let’s take a journey into the brain of your computer! <br>Have you ever wondered how your computer can think and work so fast? This is where the hidden hero comes in: The CPU, or Central Processing Unit.<br>The CPU can be likened to the chef cook in a kitchen.</p><p>How? 🧑‍🍳<br>Imagine this: Your computer is a huge restaurant, and you are the owner. Your customers (that’s you, the user) are constantly placing different orders: Play a video, send an email, print a document.<br>At this point, deep in the kitchen, there is a superhero who takes all these ‘orders’ and fulfills them: CPU Chef! 🦸‍♂️</p><h4><strong><em>What is CPU?</em></strong></h4><p>The CPU (Central Processing Unit) is the brain of the computer, responsible for executing instructions, performing calculations, and managing data processing. It controls communication between input and output devices and ensures the smooth operation of tasks. The CPU is made up of smaller components that work together, making it a crucial part of any computing device.<em> </em><strong><em>The CPU’s performance is typically measured by its clock speed, which indicates how many instructions it can execute per second.</em></strong> However, other factors like the number of cores, cache size, and architecture also impact the overall performance of a CPU.</p><h4><strong>Super Powers of our CPU Chief 🦸‍♂️🍳</strong></h4><p>So, what does our kitchen superhero CPU Chef do? Here are his amazing skills:</p><h4><strong>Calculation Master</strong></h4><p>🧮CPU Chief is like a math genius. He does billions of addition, subtraction, multiplication and division operations per second. Imagine, before you can say “1+1”, it has already done a million operations!</p><h4><strong>Decision Making Machine🤔</strong></h4><p>“If this file exists, open it. If not, create a new one.” The CPU Chief makes such ‘if-then’ decisions in the blink of an eye. Like a sage, he instantly finds the right solution for every situation.</p><h4><strong>Data Carrier🏃‍♂️💨</strong></h4><p>The CPU Chief is like a waiter running all over your computer. It takes data from memory, processes it and puts it back. It does this so fast that your eyes will blur!</p><h4><strong>Traffic Police 🚦👮</strong></h4><p>It manages all the processes on your computer. It decides which program runs when, which data goes where. It is like a policeman who alone manages the traffic lights of a whole city!</p><h4><strong>Translator 🗣️🌐</strong></h4><p>The CPU Chief understands the computer language (machine code) and translates it so that other components understand it. It’s like an interpreter who can speak hundreds of languages at once! A micro-sized superhero on a tiny chip, doing all this work in a millionth of a second. That’s why your computer can “think” and fulfill your wishes instantly!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*TgsCWR1taLn0BJZJuLwJRg.png" /></figure><h4><strong>Key Components and Tasks of the CPU</strong></h4><h4><strong>Arithmetic Logic Unit (ALU)</strong></h4><p>The ALU is the part of the CPU that performs mathematical and logical operations. It performs arithmetic operations such as addition, subtraction, multiplication, division and logical operations such as AND, OR, NOT.</p><h4><strong>Control Unit</strong></h4><p>The Control Unit is the “brain” part of the CPU. It decodes, interprets and executes commands. It controls the program flow and tells other units what to do.</p><h4><strong>Registers</strong></h4><p>Registers are small, fast memory units in the CPU. They have tasks such as storing temporary data, holding addresses and storing process results.</p><h4><strong>Cache</strong></h4><p>Cache is a small but very fast type of memory that allows fast data exchange between the CPU and main memory.</p><h4><strong>Buses</strong></h4><p>Data buses are the channels that allow data to flow within the CPU and between the CPU and other hardware components.These components combine to perform the CPU’s basic tasks: Perform arithmetic and logical operations</p><ul><li>Controlling program flow</li><li>Data migration and management</li><li>Memory management</li></ul><p><strong><em>Let’s think about this with an example from everyday life:</em></strong></p><p>You can imagine the CPU as the kitchen of a restaurant. In this kitchen</p><ul><li><strong>ALU (Arithmetic Logic Unit)</strong>: The ALU is like the cook in the kitchen who does the actual chopping, stirring, and cooking. It handles the arithmetic (like adding or subtracting ingredients) and logical decisions (like deciding if a dish is done or needs more seasoning). The ALU is all about the hands-on tasks.</li><li><strong>Control Unit</strong>: The Control Unit is the head chef in charge of managing the kitchen. The head chef doesn’t cook, but ensures everything runs smoothly, giving orders to the ALU (the cooks), telling them what to do, when to do it, and in what order. It coordinates the entire cooking process.</li><li><strong>Registers</strong>: Registers are like the small preparation counters in front of the cooks. These counters hold the ingredients and tools that the cook (ALU) needs right away, making sure the cook has everything within reach to work quickly and efficiently.</li><li><strong>Cache</strong>: The cache is like a cupboard in the kitchen that holds the ingredients and tools used most frequently, such as salt, pepper, or a chef’s favorite knife. The cache is close to the preparation area, so the cooks (ALU) can grab what they need without having to go to the pantry (main memory) all the time.</li><li><strong>Buses</strong>: Buses are like the corridors and passageways in the kitchen that allow the head chef, cooks, and waiters to move around and deliver food and ingredients. They make sure information (or orders)flows smoothly between the different parts of the kitchen.</li></ul><p>In this kitchen, <strong>orders</strong> (commands) come in from customers (the user or program), and the <strong>head chef</strong> (Control Unit) interprets these orders and gives instructions to the other chefs (the ALU and other units). The cooks work by preparing ingredients on the <strong>preparation counters</strong> (Registers) in front of them, ensuring everything is ready for cooking. When they need something quickly, they retrieve ingredients from the <strong>handy cupboard</strong> (Cache), where frequently used items are stored. To move ingredients and information between areas of the kitchen, they use the <strong>corridors and passageways</strong> (Buses).</p><h3>Core Processor in a Computer</h3><p>A single CPU can only process one task at a time, but modern computers can handle multitasking effortlessly. Let’s explore how this became possible.</p><h4><strong>Example for clarity</strong></h4><p>Imagine you’re playing a computer game while listening to music in the background. In the past, the CPU could only do one of these tasks at a time either you played the game or listened to music. But today, processors are designed to handle both tasks simultaneously. This means you can play your game and listen to music at the same time without losing performance.</p><h3><strong>Multiple Cores</strong></h3><p>One of the main reasons modern computers can multitask so efficiently is due to multiple cores. In the past, CPUs had only one core, meaning they could process only one task at a time. To improve performance, manufacturers started adding more cores. For example, a dual-core CPU has two processing units, allowing it to handle two tasks simultaneously, which makes the system faster. CPUs with more cores, like quad-core (four cores) or octa-core (eight cores), can manage even more tasks at once.</p><h4><strong>Example for clarity</strong></h4><p>Imagine you are editing a video and browsing the internet at the same time. With a single-core CPU, these tasks would have to take turns, slowing down your computer. But with a quad-core CPU, one core can handle the video editing, while another core processes the browsing, allowing both tasks to run smoothly without causing delays.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*lKMxIT-L80QNnjHlB_Q7mg.png" /></figure><h3>Hyper-threading</h3><p>Hyper-threading is a technology introduced by Intel to improve multitasking and performance. First launched in 2002, it allows a single CPU core to act as if it has multiple cores. This trick makes the operating system think there are several CPUs, even though there’s only one. For instance, a single-core CPU with hyper-threading will appear as two logical CPUs to the operating system, and a dual-core CPU will appear as four. This helps the computer run tasks more efficiently by better managing hardware resources.</p><h4><strong>Example for clarity</strong></h4><p>Imagine you have a single-core CPU with hyper-threading. Even though it has just one physical core, hyper-threading makes your computer act as if it has two cores. This means when you’re running multiple programs, like a word processor and a web browser, your computer can handle them more effectively, making it seem like it’s multitasking even though it’s using just one physical core.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*shYpbVCkYYHEBjp8JFAraA.png" /></figure><h3>What Are Threads?</h3><p>Threads are virtual components or codes that divide the physical core of a CPU into virtual multiple cores. A single CPU core can have up to 2 threads per core. For example:</p><ul><li>A dual-core CPU (2 cores) will have 4 threads</li><li>An octa-core CPU (8 cores) will have 16 threads</li></ul><h3>How Threads Work</h3><ol><li><strong>Creation</strong>: Threads are created by processes. When you open an application, it creates a thread to handle all tasks specific to that application.</li><li><strong>Operating System Role</strong>: The operating system creates threads to perform tasks for specific applications.</li><li><strong>Primary Thread</strong>: Each core has a single thread (primary thread) that performs computations.</li><li><strong>Task Allocation</strong>: When the primary thread receives information from the user, it creates additional threads and allocates tasks to them.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*ty4lCSjCC9b3hqXjL2Vw5Q.png" /></figure><h3>Applications and Their Functions</h3><ol><li>Spotify:</li></ol><ul><li>Main function: Playing music and showing the user interface</li><li>Background tasks: Downloading songs and updating playlists</li></ul><p>Imagine Spotify as a music player on your phone. While you’re browsing through songs and listening to music (main thread), it’s also working behind the scenes to download new tracks you’ve added and keep your playlists up to date (background thread).</p><ol><li>YouTube:</li></ol><ul><li>Main function: Playing videos and displaying the user interface</li><li>Background tasks: Buffering video and loading comments</li></ul><p>Think of YouTube like watching TV. The main screen shows your video and lets you choose what to watch next. At the same time, it’s preparing the next part of the video so it plays smoothly (buffering) and getting ready to show you comments from other viewers.</p><h4>CPU Cores vs Threads: What is the Difference?</h4><p>In the world of modern computing, understanding the relationship between CPU cores and threads is crucial for grasping how our computers handle multiple tasks simultaneously. This article aims to demystify these concepts and provide real-world examples of their importance. To put it simply, you can think of the core as the mouth of a person, while threads can be compared with the hands of a human being. As you know that the mouth is responsible for carrying out the eating, on the other hand, the hands help organize the ‘workload.’</p><h3>Fun Explanation: Threads and the Juggling Circus</h3><p>Imagine your computer as a grand circus and the CPU as the star juggler performing on stage.</p><h3>Thread = Ball in the Juggler’s Hand</h3><ul><li>Each ball represents a task that the juggler holds in the air.</li><li><strong>Single Thread vs Multi-Thread</strong></li><li><strong>Old Juggler (Single Thread CPU):</strong> This juggler can only throw and catch one ball at a time.</li><li><strong>Modern Juggler (Multi-Thread CPU):</strong> This juggler can keep many balls in the air simultaneously.</li></ul><h3>Parallel Processing</h3><ul><li>Just like a juggler who can keep multiple balls in the air at once, a CPU can handle several tasks at the same time.</li></ul><h3>Single CPU, Single Thread</h3><ul><li>This scenario is akin to a circus where there is only one juggler, and he performs with just one ball at a time.</li></ul><h3>Hyper-Threading</h3><ul><li>Imagine our juggler magically growing two extra arms!</li><li>With these additional arms, he can perform tasks that usually require two jugglers working separately.</li></ul><h3>The Benefit of Threads</h3><ul><li>The more balls our juggler can keep in the air at once (multi-threading), the more impressive and faster the show becomes.</li><li>Similarly, having multiple threads boosts your computer’s performance, allowing it to handle more tasks efficiently.</li></ul><h3>In Summary</h3><p>The CPU is the brain of the computer; every process, every click is its creation. It’s the silent hero turning our dreams into code and our ideas into reality. But the real magic happens when it comes to life through your commands. So, don’t just see your computer as a tool — think of it as your own digital stage, and you’re the star ready to leave your mark. Now, enjoy the thrill of mastering that mysterious world inside your computer! I hope everything’s clearer after this post — if it is, I’ll take a ‘like’ or maybe a comment. 😊</p><p><a href="https://www.redswitches.com/blog/cores-vs-threads/">https://www.redswitches.com/blog/cores-vs-threads/</a><br><a href="https://www.geeksforgeeks.org/thread-in-operating-system/">https://www.geeksforgeeks.org/thread-in-operating-system/</a><br><a href="https://www.freecodecamp.org/news/what-is-cpu-meaning-definition-and-what-cpu-stands-for/">https://www.freecodecamp.org/news/what-is-cpu-meaning-definition-and-what-cpu-stands-for/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1ee3ce7a100" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>