A small but powerful learning from Effective Java – Item 1 Prefer Static Factory Methods Over Constructors At first glance, constructors look fine. But static factory methods give better control and cleaner APIs. Why prefer them? • ✅ Meaningful method names • ✅ Control over object creation • ✅ Can return cached or subtype instances Examples: // Instead of new Boolean("true"); // Prefer Boolean.valueOf("true"); // Instead of new ArrayList<>(); // Prefer List.of(1, 2, 3); You don’t worry how objects are created — you focus on using them correctly. Constructors create objects. Static factory methods design APIs. Source- "Effective Java – Joshua Bloch" #Java #EffectiveJava #BackendEngineering #SoftwareEngineering #CleanCode #SystemDesign #ProductEngineering
Prefer Static Factory Methods Over Constructors in Java
More Relevant Posts
-
Whats the story of lambda expressions? 1. Functional interfaces are interfaces which have only one abstract method, can have static and default methods. 2. Sometimes we dont want to implement an interface by creating a new class. 3. Java gives us anonymous inner classes for it which implement the interface inline. 4. In places where a functional interface is expected we can pass anonymous function (as implementation of abstract method), its type checked against the functional interface and java uses it to create an instance of functional interface. 5. A very cleaner way to write an anonymous function in java is lambda expression. #java #backend
To view or add a comment, sign in
-
Java☕ — Interface vs Abstract Class finally clicked 💡 For a long time, I used them randomly. If code compiled, I thought it was correct. Then I learned the real difference 👇 📝Interface = what a class CAN do 📝Abstract class = what a class IS #Java_Code interface Flyable { void fly(); } abstract class Bird { abstract void eat(); } A plane can fly — but it’s not a bird. That single thought cleared everything for me. Use interface when: ✅Multiple inheritance needed ✅Behavior matters ✅You’re defining a contract Use abstract class when: ✅You share base state ✅You provide common logic ✅Relationship is strong Understanding this saved me from messy designs. #Java #Interface #AbstractClass #OOP #LearningJava
To view or add a comment, sign in
-
🔹 Java String Immutability — Explained Simply Understanding why String is immutable in Java helps you write safer, more efficient, and more reliable code. 📌 What this visual covers: 🔒 Security — prevents unintended data changes ⚡ Performance — enables String Constant Pool reuse 🧵 Thread-safety — safe to share across threads 🧠 Memory behavior — how new objects are created Strong fundamentals lead to better software design and cleaner codebases. 💬 What Java concept do you think every developer should master? #Java #CoreJava #Programming #SoftwareEngineering #JavaDevelopers #TechEducation #JavaProgramming #LearnJava #JavaString
To view or add a comment, sign in
-
-
I used to overuse Optional in Java. Then I learned when not to use it. Optional is great for: • Return types • Avoiding null checks • Making intent clear But using it everywhere can actually make code worse. ❌ Don’t do this: class User { Optional<String> email; } Why? • Makes serialization messy • Complicates getters/setters • Adds noise where it’s not needed ✅ Better approach: Optional<String> findEmailByUserId(Long userId); Rule of thumb I follow now: 👉 Use Optional at the boundaries, not inside your models. Java gives us powerful tools, but knowing where to use them matters more than just knowing how. Clean code is less about showing knowledge and more about reducing confusion. What’s one Java feature you stopped overusing after some experience? #Java #CleanCode #BackendDevelopment #SoftwareEngineering #LearningInPublic #OptionalInJava #Optimization
To view or add a comment, sign in
-
🔖 Marker Interface in Java — Explained Simply Not all interfaces define behavior. Some exist only to signal capability — these are called Marker Interfaces. ⸻ ✅ What is a Marker Interface? A Marker Interface is an interface with no methods. It marks a class so the JVM or framework changes behavior at runtime. Example: Serializable, Cloneable ⸻ 🆚 Marker vs Normal Interface Normal Interface • Defines what a class should do • Has methods • Compile-time contract 👉 Example: Runnable Marker Interface • Defines what a class is allowed to do • No methods • Runtime check 👉 Example: Serializable ⸻ 🤔 Why Marker Interfaces? ✔ Enable / restrict features ✔ Control JVM behavior ✔ Avoid forcing unnecessary methods ⸻ 📌 Common Examples • Serializable → Allows object serialization • Cloneable → Allows object cloning • RandomAccess → Optimizes list access ⸻ 💡 Key Insight Marker Interfaces use metadata instead of methods to control behavior. ⸻ 🚀 Final Thought In Java, sometimes doing nothing enables everything. ⸻ #Java #CoreJava #MarkerInterface #JavaInterview #BackendDeveloper #SpringBoot
To view or add a comment, sign in
-
Decoding the JVM: The Class Loading Process Ever wondered what happens behind the scenes when you run a Java program? It all starts with the Class Loader Subsystem in the JVM. This diagram perfectly illustrates the three main phases a Java class goes through before execution: Loading: Reading the .class file from the hard disk. Linking: The core process involving Verification, Preparation, and Resolution. This ensures the bytecode is valid and prepares the necessary memory structures. Initialization: Executing the static initializers and static blocks. Understanding the JVM architecture is key to writing efficient Java code. \#Java \#JVM \#ClassLoading \#Programming \#Tech \#SoftwareDevelopment
To view or add a comment, sign in
-
-
The magic behind .dot.chaining` in Java? It’s just one keyword. 💡 Ever wondered how libraries like Stream API or Rest Assured allow you to chain methods endlessly? It isn't complex magic. It relies on one simple Java keyword: this. In a standard Setter method, the return type is usually void. The connection closes after the value is set. But in the Builder Pattern, we change the game: 1️⃣ Change the return type from void to the ClassName. 2️⃣ End the method with return this;. By returning this, you are passing the current object reference back to the caller immediately. This allows the next method to pick up exactly where the last one left off. Here is the difference: ❌ Standard Way (Verbose): obj.setName("Alex"); obj.setRole("QA"); obj.setExp(3); ✅ Method Chaining (Clean): obj.setName("Alex") .setRole("QA") .setExp(3); It makes your test data creation and configuration logic readable and beautiful. #Java #CodingTips #CleanCode #BuilderPattern #AutomationTesting #SDET
To view or add a comment, sign in
-
-
Java is no longer the "verbose" language we used to joke about. With Java 25, the entry barrier has been smashed. Instance Main Methods: No more static. Just void main(). Flexible Constructors: You can now run logic before calling super(). Markdown in Javadoc: Finally, documentation that looks good without HTML hacks. Question for the comments: Are you team "Modern Java" or do you still prefer the classic boilerplate? 👇 #Java25 #SoftwareEngineering #CodingLife #BackendDevelopment #codexjava_ If you’re still writing Java like it’s 2011 (Java 7), you’re missing out on a 50% productivity boost.
To view or add a comment, sign in
-
-
🔹 Abstraction Using Abstract Class in Java 🔹 An abstract class is used to achieve partial abstraction by hiding implementation details while allowing some concrete behavior. ✅ Allowed in Abstract Class ✔ Abstract methods (without body) ✔ Concrete methods (with implementation) ✔ Instance variables ✔ Static variables and methods ✔ Final methods ✔ Constructors ✔ Access modifiers (public, protected, default, private) ❌ Not Allowed in Abstract Class ✖ Creating objects directly ✖ Abstract variables ✖ Abstract constructors ✖ Abstract static methods ✖ Instantiating abstract class using new 📌 Key Point: An abstract class can have both abstraction and implementation, making it useful when classes share common behavior. #Java #CoreJava #AbstractClass #OOPs #Abstraction #Learning 🚀
To view or add a comment, sign in
-
-
Sharing a quick Java concept today final, finally, and finalize look almost the same, but they mean completely different things in Java — and this confuses a lot of learners. ▪️ final Used to restrict changes. A final variable can’t be changed, a final method can’t be overridden, and a final class can’t be inherited. ▪️ finally Used with try-catch. It always executes, whether an exception occurs or not. ▪️ finalize A method called by the Garbage Collector before an object is removed from memory. Easy way to remember: final → restriction finally → cleanup finalize → object cleanup Once I understood this clearly, Java exception handling and memory concepts made much more sense. #Java #CoreJava #JavaDeveloper #CodingJourney #StudentDeveloper
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