The God class in your codebase was probably built by engineers doing the right thing. It started small. Focused. Every method belonged there. Then more related logic got added. Then more. Then more. Nobody was cutting corners. Nobody was being careless. Every addition made sense at the time. User registration lives here. User profile. User preferences. User activity. User billing. User notifications. All user-related. All in one place. 4,000 lines later, the class is doing everything. Changing one method breaks three others. Adding a new feature requires understanding the entire file. Every code review becomes a negotiation about what is safe to touch. The problem was never the intent. It was the missing boundary. Related is not the same as same responsibility. User registration and user billing are both user-related. But they change for completely different reasons. One changes when the signup flow changes. The other changes when the pricing model changes. When two things change for different reasons, they don’t belong in the same class. No matter how related they feel. This is the Single Responsibility Principle. Not one method per class. Not one feature per class. One reason to change per class. A class that grows to 4,000 lines is not a code problem. It is what happens when boundaries are never defined. #Java #SystemDesign #SoftwareEngineering
The Single Responsibility Principle in Code Design
More Relevant Posts
-
While working on code standardization in our Spring Boot services, I revisited something very fundamental — how we inject dependencies. Earlier, many classes were using field injection (@Autowired). As part of cleanup and consistency, I refactored them to constructor injection using @RequiredArgsConstructor. At first, it looked like a small structural change… but it actually brought some meaningful improvements: 1. Immutability by design Dependencies are now final, which means they can’t be reassigned after object creation. This makes the code safer and more predictable. 2. No partially initialized objects With constructor injection, a class cannot be created without its required dependencies. This avoids hidden null risks that can occur with field injection. 3. Improved testability We can now instantiate classes directly with mocks, without needing to spin up the Spring context. This makes unit testing faster and cleaner. 4. Clear and explicit dependencies The constructor clearly shows what the class depends on, improving readability and maintainability. 5. Early detection of design issues Constructor injection helps catch circular dependencies at startup rather than at runtime. What started as a “standardization task” ended up reinforcing how small design choices can significantly impact code quality, testability, and maintainability. Curious to know , do you still see field injection being used in your projects, or has your team fully moved to constructor injection? #BackendDevelopement #Java #SpringBoot #LowLevelDesign
To view or add a comment, sign in
-
Are you still using @Autowired on private fields? It might be time to refactor. 🛑 While Field Injection is short and easy to write, it hides dependencies and makes your code harder to maintain. As your application grows, Constructor Injection becomes the superior choice. Why the shift? ✅ Immutability: You can define your dependencies as final, ensuring they aren't changed after initialization. ✅ Testability: No need for Reflection or Mockito's @InjectMocks magic just to run a simple Unit Test. You can just pass mocks through the constructor. ✅ Object Integrity: It prevents the "NullPointerException" trap. Your object is never in an inconsistent state; it either has all its dependencies or it doesn't compile. Tip: If your constructor has more than 5 dependencies, it's a "Code Smell." It’s telling you that your class is doing too much and needs to be split (SRP violation). Do you use @Autowired for speed, or do you stick to Constructor Injection for safety? Let's debate! 👇 #Java #SpringBoot #CleanCode #SoftwareArchitecture #Testing #BackendDevelopment #CodingTips
To view or add a comment, sign in
-
-
As developers, we all say *“async = separate thread”*… but when I went deeper during development, a few real questions hit me 👇 Can I actually **see which thread is running my async task?** Yes — using `Thread.currentThread().getName()` you can log and observe it. But then the bigger question… 👉 **How many threads are actually created?** 👉 Is it always a new thread per task? 👉 Or are threads reused? I came across a post saying **“by default 8 threads are used”** — but is that really true in all cases? From what I understand so far: * It depends on the **thread pool configuration** * Frameworks like Spring Boot often use executors (not raw thread creation) * Threads are usually **reused**, not created every time But I want to hear from real-world experience 👇 💬 How does async actually behave in production systems? 💬 What decides the number of threads? 💬 Any pitfalls you’ve seen while working with async? Let’s learn from each other 🚀
To view or add a comment, sign in
-
Architecture vs. Speed: When is 8 classes for one task actually worth it? 🚀 As a Senior Developer, I often see a common struggle: when to keep it simple and when to build a robust architecture. In my latest video for Let’s Code Java, I took a simple console app and transformed it into a professional, service-oriented system. The result? I added 8 new classes (builders, services, exception hierarchy), but technically... I didn’t add a single new feature. Was it worth it? It depends. If you're building a prototype, this level of engineering will only slow you down. But if you’re working on a long-term enterprise project, skipping this foundation will cost you twice as much time later when you have to refactor "dirty" code. In this episode, I dive deep into: ✅ Building a Custom Exception Hierarchy that doesn't mess up your logic. ✅ Implementing a Service Layer to isolate business rules from I/O. ✅ Using the Builder Pattern to ensure object validity from the start. ✅ Preparing the ground for Spring Boot & REST API. If you want to see how to design Java applications that are ready for the real world (and why "perfect" code isn't always the goal), check out the video in the first comment. Question for my fellow devs: Where do you draw the line between "clean architecture" and "over-engineering"? Let’s discuss in the comments! 👇 #Java #SoftwareArchitecture #CleanCode #BackendDevelopment #JavaDeveloper #ProgrammingTips #SpringBoot #LetsCodeJava
To view or add a comment, sign in
-
-
🚀 Day 11 of my Spring Framework Journey: Mastering Bean Scopes & Design Patterns! 🚀 Today was a deep dive into the core architectural principles that make Spring so powerful. Understanding how the Spring container manages objects is a game-changer for writing efficient, scalable code. Here are the key takeaways from today’s session: 🔹 Spring Bean Scopes: Singleton vs. Prototype In Spring, the Singleton scope is the default. This means the IoC container creates exactly one instance of that bean, which is shared across the entire container. However, if your application requires a brand-new instance every time a bean is requested, the Prototype scope is the way to go. 🔹 Spring Singleton vs. Java Singleton It is crucial to distinguish between the two! A standard Java Singleton ensures only one instance of a class exists per JVM/ClassLoader. In contrast, a Spring Singleton is "per container"—meaning Spring ensures one instance per specific Bean ID within that container. 🔹 Strategy Design Pattern in Spring I also explored how Spring makes implementing the Strategy Design Pattern incredibly seamless. By using interfaces and multiple implementations (like different engine types for a vehicle), we can decouple our business logic. Spring’s Dependency Injection, combined with the @Qualifier annotation, allows us to swap these "strategies" at runtime without changing the core code. Learning these architectural patterns is helping me transition from just "writing code" to "designing systems." What’s your favorite Spring feature? Let’s connect and grow together! 👇 #SpringFramework #JavaDevelopment #SoftwareEngineering #LearningJourney #BackendDevelopment #CodingCommunity #Day11 #BeanScopes #DesignPatterns #JavaProgramming #SpringBoot
To view or add a comment, sign in
-
Yesterday: “It’s working perfectly 😌” Today: Application failed to start. Same code. Same logic. Different story. Welcome to Spring Boot reality 👇 → One missing bean = full system collapse → One wrong config = hours gone → One hidden null = chaos unleashed → One DB hiccup = everything breaks And suddenly… you’re not coding anymore, you’re investigating. Logs become clues. Stack traces become stories. Debugging isn’t pain — it’s where real backend thinking begins. Because great developers don’t fear crashes… they understand them. ⚡ #SpringBoot #Java #BackendDevelopment #Debugging #BuildInPublic
To view or add a comment, sign in
-
-
Hot take: most performance issues I've seen weren't bugs. They were violations of the Single Responsibility Principle wearing a disguise. Stay with me... When one class does 5 things, it holds 5 things in memory, initializes 5 dependencies, and forces 5 code paths through every request (even when you only needed 1). A few real patterns I've watched play out: - A "UserService" that also handled notifications, audit logging, and report generation. Every login loaded an email client it didn't need. - A controller doing validation, transformation, AND orchestration. Impossible to cache any layer independently. - One giant "helper" class everyone imported; dragging 40 unrelated dependencies into every test and every startup. The fixes weren't fancy. Split the class. Extract an interface. Apply Dependency Inversion so high-level code doesn't drag low-level baggage around. Classic SRP and DIP. Result? Faster startup. Lower memory footprint. Smaller deployable units. Tests that run in seconds instead of minutes. SOLID gets dismissed as 'academic.' But every principle has a performance story hiding underneath. Clean code isn't just for humans. Your runtime reads it too ;) #Java #SpringBoot #SOLID #SoftwareEngineering #BackendDevelopment #designPatterns #systemDesign
To view or add a comment, sign in
-
🚀 How do you prevent cascading failures when an external API goes down? Enter the Circuit Breaker Pattern! 🛡️ In microservices, depending on external services can be risky. If a downstream API times out or fails, it can exhaust your system's resources and take your entire application down with it. To solve this, I recently built a Spring Boot application demonstrating the Circuit Breaker pattern using Resilience4j. I’ve attached a diagram breaking down the architecture, states, and configurations! 🧠👇 Here is a look at how the application is configured to handle failures gracefully: ✅ The States: 1. CLOSED (Normal): Requests flow to the external WeatherService. The system monitors the last 5 calls (Sliding Window). 2. OPEN (Tripped): If the failure rate hits 50%, or if calls take longer than 2 seconds, the circuit trips! Requests are instantly routed to a Fallback Method, returning a default message instead of crashing. 3. HALF-OPEN (Recovery): After 10 seconds, the circuit allows exactly 3 test calls through to check if the downstream API has recovered. If successful, it closes again! By implementing a simple @CircuitBreaker annotation and configuring my application.properties, the system automatically fails fast and ensures a smooth user experience—even when things break behind the scenes. 💡 💻 Check out the full source code on my GitHub: 🔗 https://lnkd.in/g--Xf87k Have you used Resilience4j or similar fault-tolerance libraries in your projects? Let me know your thoughts in the comments! 👇 #SpringBoot #Java #Microservices #Resilience4j #SoftwareArchitecture #CircuitBreaker #BackendDevelopment #FaultTolerance #JavaDeveloper #Coding
To view or add a comment, sign in
-
-
Solved: Product of Array Except Self 💡 Key Takeaway: Instead of recalculating product for every index, we can use prefix and suffix products to build the result efficiently. 👉 Approach I followed: - First pass → store left (prefix) product - Second pass → multiply with right (suffix) product - No division used 📊 Time Complexity: O(n) 📦 Space Complexity: O(1) 🔍 What made it interesting: Understanding how left and right contributions combine at each index to avoid redundant calculations. Consistency + clarity is slowly building confidence 💪 #DSA #Java #LeetCode #CodingJourney #BackendDeveloper #SoftwareEngineering
To view or add a comment, sign in
-
🚀 Most developers hear “ApplicationContext”… but don’t truly understand it. If you’re using Spring Boot, this is the MOST important concept. Let’s simplify it 👇 👉 What is ApplicationContext? It’s the heart of Spring Boot. A container that: ✔ Creates objects (beans) ✔ Manages their lifecycle ✔ Injects dependencies automatically --- 💡 Example: @Service public class OrderService {} @RestController public class OrderController { private final OrderService orderService; public OrderController(OrderService orderService) { this.orderService = orderService; } } 👉 You never created OrderService manually… right? That’s ApplicationContext doing the magic ✨ --- ⚙️ What actually happens internally? 1️⃣ Spring scans your project 2️⃣ Finds @Service, @Component, etc. 3️⃣ Creates objects (beans) 4️⃣ Stores them in ApplicationContext 5️⃣ Injects them wherever needed --- 🔥 Real-world impact: Without ApplicationContext: ❌ You manually create objects ❌ You manage dependencies yourself ❌ Code becomes tightly coupled With Spring: ✅ Loose coupling ✅ Cleaner code ✅ Easy testing --- 📌 Key Takeaway: ApplicationContext = Brain of Spring Boot Everything revolves around it. Follow for more such deep dives 🚀 #SpringBoot #Java #BackendDevelopment #SoftwareEngineer
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