💡 Value Object vs Entity in Java In domain-driven design (DDD), not all objects are the same. Some are defined by identity, while others are defined by their values. Let’s break it down simply 👇 🔹 Entity An Entity is an object that has a unique identity, even if its data changes. Example: A User in a system. User(id=101, name="John") Even if the name changes to "Johnny", it’s still the same user because the ID stays the same. Key points: • Has a unique identifier (ID) • Mutable (state can change) • Equality based on identity Example: class User { Long id; String name; } 🔹 Value Object A Value Object is defined only by its values, not identity. Example: Money, Address, Coordinates. Money(500, "INR") Money(500, "INR") Both are equal because their values are the same. Key points: • No identity • Usually immutable • Equality based on values Example: class Money { final int amount; final String currency; } 🧠 Rule of Thumb If the object needs a unique identity → Entity If the object is defined only by data → Value Object 👉 If you are preparing for backend interviews, connect & follow - I share short, practical backend concepts regularly. #Java #SpringBoot #BackendDevelopment #JavaDeveloper #SystemDesign #SoftwareEngineering #CleanCode #JavaTips
Java Domain-Driven Design: Entities vs Value Objects
More Relevant Posts
-
Java records are powerful. But they are not a replacement for every POJO. That is where many teams get the migration decision wrong. A record is best when your type is mainly a transparent carrier for a fixed set of values. Java gives you the constructor, accessors, equals(), hashCode(), and toString() automatically, which makes records great for DTOs, request/response models, and small value objects. But records also come with important limits. A record is shallowly immutable, its components are fixed in the header, it cannot extend another class because it already extends java.lang.Record, and you cannot add extra instance fields outside the declared components. You can still add validation in a canonical or compact constructor, but records are a poor fit when the model needs mutable state, framework-style setters, or inheritance-heavy design. So the real question is not: “Should we convert all POJOs to records?” The better question is: “Which POJOs are actually just data carriers?” That is where records shine. A practical rule: use records for immutable data transfer shapes, keep normal classes for JPA entities, mutable domain objects, lifecycle-heavy models, and cases where behavior and state evolve over time. Also, one important clarification: this is not really a “Java 25 only” story. Records became a permanent Java feature in Java 16, and Java 25 documents them as part of the standard language model. So no, the answer is not “change every POJO to record.” Change only the POJOs that truly represent fixed data. Where do you draw the line in your codebase: DTOs only, or value objects too? #Java #Java25 #JavaRecords #SoftwareEngineering #BackendDevelopment #CleanCode #JavaDeveloper #Programming #SystemDesign #TechLeadership
To view or add a comment, sign in
-
-
Ever wondered why ArrayList is fast… until it suddenly isn’t? Most of us use ArrayList daily in Java. But very few actually think about what’s happening internally. Let’s break it down in a simple way. ➤ What is ArrayList internally? ArrayList is backed by a dynamic array. That means: • It uses a normal array under the hood • But it can grow automatically when needed ➤ Why is ArrayList so fast? When you do: list.get(index); It directly accesses the element using index. 👉 No looping 👉 No searching That’s why read operation = O(1) (very fast) ➤ Then where is the catch? The problem starts when the array gets full. Let’s say: Current capacity = 10 You try to add 11th element Now Java does something expensive: 1. Creates a new bigger array 2. Copies all old elements 3. Adds the new element 👉 This is called resizing ➤ How much does it grow? It doesn’t just add 1 more space. New capacity = old capacity + (old capacity / 2) 👉 ~1.5x growth This helps reduce frequent resizing, but still… ⚠️ Resizing = costly operation ➤ Why adding in middle is slow? If you do: list.add(0, element); All elements shift one position to the right. 👉 Time complexity = O(n) ➤ Real-world analogy Think of ArrayList like a row of fixed seats: • Sitting in an empty seat → fast • All seats full → need a bigger row (move everyone) • Inserting in middle → everyone shifts ➤ Pro Developer Tip If you already know the size: new ArrayList<>(1000); 👉 Avoids multiple resizes 👉 Improves performance significantly ➤ Key Takeaway ArrayList is fast because of: • Direct index access But it becomes slow when: • Resizing happens • Frequent insertions in middle #Java #ArrayList #CoreJava #DataStructures #Performance #SoftwareEngineering
To view or add a comment, sign in
-
Managing native memory in Java has become more accessible with the Foreign Function & Memory API. But how do you choose between arenas, malloc, and custom pools? David Vlijmincx breaks down the different approaches to native memory allocation in Java, comparing their performance characteristics and use cases. This guide helps you understand when to use each allocation strategy and what trade-offs to consider. Whether you're working with off-heap data structures or interfacing with native libraries, this article provides practical insights into memory-management patterns to improve your application's performance. Read the full article here: https://lnkd.in/ebjUskrN #Java #Performance #NativeMemory #FFM
To view or add a comment, sign in
-
🚀 Day 5 of my Java journey — Abstraction, Enums, Lambda! Today was a deep dive into some of the most powerful features of Java! 🔥 🏗️ Abstract Class — deeper understanding ✅ Abstract class cannot be instantiated directly ✅ BUT you can create an anonymous class from it on the spot! ✅ This is how Java gives flexibility without creating a full new class 🔗 Interface — deeper concepts ✅ Interface can extend another interface ✅ A class can implement multiple interfaces ✅ Deep abstraction — hide implementation, show only what matters 🎯 Types of Interfaces in Java ✅ Normal interface — only abstract methods ✅ Functional interface — exactly ONE abstract method (used with lambda!) ✅ Marker interface — no methods at all, just marks a class (e.g. Serializable) 🔢 Enum in Java ✅ Enum = a fixed set of constants ✅ Example: Days of week, Directions (NORTH, SOUTH, EAST, WEST) ✅ Much safer than using plain int or String constants 💡 Functional Interface + Lambda Expression ✅ @FunctionalInterface annotation — only 1 abstract method allowed ✅ Lambda replaces the need to write a full class! ✅ Before lambda: create a class, implement method, create object ✅ With lambda: just write the logic in one line — clean and powerful! Example: A obj = (int a) -> { System.out.println("Hello from lambda!"); }; obj.show(5); Java is getting more and more interesting every day! 🚀 Day 1 ✅ | Day 2 ✅ | Day 3 ✅ | Day 4 ✅ | Day 5 ✅ ... #Java #JavaDeveloper #Lambda #FunctionalInterface #Enum #Abstraction #100DaysOfCode #BackendDevelopment #TechCareer #LearningToCode
To view or add a comment, sign in
-
Every Java developer knows Java is a type-safe language. But does that mean we never face type issues? Definitely not. We still run into type concerns here and there but that hasn’t stopped Java from being one of the most reliable languages in backend engineering. At some point in our journey, many of us start by solving problems quickly and then writing wrappers just to convert types. I’ve done it more times than I can count. Then I learned 𝐆𝐞𝐧𝐞𝐫𝐢𝐜𝐬. I had seen them everywhere in Java code: <𝘛>, <?>, <? 𝘦𝘹𝘵𝘦𝘯𝘥𝘴 𝘚𝘰𝘮𝘦𝘵𝘩𝘪𝘯𝘨>. And honestly… at first they looked intimidating. But once it clicked, it completely changed how I structure reusable code. 𝐓𝐡𝐞 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 We’ve all had that situation where one code base is implemented the same way for different types. Each class looked almost identical. Same logic. Same structure. Only the type changes. And we all know the 𝐃𝐑𝐘 (Don't Repeat Yourself) principle. What Generics does: With Generics, we write that logic once using a WrapperClass<T> class. Now it works for any type (`ProductResponse`, `OrdersResponse`, `UserResponse`...) without code duplication. No duplication. No casting. No ClassCastException surprises. The compiler now has your back. Check the image for a real-world application In real 𝐛𝐚𝐜𝐤𝐞𝐧𝐝 𝐬𝐲𝐬𝐭𝐞𝐦𝐬 (especially in 𝐒𝐩𝐫𝐢𝐧𝐠 𝐁𝐨𝐨𝐭), we often return a standard API response structure. Without generics, you might end up with UserResponse, OrdersResponse, ProductResponse ... all with the same structure. With generics, you create a single 𝐀𝐩𝐢𝐑𝐞𝐬𝐩𝐨𝐧𝐬𝐞<𝐓> class. Now your controllers can return any type safely (ApiResponse<UserResponse>, ApiResponse<ProductResponse>, ApiResponse<List<OrdersResponse>>, etc.). One class. Infinite flexibility. Fully type-safe. This is where generics really shine in production systems. It’s amazing how much cleaner, safer, and more reusable code becomes once you start rethinking your engineering process. If you’ve been seeing <T> everywhere in Java codebases, now you know why. 😉 #Java #SoftwareEngineering #CleanCode #Generics #SpringBoot
To view or add a comment, sign in
-
-
🔐 Ever wondered what it takes to build transactional maps from scratch in Java? Over the past few weeks, I deep-dived into implementing multiple transactional map designs — each with different isolation levels and fascinating trade-offs. Here's what I explored: 🔵 **Optimistic & Pessimistic Maps** — READ COMMITTED globally, SERIALIZABLE per-key. Smart lock upgrading prevents deadlocks, while semantic awareness avoids unnecessary SIZE locks. 🟡 **Read Uncommitted Map** — Dirty reads allowed! Store buffers give you read-your-own-writes consistency without any blocking. ⚪ **Snapshot-based Map** — Copy-on-write via CAS. Beautiful simplicity, brutal under write-heavy workloads ⚡ **Flat Combining Maps** — Instead of threads fighting for locks, they cooperate! One combiner batches and applies operations. Surprisingly, a single combiner outperforms segmented ones due to better amortization. 🕰️ **MVCC Map** — Version chains per key. Readers never block writers, writers never block readers. Pure elegance. Each design reveals a different philosophy about concurrency — there's no silver bullet, only trade-offs! 💬 Which isolation level do YOU prioritize in your systems — performance or consistency? #Java #Concurrency #DatabaseInternals #DataStructures #SoftwareEngineering #BackendDevelopment #SystemsDesign
To view or add a comment, sign in
-
-
10 Modern Java Features Senior Developers Use to Write 50% Less Code 12 years of writing Java taught me one thing: The gap between a junior and senior dev isn’t just system design or DSA. It’s knowing which language feature kills which boilerplate. Most teams I’ve seen are still writing Java 8 style code — in 2025. Verbose DTOs. Null-check pyramids. Blocking futures. Fall-through switch bugs. Meanwhile Java 17–21 ships features that do the same job in 20% of the lines. The PDF covers all 10 with real before/after examples: ✦ Records → kill 25-line data classes ✦ Sealed Classes → compiler-enforced polymorphism ✦ Pattern Matching → no more redundant casts ✦ Switch Expressions → no more fall-through bugs ✦ Text Blocks → readable SQL/JSON/HTML in code ✦ var → less noise, same type safety ✦ Stream + Collectors → declarative data pipelines ✦ Optional done right → zero NPE by design ✦ CompletableFuture → parallel API calls cleanly ✦ Structured Concurrency → the future of Java async Every feature includes a Pro Tip from production experience. Drop a comment: which Java version is your team actually running? I’ll reply to every answer. ♻️ Repost to help a Java dev on your team level up. #Java #Java21 #SpringBoot #BackendEngineering #SoftwareEngineering #PrincipalEngineer #CleanCode #TechLeadership
To view or add a comment, sign in
-
the evolution is huge and it keeps growing way more with java 26.... leaves one wondering the integration with AI and what to expect in upcoming versions
Full-Stack Principal Engineer | AI · LLM · RAG Pipelines · AWS · Java · Node.js . LangGraph | 12+ Years
10 Modern Java Features Senior Developers Use to Write 50% Less Code 12 years of writing Java taught me one thing: The gap between a junior and senior dev isn’t just system design or DSA. It’s knowing which language feature kills which boilerplate. Most teams I’ve seen are still writing Java 8 style code — in 2025. Verbose DTOs. Null-check pyramids. Blocking futures. Fall-through switch bugs. Meanwhile Java 17–21 ships features that do the same job in 20% of the lines. The PDF covers all 10 with real before/after examples: ✦ Records → kill 25-line data classes ✦ Sealed Classes → compiler-enforced polymorphism ✦ Pattern Matching → no more redundant casts ✦ Switch Expressions → no more fall-through bugs ✦ Text Blocks → readable SQL/JSON/HTML in code ✦ var → less noise, same type safety ✦ Stream + Collectors → declarative data pipelines ✦ Optional done right → zero NPE by design ✦ CompletableFuture → parallel API calls cleanly ✦ Structured Concurrency → the future of Java async Every feature includes a Pro Tip from production experience. Drop a comment: which Java version is your team actually running? I’ll reply to every answer. ♻️ Repost to help a Java dev on your team level up. #Java #Java21 #SpringBoot #BackendEngineering #SoftwareEngineering #PrincipalEngineer #CleanCode #TechLeadership
To view or add a comment, sign in
-
🚀 Day 19/100: The Grammar of Java – Writing Clean & Readable Code 🏷️✨ Today’s focus was on something often underestimated but critically important in software development—writing code that humans can understand. In a professional environment, code is not just for the compiler; it’s for collaboration. Here’s what I worked on: 🔍 1. Identifiers – Naming with Purpose Identifiers are the names we assign to variables, methods, classes, interfaces, packages, and constants. Good naming is not just syntax—it’s communication. 📏 2. The 5 Golden Rules for Identifiers To ensure correctness and avoid compilation errors, I reinforced these rules: Use only letters, digits, underscores (_), and dollar signs ($) Do not start with digits Java is case-sensitive (Salary ≠ salary) Reserved keywords cannot be used as identifiers No spaces allowed in names 🏗️ 3. Professional Naming Conventions This is where code quality truly improves. I practiced industry-standard naming styles: PascalCase → Classes & Interfaces (EmployeeDetails, PaymentGateway) camelCase → Variables & Methods (calculateSalary(), userAge) lowercase → Packages (com.project.backend) UPPER_CASE → Constants (MIN_BALANCE, GST_RATE) 💡 Key Takeaway: Clean and consistent naming transforms code from functional to professional and maintainable. Well-written identifiers reduce confusion, improve collaboration, and make debugging easier. 📈 Moving forward, my focus is not just on writing code that works—but code that is clear, scalable, and team-friendly. #Day19 #100DaysOfCode #Java #CleanCode #JavaDeveloper #NamingConventions #SoftwareEngineering #CodingJourney #LearningInPublic #JavaFullStack#10000coders
To view or add a comment, sign in
-
🚀 Java Series — Day 10: Abstraction (Advanced Java Concept) Good developers write code… Great developers hide complexity 👀 Today, I explored Abstraction in Java — a core concept that helps in building clean, scalable, and production-ready applications. 🔍 What I Learned: ✔️ Abstraction = Hide implementation, show only essentials ✔️ Difference between Abstract Class & Interface ✔️ Focus on “What to do” instead of “How to do” ✔️ Improves flexibility, security & maintainability 💻 Code Insight: Java Copy code abstract class Vehicle { abstract void start(); } class Car extends Vehicle { void start() { System.out.println("Car starts with key"); } } ⚡ Why Abstraction is Important? 👉 Reduces complexity 👉 Improves maintainability 👉 Enhances security 👉 Makes code reusable 🌍 Real-World Examples: 🚗 Driving a car without knowing engine logic 📱 Mobile applications 💳 ATM machines 💡 Key Takeaway: Abstraction helps you build clean, maintainable, and scalable applications by hiding unnecessary details 🚀 📌 Next: Encapsulation & Data Hiding 🔥 #Java #OOPS #Abstraction #JavaDeveloper #BackendDevelopment #CodingJourney #100DaysOfCode #LearnInPublic
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development