Prefer Static Factory Methods Over Constructors in Java

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

  • graphical user interface, website

To view or add a comment, sign in

Explore content categories