<?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 Adam Shaffer on Medium]]></title>
        <description><![CDATA[Stories by Adam Shaffer on Medium]]></description>
        <link>https://medium.com/@greatdeveloper66?source=rss-f466aa6c814d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ykoTlUblTC94k8mAvKyAgw.jpeg</url>
            <title>Stories by Adam Shaffer on Medium</title>
            <link>https://medium.com/@greatdeveloper66?source=rss-f466aa6c814d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 20:38:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@greatdeveloper66/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[The Object-Oriented Debate: Why a 1960s Idea Still Divides Developers]]></title>
            <link>https://greatdeveloper66.medium.com/the-object-oriented-debate-why-a-1960s-idea-still-divides-developers-336786ceae7f?source=rss-f466aa6c814d------2</link>
            <guid isPermaLink="false">https://medium.com/p/336786ceae7f</guid>
            <category><![CDATA[arguments]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Adam Shaffer]]></dc:creator>
            <pubDate>Thu, 20 Aug 2026 14:31:01 GMT</pubDate>
            <atom:updated>2026-08-20T14:31:01.398Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ItBHMzKTZ-oo8v7yxBqYFA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@javaistan?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Afif Ramdhasuma</a> on <a href="https://unsplash.com/photos/man-and-woman-pointing-fingers-mv38TB_Ljj8?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Object-oriented programming has been controversial since Simula introduced the concept decades ago. That’s a strange thing to say about a paradigm that still underpins massive amounts of enterprise software, but it’s true. Ask ten developers whether OOP is a fundamental tool or an outdated crutch, and you’ll get ten different answers, most of them delivered with surprising conviction.</p><p>I don’t think the debate is going away anytime soon. And honestly, I don’t think it should. The tension between OOP’s proponents and its critics has pushed the whole industry toward better design thinking, even when the two sides can’t agree on what “better” means.</p><h3>What Object-Oriented Programming Actually Is</h3><p>Before getting into the arguments, it’s worth grounding the conversation in a plain definition. Object-oriented programming is a paradigm that splits code into data and action. The data lives in an object’s fields or attributes. The action lives in its methods, which are designed to operate on that data. Each object is self-contained, interacting with the rest of the program by interfacing with other objects rather than reaching directly into their internals.</p><p>That self-containment is the whole ballgame. Nearly every argument for or against OOP traces back to how well (or how poorly) that boundary holds up in practice.</p><h3>The Case For Object-Oriented Programming</h3><ol><li><strong>Modularity.</strong> Because objects are self-contained, developers can work on them independently. That leads to cleaner organization and easier long-term maintenance, especially on teams where multiple people are touching the same codebase.</li><li><strong>Code reuse.</strong> This benefit is usually credited to inheritance and polymorphism. Instead of rewriting logic from scratch, developers can extend existing structures. That hierarchical reuse cuts down on duplicated work and can meaningfully speed up both production and deployment.</li><li><strong>Real-world modeling.</strong> Supporters of OOP point to its intuitive connection to how people already think. We naturally organize the real world into hierarchies of related things. When code mirrors that structure, it becomes easier to understand, which speeds up everything downstream: maintenance, onboarding, and future upgrades.</li><li><strong>Scalability and flexibility.</strong> Hierarchical inheritance makes it more straightforward to add or modify data and methods as a codebase grows in size and complexity. The structure that felt like overhead on day one starts paying dividends once the system matures.</li><li><strong>Containment of bugs.</strong> Encapsulation lets developers focus on and modify a single object without disturbing the rest of the system. When something breaks, the damage tends to stay isolated to that object rather than rippling outward.</li></ol><h3>The Case Against Object-Oriented Programming</h3><p>The critics aren’t wrong just because the paradigm is popular. Their objections are specific, and most working developers have felt at least one of them firsthand.</p><ol><li><strong>Overcomplexity.</strong> This is the most common knock against OOP. The paradigm can demand a level of logical scaffolding that’s simply unnecessary for straightforward problems. Not every task needs a class hierarchy.</li><li><strong>Slowed performance.</strong> Objects often require storing more information and accessing data indirectly, which can drag down performance compared to leaner approaches.</li><li><strong>Inheritance issues.</strong> Inheritance trees create their own problems. When a hierarchy grows too complex, it becomes difficult to untangle. And when a base class changes, that fragility tends to cascade down into every subclass depending on it.</li><li><strong>Overhead and boilerplate.</strong> Complex inheritance structures can pile up layers of abstraction and boilerplate code, which weakens performance, readability, and debugging all at once.</li><li><strong>Problem suitability.</strong> OOP isn’t the right tool for every job. Critics argue it’s actually a poor fit for a large share of problems, where a more straightforward procedural approach would get the job done with less ceremony.</li></ol><h3>Hierarchy: Real-World Modeling or False Organization?</h3><p>One of the classic arguments for OOP is that inheritance and polymorphism simulate how the human mind naturally categorizes the world, organizing everything into hierarchies of meaning. It’s a compelling idea. But it’s also worth asking whether that hierarchy reflects genuine structure in the problem, or whether it’s a organizational scheme the programmer imposed after the fact because it felt tidy.</p><h3>Encapsulation: Modularity or Just Shared State in Disguise?</h3><p>Encapsulation and single responsibility are supposed to solve one of software engineering’s oldest problems: shared mutable state. “Shared mutable state is the root of all evil” has been said many times. Yet plenty of engineers who’ve worked in large, mature OOP codebases will tell you that sharing data between objects becomes a practical necessity as systems grow, which quietly violates the very principle OOP was supposed to protect.</p><p>Getters and setters are the clearest example of this tension in practice. Most programmers will argue that getters and setters don’t violate encapsulation, for two main reasons. First, internal variables are never accessed directly; every read or write passes through a controlled method. Second, there’s no genuinely shared state, since each object still owns and manages its own data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*yZ5O22cQkCsf5zCyHqc0YA.jpeg" /></figure><p>Other programmers push back on that defense. Their argument: a getter and setter that simply expose a private field with no added logic or validation are just violating encapsulation with an extra step. If any external object can freely read and overwrite an internal value, the fact that it’s routed through a method rather than accessed directly is a technicality, not a genuine boundary.</p><h3>Where This Leaves Testing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7A1Gl2puGyvdVsqsp12cHA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@sen7?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Sen</a> on <a href="https://unsplash.com/photos/a-close-up-of-many-different-colored-legos-rgP93cPsVEc?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>OOP’s emphasis on modularity has a natural downstream effect: it makes unit testing easier to adopt, because each object is a discrete, testable unit. That’s a real strength. Catching bugs early, when the team has a clear understanding of requirements, saves an immense amount of time and cost compared to catching them in production. Code also becomes safer to change, since breaking changes get flagged quickly rather than surfacing weeks later.</p><p>But unit testing carries its own tradeoffs, and they mirror the OOP debate almost exactly. Writing and maintaining unit tests takes real time, both when building new code and when updating existing code. Unit tests validate low-level behavior, which means a codebase can pass every unit test it has while still failing to meet higher-level system requirements. That’s a false sense of security, and it’s a critical distinction for any team leaning heavily on test coverage as a proxy for quality.</p><h3>Popular Doesn’t Mean Perfect, But It Isn’t Nothing Either</h3><p>Here’s the fact that’s easy to lose in the back-and-forth: object-oriented programming is still one of the most widely used paradigms in software today. It powers an immense share of enterprise systems, dominates a long list of mainstream languages, and shows no real sign of losing ground. That kind of staying power doesn’t happen by accident. When millions of developers keep reaching for the same tool across decades, it’s usually doing something right.</p><p>But popularity isn’t proof of correctness. Plenty of widely adopted ideas in this industry have turned out to be flawed, overused, or simply not as universal as they once seemed. OOP is not immune to that possibility just because it’s everywhere.</p><p>That’s exactly why the debate still has value. Widespread adoption earns OOP the benefit of the doubt, not a free pass. The critics who keep pushing on its weak points, and the proponents who keep defending its strengths, are both doing the industry a service.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=336786ceae7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Full-Stack Meal Planning App: The User Authorization Service (Part 2)]]></title>
            <link>https://greatdeveloper66.medium.com/building-a-full-stack-meal-planning-app-the-user-authorization-service-part-2-89c624f57ea8?source=rss-f466aa6c814d------2</link>
            <guid isPermaLink="false">https://medium.com/p/89c624f57ea8</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Adam Shaffer]]></dc:creator>
            <pubDate>Fri, 01 May 2026 06:01:01 GMT</pubDate>
            <atom:updated>2026-05-01T06:01:01.661Z</atom:updated>
            <content:encoded><![CDATA[<h3>Picking Up Where We Left Off</h3><p>In Part 1 of this series I walked through the overall architecture of this meal planning application — five backend microservices deployed to Vercel, a React/TypeScript frontend, and a JWT-based identity thread connecting them all. If you haven’t read that article yet, I’d recommend starting there for context. It will make what follows a lot clearer.</p><p>In this article we go one level deeper. Before a user can store a dietary profile, generate a meal plan, or retrieve a list of nearby grocery stores, the system needs to answer one fundamental question — who are you, and can I trust you? That is the job of the User Authorization Service. It is the first service a user touches and the one every other service depends on.</p><h3>What This Service Does</h3><p>The User Authorization Service is a Node.js microservice deployed to Vercel and connected to a MongoDB database. Its responsibilities are straightforward:</p><ol><li><strong>Register</strong> a new user and store their data securely</li><li><strong>Login</strong> an existing user and issue a JWT token</li><li><strong>Logout</strong> a user and invalidate their session</li><li><strong>Protect</strong> sensitive routes — get profile, update profile, and delete user — behind JWT middleware</li></ol><p>That last point is where the real architectural weight lives. The token this service generates at login doesn’t just authenticate the user here — it travels across the entire system, giving every downstream service a secure, verifiable way to identify who is making a request.</p><h3>The User Model</h3><p>The data model is deliberately lean. Each user document in MongoDB contains five fields:</p><ul><li><strong>First name</strong></li><li><strong>Last name</strong></li><li><strong>Email</strong></li><li><strong>Phone number</strong></li><li><strong>Password</strong></li></ul><p>Keeping the model focused is an intentional decision. This service owns identity data — nothing more. Nutritional profiles, meal plans, and grocery preferences all live in their own services, linked back to this record through a shared userId. Clean separation of concerns starts here.</p><h3>Password Security with bcrypt</h3><p>Storing passwords in plain text is one of the most fundamental security failures a developer can make. This service uses <strong>bcrypt</strong> to handle password encryption before any user record is written to the database.</p><p>When a user registers, bcrypt hashes the password through a computationally expensive algorithm — one that is intentionally slow to make brute-force attacks impractical. When a user logs in, bcrypt compares the submitted password against the stored hash without ever decrypting it.</p><pre>// Hashing a password on registration<br>const salt = await bcrypt.genSalt(10);<br>const hashedPassword = await bcrypt.hash(password, salt);<br><br>// Comparing on login<br>const isMatch = await bcrypt.compare(submittedPassword, storedHash);</pre><p>Two lines of logic. Immense security consequence. This is one of those areas where understanding <em>why</em> the tool works the way it does matters as much as knowing how to use it.</p><h3>The JWT Token Strategy</h3><p>When a user successfully logs in, the service generates a JSON Web Token. The token payload carries two things — the <strong>userId</strong> and an <strong>expiration time</strong>. That’s it. Deliberately minimal.</p><pre>const createJwtToken = (userId, expireTime) =&gt; {<br>  return jwt.sign({ id: userId }, process.env.JWT_SECRET, {<br>    expiresIn: expireTime,<br>  });<br>};</pre><p>The beauty of this approach is what it enables downstream. Every other service in the system — the diet profile service, the meal plan storage service, the grocery locator — can decode this token and extract the userId without ever calling the auth service directly. The token is self-contained proof of identity. That single design decision is what allows five independent services to behave like one coherent application.</p><h3>Protecting Routes with Middleware</h3><p>Not every route in this service is open to the public. Three routes require a valid token before they will respond: <strong>get profile</strong>, <strong>update profile</strong>, and <strong>delete user</strong>.</p><p>The middleware sits between the incoming request and the route handler. It intercepts the request, validates the Authorization header, decodes the token, and either passes the request through or returns an error. Here is the actual implementation:</p><pre>export const protect = async (req, res, next) =&gt; {<br>  try {<br>    // Check header exists<br>    const authHeader = req.headers.authorization;<br>    if (!authHeader)<br>      return res.status(401).json({ message: &quot;No token provided&quot; });<br><br>    // Extract token<br>    const token = authHeader.split(&quot; &quot;)[1];<br>    if (!token)<br>      return res.status(401).json({ message: &quot;Missing token&quot; });<br><br>    // Verify token<br>    const decoded = jwt.verify(token, process.env.JWT_SECRET);<br><br>    // Attach user to request<br>    req.user = await User.findById(decoded.id).select(&quot;-password&quot;);<br>    if (!req.user)<br>      return res.status(404).json({ message: &quot;User not found&quot; });<br><br>    next();<br>  } catch (err) {<br>    res.status(401).json({ message: &quot;Invalid or expired token&quot; });<br>  }<br>};</pre><p>A few things worth noting here. The middleware checks for the header’s existence and the token’s presence as two separate steps — a small but important distinction that produces cleaner, more descriptive error messages. It also explicitly verifies that the decoded userId resolves to a real user in the database before passing the request forward. And critically, the .select(&quot;-password&quot;) call ensures the hashed password is never attached to the request object, even in memory. Each of these decisions reflects the same principle — defense in depth.</p><p>This pattern, middleware as a gatekeeper, is one of the most fundamental concepts in backend development. Once you internalize it, you start seeing it everywhere.</p><h3>CORS and Why It Matters</h3><p>The service also uses <strong>CORS</strong> — Cross-Origin Resource Sharing. When a frontend application running on one domain tries to call an API on a different domain, browsers block that request by default as a security measure. CORS configuration tells the server which origins it should trust and accept requests from.</p><p>For a microservices architecture like this one, where the frontend and backend services live on separate deployments, getting CORS right is not optional — it is critical. A misconfigured CORS policy is one of those bugs that will stop you cold and is not always obvious to diagnose the first time you encounter it.</p><h3>The Hardest Part Isn’t the Code</h3><p>I want to be honest about something. The technical implementation of this service is not where I spent most of my time. The bigger challenge was understanding how all of the pieces fit together — what each layer expected as input, what it returned as output, and how a token generated here eventually made its way into a MongoDB query in a completely separate service.</p><p>Debugging that flow is humbling. When something breaks across service boundaries, you have to hold the entire system in your head while isolating the fault in one specific layer. That kind of problem-solving requires patience more than it requires cleverness.</p><p>There is also a harder, more practical lesson I took from building this: scope never stops growing. There is always something that needs to be added. Knowing when to draw the line — when the service is <em>good enough</em> to move forward — requires an honest assessment of your own abilities and time constraints. That self-awareness is itself an engineering discipline. It doesn’t show up in the documentation, but it shapes every decision you make.</p><h3>What’s Next</h3><p>With identity and authentication handled, the system has a secure foundation to build on. In the next article I’ll go deeper into another layer of the stack — how user data flows between services, how the shared userId becomes the connective thread across independent databases, and how the system maintains coherence without tight coupling between services.</p><p>If you have questions about the implementation or have built something similar, I’d love to hear from you in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89c624f57ea8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Full-Stack Meal Planning App: The Architecture (Part 1)]]></title>
            <link>https://greatdeveloper66.medium.com/building-a-full-stack-meal-planning-app-the-architecture-part-1-8b6b2e3e3f46?source=rss-f466aa6c814d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b6b2e3e3f46</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[typescript-with-react]]></category>
            <category><![CDATA[user-experience]]></category>
            <category><![CDATA[api-development]]></category>
            <dc:creator><![CDATA[Adam Shaffer]]></dc:creator>
            <pubDate>Fri, 24 Apr 2026 04:21:01 GMT</pubDate>
            <atom:updated>2026-05-07T20:27:51.504Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why I Built This</h3><p>Planning meals aligned to your specific diet goals, body composition, and personal situation can be genuinely difficult. As someone who cares about health and fitness, I wanted to create something that made it easy to plan your weekly meals ahead of time — so you can autopilot your food planning and focus on more important things.</p><p>My idea was simple in concept: an application that takes your personal information and returns a tailored weekly meal plan through an interactive, user-friendly interface. I didn’t want to create a simple flat macro or ingredient list. I wanted an end-to-end tool.</p><p>This is the first in a multi-part series documenting how I built it — from the architecture decisions to the individual services, the integration challenges, and the lessons learned along the way. Let’s start at the top: the overall system design.</p><h3>The Big Picture</h3><p>The application is composed of seven distinct components — one frontend, one Backend for Frontend service, and five backend microservices. Each component has a single, well-defined responsibility. The frontend communicates exclusively with the BFF, which in turn routes requests to the appropriate backend services and aggregates their responses. JWT tokens are passed along with those requests, allowing each individual service to handle its own authentication validation independently.</p><p>The five backend microservices and the BFF are deployed to Vercel. The frontend, built with React and TypeScript, will be deployed to Render. This separation keeps the architecture clean, each service independently scalable, and the frontend blissfully unaware of the complexity happening behind the scenes.</p><p><em>(See architecture diagram below)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*VtClcGy5a7ScccC1CcGwBw.jpeg" /></figure><h3>The Seven Components</h3><h4>1. The React / TypeScript Frontend</h4><p>The frontend is the user’s entire window into the system. It handles two categories of input: user identity data (name, email, password, phone number) and nutritional profile data (age, sex, weight, height, activity level, dietary preferences, and budget level).</p><p>Two key output views bring the system’s value to life. The meal plan view displays the current AI-generated plan, including a generated image for each meal. The grocery view displays a browsable list of stores within a 50-mile radius, each with ratings, hours, and contact information. The entire frontend is written in TypeScript with React, applying UX and UI best practices for a fully responsive experience across devices.</p><h4>2. The User Authorization Service</h4><p>This service handles the foundational security layer — registration, login, and JWT generation. User identity data is persisted in a dedicated MongoDB database.</p><p>When a user logs in, the service generates a JWT token. That token becomes the thread of identity that runs through the entire system. Every downstream service that needs to know <em>who</em> is making a request decodes that token to retrieve the userId, which serves as the shared key across all databases.</p><h4>3. The Diet Profile Service</h4><p>The diet profile service stores and retrieves each user’s nutritional profile — the core input that makes personalization possible. Like the auth service, it uses a MongoDB database for persistence.</p><p>The critical design decision here is the shared userId. When a user logs in, the same userId present in the auth database is used as the foreign key in the diet profile database. This allows both services to remain fully decoupled while still referencing the same user. No shared database, no tight coupling — just a clean token-based identity thread.</p><h4>4. The AI Meal Planner Service</h4><p>This is the most technically interesting of the five services, and it has two distinct functions.</p><p>The first takes the user’s full dietary profile as input — age, sex, weight, height, activity level, dietary preferences, and budget level — and sends it to the OpenAI API to generate a structured meal plan. The returned object is a detailed array of daily meals, each broken down by breakfast, lunch, and dinner, with individual food items carrying calorie, protein, carbohydrate, fat, and quantity data.</p><p>The second function takes that returned meal plan and makes a follow-up call to OpenAI to generate an AI image of each meal.</p><h4>5. The Meal Plan Storage Service</h4><p>One of the more important architectural decisions I made was adding a dedicated meal plan storage service. Once the AI meal planner generates a plan and its associated images, those results are persisted to a MongoDB database keyed to the user’s userId.</p><p>The practical benefit is significant: the application no longer needs to call the OpenAI API every time a user wants to view their current meal plan. The generated plan and images are retrieved directly from the database, making the experience faster and more cost-efficient. The AI service is only invoked when the user explicitly requests a new plan.</p><h4>6. The Grocery Locator Service</h4><p>The final backend service closes the loop between planning and execution. It accepts a GPS location (latitude and longitude) and a search radius, then calls the Google Places API to return all grocery stores within that area.</p><p>Each result includes the store name, coordinates, address, operating status, hours, ratings, price level, photos, and website. On the frontend, this data is surfaced as a browsable list within a 50-mile radius — giving the user everything they need to act on their meal plan immediately.</p><h4>7. The Backend for Frontend Service</h4><p>As the application grew, coordinating requests across five independent backend services from the frontend became increasingly complex. The frontend would need to know which service to call, in what order, and how to handle responses — or errors — from multiple sources simultaneously. That is the kind of complexity that compounds quickly and belongs nowhere near a UI layer.</p><p>The Backend for Frontend service solves this cleanly. It sits between the frontend and all five microservices, acting as the single entry point for every request the frontend makes. Its two core responsibilities are request routing — directing each incoming request to the correct downstream service — and response aggregation — collecting and combining responses before returning them to the frontend as a single, coherent payload.</p><p>Critically, the BFF does not take over JWT validation. Each backend service continues to handle its own authentication independently. The BFF simply forwards the token along with each request, keeping the security model consistent and the individual services fully self-contained. The result is a frontend that speaks to one endpoint, and a backend that remains modular and independently deployable.</p><h3>What’s Next</h3><p>In the articles that follow, I’ll go deep on each individual service — the implementation details, the integration challenges, and the specific design decisions I made along the way. Next up: the User Authorization Service and how JWT-based identity flows through the entire system.</p><p>If you’re building something similar or have thoughts on the architecture, I’d love to hear from you in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b6b2e3e3f46" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Make Your API Impossible to Use]]></title>
            <link>https://greatdeveloper66.medium.com/how-to-make-your-api-impossible-to-use-3047d2afab9a?source=rss-f466aa6c814d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3047d2afab9a</guid>
            <category><![CDATA[budgeting]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[api-integration]]></category>
            <category><![CDATA[api-development]]></category>
            <dc:creator><![CDATA[Adam Shaffer]]></dc:creator>
            <pubDate>Tue, 20 Jan 2026 05:41:59 GMT</pubDate>
            <atom:updated>2026-01-20T05:41:59.376Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*uf3oA_SJAwztiomfl0Yt7Q.gif" /></figure><p>If you’ve ever:</p><ul><li>Read an API’s documentation three times and still didn’t know how to make a request</li><li>Received a 400 Bad Request and nothing else</li><li>Dug through a deeply nested JSON response just to extract one useful value</li><li>Or discovered that the “free tier” wasn’t free <em>after</em> deploying to production</li></ul><p>Congratulations.</p><p>You’ve experienced what many teams proudly call a ‘production-ready’ API.”</p><p>These APIs don’t just happen by accident. They’re the result of careful decisions: outdated documentation, ambiguous error messages, confusing data structures, and pricing models that reward delusional optimism.</p><p>In this article, I’ll walk through the proven techniques for achieving this level of excellence — a practical guide on <strong>how to make your API impossible to use</strong>.</p><p>Let’s start with the foundation of every unusable API: substandard documentation.</p><h3>The Three Rules of API Documentation</h3><p><strong>Rarely Update It</strong><br>First and foremost, your priority is writing code quickly — not making the end user’s life easier. Documentation is a <strong>historical artifact</strong>, not a living document.</p><p>If the API changes, it’s up to the developers to figure it out.</p><p>Like the Code of Hammurabi, your API documentation should exist as a snapshot of your brilliance, preserved for future generations. Any resemblance to the current implementation is purely coincidental.</p><p><strong>Avoid Clarity at All Costs</strong><br> Clarity is the enemy of velocity and throughput.</p><p>When an API fails to work as intended, it’s rarely because the documentation is bad. It’s because the end user is semi-literate. It is not your responsibility to walk them through it.</p><p>Use jargon. Use acronyms. Use internal team slang that only makes sense to the three people who originally wrote the service. If developers don’t understand it, that just means they’re not senior enough.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*hW8f5HeQLpuMkDcDE_xgTw.jpeg" /></figure><p><strong>Error Handling Is a Crutch</strong><br> Don’t do developers’ debugging work for them.</p><p>Returning precise error codes with helpful messages takes time — time that could be spent shipping features no one asked for. A simple 400 Bad Request is more than sufficient.</p><p>Real developers debug using intuition, vibes, and late-night despair. If they wanted guidance, they should have chosen a different career.</p><p>Follow these rules, and you will set an example for all API developers and maintainers for years to come.</p><p>After all, confusion is temporary — but technical debt is forever.</p><h3>Response Data: Chaos Is a Feature</h3><p><strong>Deeply Nested JSON</strong><br>Don’t waste your time — or your immense brainpower — coming up with easy-to-follow JSON structures. It’s far more rewarding to design overcomplicated and obscure access paths.</p><p>For example, why return temperature when you can return<br> data.weather.current.conditions.metrics.values.primary.temp.actual?</p><p>It’s not your job to babysit other development teams.</p><p>Flattening data is spoon-feeding. Developers should work for their payloads.</p><p><strong>Inconsistency Builds Character</strong><br> Some people believe returning consistent data structures is a sign of professionalism and technical competence. These people don’t know what they’re talking about.</p><p>Variety demonstrates technical depth. Sometimes return arrays. Sometimes objects. Occasionally return strings that <em>look</em> like numbers. Growth happens in discomfort.</p><p>Remember: if you don’t make the end user’s job more difficult, they will never learn.</p><p><strong>Ambiguous Field Names</strong><br>Why be boring when you can be mysterious?</p><p>Never clarify whether value, amount, or count refers to the same thing. Avoid documentation that maps fields to meaning. Let developers explore.</p><p>Discovery is fun. Especially when it happens in production. After all, if the data were easy to understand, people might start using it correctly</p><h3>Confusing Pricing Tiers (Monetization Through Fear)</h3><h4>Hide the Limits</h4><p>Never allow developers to understand clearly how much they can use your API.</p><p>Rate limits, quotas, and overage thresholds should be fragmented across multiple locations. For best results, document them in a separate PDF behind a login wall. Bonus points if the PDF hasn’t been updated in years.</p><p>The goal is uncertainty. When developers can’t predict usage, they can’t set budgetary expectations — and that’s their problem, not yours.</p><h4>Make Usage Impossible to Predict</h4><p>Static limits are boring.</p><p>Dynamic, sliding, “fair use” thresholds are ideal. They give you flexibility while giving developers anxiety. Avoid exact numbers whenever possible. Words like <em>reasonable</em>, <em>excessive</em>, and <em>at scale</em> are especially effective.</p><p>Surprise invoices build excitement. They also encourage developers to closely re-examine their life choices.</p><h4>Aggressive Tier Jumps</h4><p>Smooth pricing curves are for cowards.</p><p>Go straight from free to $5,000 per month. Make the jump sudden and dramatic. Ideally, the upgrade page should appear only after the limit has already been exceeded.</p><p>If the developers are serious, they’ll find the budget. If not, they probably weren’t a good fit anyway.</p><h4><strong>Conclusion: Developers Need to Toughen Up</strong></h4><p>If developers wanted clear documentation, readable responses, predictable pricing, and helpful error messages, they should have chosen a different profession.</p><p>After all, software is hard. That’s not your fault — it’s the fault of people who continue to make poor career choices.</p><p>There’s no need to spend time making APIs usable for people you will never meet or care about. Empathy doesn’t scale, and neither does clarity.</p><p>Remember: any inconvenience experienced by developers is simply the cost of innovation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3047d2afab9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Banks Still Love Java — and Probably Always Will]]></title>
            <link>https://greatdeveloper66.medium.com/why-banks-still-love-java-and-probably-always-will-d220e6805b8e?source=rss-f466aa6c814d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d220e6805b8e</guid>
            <category><![CDATA[business-strategy]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Adam Shaffer]]></dc:creator>
            <pubDate>Mon, 29 Dec 2025 02:16:56 GMT</pubDate>
            <atom:updated>2025-12-29T02:16:56.114Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why Banks Still Love Java — and Probably Always Will</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ZCcc9U5RlaHdp01GUv4yQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@aboodi_vm?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">A</a>boodi Vesakaranon <a href="https://unsplash.com/photos/a-tall-building-with-a-clock-on-the-side-of-it-YdjGfQz-s9I?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>The banking industry has never been known for risk-taking — and given what’s at stake, it’s no wonder. When software fails to move money, it isn’t a learning experience; it’s a lawsuit. A bad deployment can cost millions, invite regulators, and erode trust overnight.</p><p>Unlike social media startups, banks can’t simply issue an apology and return to business as usual.</p><p>So why does such a risk-averse, heavily regulated industry continue to rely on a 30-year-old programming language?</p><h3>Failure is Expensive</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H5_XsckMkhAxDne3hOGAXw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@pastorthomasbwilson?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Tom Wilson</a> on <a href="https://unsplash.com/photos/white-and-black-light-fixture-Em2hPK55o8g?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In most industries, clean code is a luxury. <br>In banking, it’s evidence — evidence that systems can be audited, trusted, and justified.</p><p>When software handles sensitive financial data, reliability and predictability aren’t stylistic preferences; they’re non-negotiable requirements. Code must be comprehensible not just to developers, but to auditors, regulators, and security teams.</p><p>Java fits this world perfectly, not because it’s trendy, but because it is predictable.</p><p>Verbosity is one of Java’s most commonly criticized features. For many developers, it slows progress and feels restrictive. In regulated environments, however, that same verbosity becomes an asset. Explicit types, clear structure, and well-defined behavior make large codebases easier to document, audit, and verify.</p><p>Garbage collection reflects a similar tradeoff. Java willingly accepts runtime overhead and heavier frameworks in exchange for controlled memory management and predictable failure modes. Instead of entire systems collapsing due to subtle memory bugs, failures are contained and diagnosable.</p><p>In banking software, the loss of elegance is a price worth paying to preserve financial stability, trust, and regulatory compliance. Java’s design consistently favors reliability over cleverness — exactly what systems handling real financial risk require.</p><h3>Predictability Beats Innovation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZPp_1YKN7OeZKRllFKJ6zw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@mvds?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Mads Schmidt Rasmussen</a> on <a href="https://unsplash.com/photos/ice-capped-mountain-at-daytime-xfngap_DToE?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>The tech industry prides itself on adaptability and inventiveness. In finance, however, risk aversion dominates and predictability takes the win. Once failure becomes expensive, novelty quickly loses its appeal.</p><p>There is no better example of this philosophy than the Java Virtual Machine (JVM). Bytecode compatibility across machines ensures long-term stability. “Write Once, Run Anywhere” isn’t just about portability — it’s about longevity. Java doesn’t merely support older code; it is contractually committed to it.</p><p>Java’s standard libraries also evolve conservatively, which is a surprising strength of the ecosystem. APIs are rarely removed, allowing codebases to function long after updates. Java rejects the “update or break” philosophy common in modern frameworks, carrying its history forward rather than discarding it.</p><p>Just as importantly, Java is observable. The JDK includes profilers, debuggers, heap analyzers, and mature monitoring tools. Problems are diagnosable, audits are survivable, and failures are explainable. A system you can’t observe is a system you can’t trust.</p><p>When software must outlive teams, frameworks, and even companies, stability becomes a strategic requirement.</p><h3>Institutions Optimize for Time, not Trends</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*vekfpxwFGMK6OG3U_-HMpQ.jpeg" /></figure><p>Banks don’t build software for the next release cycle; they make it for the next generation of engineers.</p><p>Teams change, people leave, and institutional knowledge fades. Long-term stability depends less on individual brilliance and more on systems that are easy to understand, operate, and hand off. The right technology preserves and amplifies institutional memory.</p><p>Frameworks like Spring Boot embody this mindset. Opinionated defaults and explicit configuration reduce ambiguity and discourage clever but fragile solutions. Convention over configuration isn’t about limiting developers — it’s about making systems understandable to the next team that inherits them. A Spring application written years ago remains recognizable today, even to engineers who didn’t build it.</p><p>Spring Security extends this philosophy into the most sensitive area: access control. Authentication, authorization, and session management are centralized and standardized rather than reimplemented by each team. This reduces security drift, simplifies audits, and makes failures easier to diagnose.</p><p>None of this is exciting — and that’s the point.</p><p>Banks choose ecosystems that scale organizations, not just codebases. By favoring established patterns, shared conventions, and mature tooling, they reduce dependency on individual developers and extend the lifespan of their systems. Java and its surrounding frameworks succeed not because they chase trends, but because they help institutions endure.</p><p>In the financial industry, unexciting software isn’t a drawback; it is a survival strategy</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d220e6805b8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Single Responsibility Principle in Java]]></title>
            <link>https://greatdeveloper66.medium.com/single-responsibility-principle-in-java-ccb4bd922034?source=rss-f466aa6c814d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccb4bd922034</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Adam Shaffer]]></dc:creator>
            <pubDate>Sat, 20 Dec 2025 00:32:29 GMT</pubDate>
            <atom:updated>2025-12-20T00:32:29.124Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding the S in SOLID design principles</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f4TswfGUnwKoAUY_rsQ2qA.png" /></figure><p>Understanding and implementing the Single Responsibility Principle (SRP) in Java is essential for software developers who aim to write resilient and maintainable code. As one of the SOLID principles, SRP states that a class should have only one reason to change, encouraging clarity and simplicity in design. By following SRP, developers improve code organization, reduce complexity, and make systems easier to maintain and extend. This principle forms a cornerstone of robust software architecture, providing a strong foundation for building adaptable applications and for understanding the other SOLID principles. Applying SRP is an investment in code that is not only functional, but also clean, expressive, and professionally crafted.</p><h4>Explanation</h4><p>At its core, the Single Responsibility Principle (SRP) states that a class should have only one reason to change — that is, it should encapsulate a single responsibility. This principle encourages developers to decompose systems into focused, well-defined units of behavior, resulting in code that is easier to understand, maintain, and extend.</p><p>By enforcing a single responsibility, SRP promotes <strong>high cohesion</strong> within classes and <strong>loose coupling</strong> between them. A highly cohesive class is more predictable and easier to reason about because all of its behavior serves a single purpose. Loose coupling, in turn, ensures that changes to one responsibility have minimal impact on other parts of the system. In practice, each class should represent one distinct piece of functionality and nothing more.</p><h4><strong>Why the Single Responsibility Principle Matters</strong></h4><p>One of the primary dangers SRP seeks to prevent is <strong>change amplification</strong>. Change amplification occurs when a small requirement change forces modifications across multiple, unrelated parts of the codebase. When a class contains multiple responsibilities, altering one responsibility risks breaking or altering behavior associated with the others. As a result, simple changes become costly, error-prone, and difficult to reason about.</p><p>By adhering to SRP, changes are localized. When a class has only one reason to change, modifications are constrained to a single, focused unit, reducing both the likelihood and the blast radius of defects.</p><p>Another way to understand SRP is through the concept of <strong>actors</strong>. An actor represents a distinct stakeholder, user, or system that has a reason to request changes to the software. A class that serves multiple actors inherently has multiple reasons to change, even if the functionality appears related.</p><p>When multiple actors influence a single class, their requirements can conflict, leading to fragile designs and unexpected regressions. SRP encourages separating responsibilities along actor boundaries so that changes requested by one actor do not affect functionality relied upon by another. In summary Single Responsibility gives:</p><ul><li><strong>Maintainability</strong><br> Classes with a single responsibility are easier to understand and modify because changes are isolated to a well-defined purpose. This reduces the risk of change amplification and unintended side effects.</li><li><strong>Reusability</strong><br> Focused classes are more reusable across different contexts because they are not coupled to unrelated behavior or actor-specific requirements.</li><li><strong>Testability</strong><br> Smaller, cohesive classes are easier to test in isolation, allowing each responsibility to be verified independently and reducing the complexity of test setups.</li></ul><h4>Examples</h4><p>Let’s look at how single responsibility works with an example using a real-world process.</p><p>Suppose we have a ‘Customer’ class designed to handle customer information and email them their updated email.</p><pre>public class Customer {<br>    private String name;<br>    private String email;<br><br>    public Customer(String name, String email) {<br>        this.name = name;<br>        this.email = email;<br>    }<br><br>    public void updateEmail(String newEmail) {<br>        this.email = newEmail;<br>        // Also send an email notification to the customer<br>        EmailService.sendEmail(this.email, &quot;Your email has been updated.&quot;);<br>    }<br><br>    // Other methods for managing customer information<br>}<br><br>Customer customer = new Customer(&quot;Alice&quot;, &quot;old@email.com&quot;);<br>customer.updateEmail(&quot;new@email.com&quot;);</pre><h4>Why This Design Violates SRP</h4><p>In the original implementation, the Customer class is responsible for both managing customer data and sending email notifications. While these actions may appear related, they represent <strong>two distinct responsibilities</strong> and are subject to change for different reasons.</p><p>For example, changes to customer data requirements — such as validation rules or additional fields — are driven by business logic. In contrast, changes to email behavior — such as message formatting, delivery mechanisms, or third-party providers — are driven by infrastructure or communication concerns. Combining these responsibilities introduces <strong>multiple reasons for the class to change</strong>, violating the Single Responsibility Principle.</p><p>This design also increases the risk of <strong>change amplification</strong>. A modification to email-sending logic could unintentionally impact customer data handling, making the system harder to maintain and more fragile over time.</p><h4>Applying SRP Through Separation of Responsibilities</h4><p>To adhere to SRP, these responsibilities should be separated. The Customer class should focus exclusively on managing customer state, while a dedicated EmailService should handle all email-related behavior.</p><p>With this separation, changes to customer data logic are isolated from changes to email delivery. Each class now has a single reason to change, leading to higher cohesion and looser coupling. The EmailService becomes a reusable and specialized component, while the Customer class remains a clear representation of the domain model.</p><p>This separation not only aligns with SRP, but also improves testability, maintainability, and long-term flexibility.</p><pre>public class Customer {<br>    private String name;<br>    private String email;<br><br>    public Customer(String name, String email) {<br>        this.name = name;<br>        this.email = email;<br>    }<br><br>    public void updateEmail(String newEmail) {<br>        this.email = newEmail;<br>    }<br><br>    // Other methods for managing customer information<br>}<br><br>public class EmailService {<br>    public static void sendEmail(String recipientEmail, String message) {<br>        // Logic for sending an email notification<br>        System.out.println(&quot;Sending an email to &quot; + recipientEmail + &quot;: &quot; + message);<br>    }<br>}<br><br>Customer customer = new Customer(&quot;Alice&quot;, &quot;old@email.com&quot;);<br>customer.updateEmail(&quot;new@email.com&quot;);<br>emailService.sendEmail(customer.getEmail(), &quot;Your email has been updated.&quot;);<br></pre><p>Let’s look at another similar example. Suppose we have a Customer class that manages customer information (e.g., name, address) and customer orders.</p><pre>public class Customer {<br>    private String name;<br>    private String address;<br>    private List&lt;Order&gt; orders;<br><br>    public Customer(String name, String address) {<br>        this.name = name;<br>        this.address = address;<br>        this.orders = new ArrayList&lt;&gt;();<br>    }<br><br>    public void addOrder(Order order) {<br>        orders.add(order);<br>        // Perform order-related actions<br>    }<br><br>    public void updateAddress(String newAddress) {<br>        this.address = newAddress;<br>        // Also, perform address-related actions<br>    }<br><br>    // Other methods for managing customer data<br>}</pre><p>In this code, the Customer class manages customer data and orders. These are two pieces of logic that should be separated. To adhere to SRP, we’ll separate the responsibilities into two classes for managing customer information and customer orders.</p><pre>public class Customer {<br>    private String name;<br>    private String address;<br><br>    public Customer(String name, String address) {<br>        this.name = name;<br>        this.address = address;<br>    }<br><br>    public void updateAddress(String newAddress) {<br>        this.address = newAddress;<br>    }<br><br>    // Other methods for managing customer data<br>}</pre><pre>public class Order {<br>    private int orderId;<br>    private LocalDate orderDate;<br>    private List&lt;Item&gt; items;<br><br>    public Order(int orderId, LocalDate orderDate) {<br>        this.orderId = orderId;<br>        this.orderDate = orderDate;<br>        this.items = new ArrayList&lt;&gt;();<br>    }<br><br>    public void addItem(Item item) {<br>        items.add(item);<br>        // Perform order-related actions<br>    }<br><br>    // Other methods for managing orders<br>}</pre><p>Now, the Customer class is responsible solely for managing customer information, while the Order class handles customer orders. Each class has a single, well-defined responsibility.</p><p>Let’s look at another example of using interfaces to achieve SRP.</p><pre>public class CombinedMediaPlayer {<br>    private String audioFileName;<br>    private String imageFileName;<br><br>    public CombinedMediaPlayer(String audioFileName, String imageFileName) {<br>        this.audioFileName = audioFileName;<br>        this.imageFileName = imageFileName;<br>    }<br><br>    public void playMedia() {<br>        // Play audio<br>        System.out.println(&quot;Playing audio: &quot; + audioFileName);<br><br>        // Display image<br>        System.out.println(&quot;Displaying image: &quot; + imageFileName);<br>    }<br><br>    // Methods for managing media settings, which further violate SRP<br>    public void adjustVolume(int volume) {<br>        // Adjust volume logic<br>        System.out.println(&quot;Volume adjusted to &quot; + volume);<br>    }<br><br>    public void setDisplayResolution(int width, int height) {<br>        // Set display resolution logic<br>        System.out.println(&quot;Display resolution set to &quot; + width + &quot;x&quot; + height);<br>    }<br><br>    // More methods for media management...<br>}</pre><h4>SRP Violation in the Original Design</h4><p>In the original implementation, the CombinedMediaPlayer class is responsible for playing audio, displaying visual content, and managing media-related settings such as volume and display resolution. These responsibilities are conceptually distinct and are likely to change for different reasons.</p><p>Any modification to audio playback logic, visual rendering behavior, or media configuration would require changes to the same class. This results in multiple reasons to change, violating the Single Responsibility Principle. Such designs increase complexity, make testing more difficult, and amplify the impact of change.</p><h4>Applying SRP Using Interfaces and Composition</h4><p>To adhere to SRP, these responsibilities can be separated into focused abstractions. The AudioPlayer interface defines behavior related solely to audio playback, while the VisualPlayer interface defines behavior related to visual rendering. Each interface is implemented by a class with a single, well-defined responsibility.</p><p>The MediaPlayer class no longer performs audio or visual operations directly. Instead, it coordinates these responsibilities by delegating work to the appropriate collaborators. Its sole responsibility is orchestration, giving it only one reason to change: modifications to playback coordination logic.</p><p>This design promotes high cohesion within classes and loose coupling between them. Changes to audio playback or visual rendering can be made independently, without impacting other parts of the system. The result is a more maintainable, testable, and extensible design that adheres to the Single Responsibility Principle.</p><p>While interfaces help enforce separation of concerns, SRP is ultimately about ensuring that each class has only one reason to change — not simply splitting code into multiple abstractions.</p><pre>public interface AudioPlayer {<br>    void playAudio(String audioFileName);<br>    void adjustVolume(int volumeLevel);<br>}<br><br>public interface VisualPlayer {<br>    void displayImage(String imageFileName);<br>    void setDisplayResolution(int width, int height)<br>}<br><br>public class SimpleAudioPlayer implements AudioPlayer {<br>    @Override<br>    public void playAudio(String audioFileName) {<br>        // Implementation to play audio<br>        System.out.println(&quot;Playing audio: &quot; + audioFileName);<br>    }<br><br>    @Override<br>    public void adjustVolume(int volumeLevel) {<br>        // Adjust volume logic<br>        System.out.println(&quot;Volume adjusted to &quot; + volume);<br>    }<br>}<br><br>public class SimpleVisualPlayer implements VisualPlayer {<br>    @Override<br>    public void displayImage(String imageFileName) {<br>        // Implementation to display an image<br>        System.out.println(&quot;Displaying image: &quot; + imageFileName);<br>    }<br><br>    @Override<br>    public void setDisplayResolution(int width, int height) {<br>        // Set display resolution logic<br>        System.out.println(&quot;Display resolution set to &quot; + width + &quot;x&quot; + height);<br>    }<br>}<br><br>public class MediaPlayer {<br>    private AudioPlayer audioPlayer;<br>    private VisualPlayer visualPlayer;<br><br>    public MediaPlayer(AudioPlayer audioPlayer, VisualPlayer visualPlayer) {<br>        this.audioPlayer = audioPlayer;<br>        this.visualPlayer = visualPlayer;<br>    }<br><br>    public void playMedia(String audioFileName, String imageFileName) {<br>        audioPlayer.playAudio(audioFileName);<br>        visualPlayer.displayImage(imageFileName);<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        AudioPlayer audioPlayer = new SimpleAudioPlayer();<br>        VisualPlayer visualPlayer = new SimpleVisualPlayer();<br><br>        MediaPlayer mediaPlayer = new MediaPlayer(audioPlayer, visualPlayer);<br><br>        // Play media with separated concerns<br>        mediaPlayer.playMedia(&quot;song.mp3&quot;, &quot;image.jpg&quot;);<br>    }<br>}</pre><h4>Key Takeaways</h4><ul><li>A class following SRP should be limited to one responsibility, having only one reason to change.</li><li>The single responsibility of a class should be evident in its name, methods, and properties.</li><li>Modifications to a class should relate solely to its single commitment, minimizing unintended side effects.</li><li>Classes adhering to SRP are easier to maintain, reducing the risk of accidental impact on unrelated parts of the system.</li><li>SRP promotes better code organization and modularization by encouraging the creation of smaller, focused classes.</li><li>Adhering to SRP results in more modular and maintainable software, enhancing code understanding, testing, and extension.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccb4bd922034" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to AWS Global Infrastructure]]></title>
            <link>https://greatdeveloper66.medium.com/introduction-to-aws-global-infrastructure-07e77aeab366?source=rss-f466aa6c814d------2</link>
            <guid isPermaLink="false">https://medium.com/p/07e77aeab366</guid>
            <category><![CDATA[cloud-services]]></category>
            <category><![CDATA[computing]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[internet]]></category>
            <dc:creator><![CDATA[Adam Shaffer]]></dc:creator>
            <pubDate>Sat, 07 Jun 2025 11:06:38 GMT</pubDate>
            <atom:updated>2025-06-07T11:06:38.636Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LTxc92hGeM68ExrTFzrQWQ.png" /></figure><p>AWS cloud computing is one of the fastest-growing technologies in today’s market. Businesses and developers alike leverage AWS to build scalable, efficient, and cost-effective applications without the burden of maintaining physical infrastructure. Compared to traditional in-house data storage solutions, AWS offers significant advantages by eliminating upfront investment costs, streamlining operations, and providing global accessibility.</p><p>Some of the key benefits include:</p><ul><li><strong>Trading Capital Expense for Variable Expense</strong> — Instead of investing heavily in hardware, organizations pay only for the resources they use, optimizing costs.</li><li><strong>Leveraging Economies of Scale</strong> — AWS’s vast infrastructure enables lower-cost computing by distributing expenses across millions of users.</li><li><strong>Predictable Capacity</strong> — AWS scales resources dynamically, preventing over-provisioning or underutilization.</li><li><strong>Increased Speed and Agility</strong> — Cloud environments allow businesses to deploy applications quickly, reducing time to market.</li><li><strong>Operational Cost Outsourcing</strong> — AWS handles maintenance, security, and infrastructure, allowing teams to focus on innovation.</li><li><strong>Fast Global Deployment</strong> — With multiple regions and edge locations worldwide, AWS ensures low-latency access for users across different geographies</li></ul><p>Beyond these high-level advantages, AWS’s global infrastructure plays a crucial role in maintaining reliability, scalability, and performance. By distributing resources across <strong>Regions, Availability Zones, Local Zones, Edge Locations, and Wavelength Zones</strong>, AWS optimizes data delivery and ensures minimal downtime.</p><h3>AWS Regions and Availability Zones</h3><p>At the foundation of AWS architecture is the <strong>AWS Region</strong>, a geographically defined area that contains a cluster of data centers. Each region operates <strong>independently</strong> to ensure fault tolerance and minimize latency, allowing organizations to deploy applications close to their users.</p><p>Within each AWS Region, there are Availability Zones (AZs) — physically separate data centers designed for high availability. Each AZ has its own storage, cooling, and networking infrastructure, ensuring redundancy and resilience. These zones function <strong>autonomously</strong> while maintaining <strong>low-latency connectivity</strong>, enabling seamless access to AWS services and optimizing performance for end users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a0mRcyeS8zURPo0a1ddWZQ.png" /></figure><h3>Local Zones, Edge Locations, and Regional Edge Caches</h3><p>While AWS Regions and Availability Zones provide scalable infrastructure, Local Zones extend the reach of AWS services to areas outside standard regions. These zones are strategically placed in metropolitan areas to minimize <strong>latency</strong> for users located far from AWS’s main data centers, enabling faster application performance.</p><p>Beyond Local Zones, Edge Locations further <strong>enhance content delivery</strong> by caching data closer to end users. As integral components of AWS CloudFront, these locations optimize response times for global users by reducing the distance data needs to travel. They serve as endpoints for AWS’s content delivery network, ensuring <strong>high-speed access</strong> to frequently requested content.</p><p>To further improve cloud accessibility, Regional Edge Caches sit between CloudFront servers and Edge Locations. These caches <strong>store frequently accessed data</strong>, reducing load times and improving overall network efficiency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*_MIGH-wv51CbNu8Lx2IxyQ.jpeg" /></figure><h3>Wavelength Zones and 5G Integration</h3><p>AWS <strong>Wavelength Zones</strong> are designed to integrate seamlessly with <strong>5G networks</strong>, allowing developers to deploy applications at the <strong>edge of </strong>telecom carrier networks. By placing compute and storage resources closer to mobile users, these zones significantly <strong>reduce latency</strong>, making them ideal for applications that require near-instant responsiveness.</p><h3>Use Case: Multiplayer Gaming with AWS Gamelift Infrastructure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EbcCK41dDB0tlCtkTjXapA.png" /></figure><p>To better understand AWS infrastructure, let’s look at <strong>multiplayer gaming</strong> as a use case.</p><p>When a player launches a game, their request goes to AWS GameLift’s matchmaking system. Here, the system evaluates their latency, skill level, and location to find the best game server. Once assigned to an optimal GameLift<strong> fleet</strong> in a <strong>low-latency region</strong>, the player connects using UDP protocol, ensuring <strong>fast, real-time data transmission</strong> with minimal delay.</p><p>For players far from major AWS regions, Local Zones help by extending cloud infrastructure <strong>closer to urban areas</strong>, reducing lag. These zones act as <strong>secondary hubs</strong>, improving responsiveness for users outside core AWS regions.</p><p>To further speed things up, Edge Locations cache static game assets — textures, maps, and updates — through AWS CloudFront, cutting down load times. Regional Edge Caches<strong> </strong>store frequently accessed assets, reducing unnecessary trips to the main servers.</p><p>For mobile gamers on <strong>5G networks, AWS Wavelength Zones</strong> process game data right at the <strong>edge of telecom carrier networks</strong>, delivering near-instant responses — essential for fast-paced games like shooters and racing titles.</p><p>By combining AWS GameLift with Regions, Availability Zones, Local Zones, Edge Locations, Regional Edge Caches, and Wavelength Zones, developers can scale multiplayer gaming globally while ensuring low-latency gameplay across PC, console, and mobile platforms.</p><h3>Conclusion</h3><p>AWS cloud computing offers a powerful, scalable solution for modern applications, eliminating the need for traditional in-house infrastructure while ensuring <strong>high availability and efficiency</strong>. By distributing resources across Regions, Availability Zones, Local Zones, Edge Locations, and Wavelength Zones, AWS provides the foundation for a <strong>low-latency, resilient network</strong> capable of supporting everything from enterprise workloads to real-time gaming. As cloud computing continues evolving, AWS remains a cornerstone for<strong> </strong>high-performance applications, driving innovation across industries.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07e77aeab366" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Worst Of Sorting Algorithms]]></title>
            <link>https://greatdeveloper66.medium.com/worst-of-sorting-algorithms-358860b4ec2d?source=rss-f466aa6c814d------2</link>
            <guid isPermaLink="false">https://medium.com/p/358860b4ec2d</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Adam Shaffer]]></dc:creator>
            <pubDate>Thu, 29 May 2025 03:22:08 GMT</pubDate>
            <atom:updated>2025-05-29T03:22:08.283Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b73aG_j7FZbM5d3oGMB53w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jankolar?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Jan Antonin Kolar</a> on <a href="https://unsplash.com/photos/brown-wooden-drawer-lRoX0shwjUQ?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>Exploring the worst of coding is more useful than you would think. It can illustrate algorithm principles just as well as competent code. Sorting Algorithms are famously many people’s first introduction to computer science algorithms. So, let’s explore the worst of the worst of sorting. Most of these are real algorithms I’ve seen. I will go from fair to bad to atrocious.</p><h4>Bubble Sort</h4><p>Bubble Sort is one of the simplest but rarely used algorithms. Its performance is subpar, but the steps are simple.</p><ol><li>Start at the beginning of the list.</li><li>Compare the first two elements.</li><li>If the first element is greater than the second, swap them.</li><li>Move to the next pair and repeat the process.</li><li>Continue to the end of the list.</li><li>Repeat the process until the whole list is sorted.</li></ol><pre>procedure BubbleSort(arr):<br>    n = length(arr)<br>    repeat<br>        swapped = false<br>        for i from 0 to n-2 do:<br>            if arr[i] &gt; arr[i+1] then:<br>                swap(arr[i], arr[i+1])<br>                swapped = true<br>        n = n - 1  # Reduce the range after each full pass<br>    until swapped == false</pre><p><strong><em>Time Complexity</em></strong></p><p>Not surprisingly, the time efficiency of this algorithm is poor, as elements must be compared multiple times. I would describe bubble sort as the kind of algorithm you resort to in an interview when your brain freezes.</p><ol><li>Best Case: O(n)</li><li>Worst Case: O(n²)</li><li>Average Case: O(n²)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9LH1iiaM34lXnLra9mQp1A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@eklektikum?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Iva Rajović</a> on <a href="https://unsplash.com/photos/stack-white-stones-on-seashore-wstYTyWtGac?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h4>Insertion Sort</h4><p>This algorithm is a slight improvement over bubble sort. It does essentially the same thing but inserts into a space between elements instead of bubbling up.</p><pre>procedure InsertionSort(arr):<br>    n = length(arr)<br>    for i from 1 to n-1 do:<br>        key = arr[i]<br>        j = i - 1<br>        while j &gt;= 0 and arr[j] &gt; key do:<br>            arr[j+1] = arr[j]  # Shift larger elements to the right<br>            j = j - 1<br>        arr[j+1] = key  # Insert the current element into the correct position</pre><p><strong><em>Time Complexity</em></strong></p><p>As seen above, this algorithm is still very brute force. I would describe insertion sort as the kind of algorithm you resort to when your brain freezes but you still have a few functioning brain cells left.</p><ol><li>Best Case: O(n)</li><li>Worst Case: O(n²)</li><li>Average Case: O(n²)</li></ol><h4>Sleep Sort</h4><p>Here is where things start to get interesting. I first came across this algorithm while watching a YouTube Short. It is kind of genius in its own way, though very inefficient — especially for larger lists.</p><p>It is called <em>Sleep Sort</em> because it makes use of timeout functions.</p><p>The basic steps are simple:</p><ol><li>Iterate through the array element by element.</li><li>For each element, set a timeout function using that element’s magnitude.</li><li>Within the timeout function, add the element to a new array.</li><li>Once all timeout functions have executed, the array will be sorted.</li></ol><pre>procedure SleepSort(arr):<br>  n = length(arr)<br>  for i from 1 to n - 1 do:<br>    setTimeout(() =&gt; newArr.push(item), item)<br>  <br>  return newArr<br></pre><p><strong><em>Time Complexity</em></strong></p><p>This algorithm is clever and simple, but potentially very inefficient for large values. The sorting time depends not only on the number of elements, <em>n</em>, but also on the largest value in the array, <em>max(arr)</em>, because each element must wait for its corresponding delay before being pushed into <em>newArr</em>. The event loop efficiently handles this scheduling, but the time complexity still scales with <em>max(arr)</em>.</p><p>If the array contains extremely large values, the waiting time can theoretically grow indefinitely (limited by system constraints on timers). Thus, the worst-case time complexity isn’t strictly upper-bounded in conventional terms. However, in practical cases where <em>max(arr)</em> remains within a reasonable limit, the complexity is <em>O(n + max(arr))</em>.</p><ol><li>Best Case: O(n)</li><li>Average Case: O(n + max(arr))</li><li>Worst Case: O(n + max(arr))</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kwSI6QcBdiQ6iURozKXj2w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@rihok?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Riho Kroll</a> on <a href="https://unsplash.com/photos/closeup-photo-of-dices-m4sGYaHYN5o?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h4>Random Insertion Sort</h4><p>Next, we introduce random functions into the mix. Now, we’re entering disaster territory. This algorithm is essentially <em>insertion sort</em>, except at every pass, the element is inserted into a random position in the array.</p><p>Here are the basic steps:</p><ol><li>Start with an unsorted array.</li><li>Randomly pick an element from the array.</li><li>Insert it into a random position.</li><li>Repeat steps 2–3 for every element.</li><li>Check if the array is sorted; if not, repeat.</li></ol><pre>procedure RandomInsertionSort(arr):<br>    while not isSorted(arr):<br>        for i from 0 to length(arr)-1 do:<br>            j = random(0, length(arr)-1)  # Pick a random index<br>            swap(arr[i], arr[j])  # Randomly swap elements</pre><p><strong><em>Time Complexity</em></strong></p><p>Oh, this is where it gets truly disastrous:</p><ol><li><strong>Best Case:</strong> <em>O(n)</em> (Somehow, it magically sorts on the first attempt — highly unlikely.)</li><li><strong>Average Case:</strong> <em>O(∞)</em> (Since every step relies on random placement, there’s no guarantee it will ever finish within a reasonable timeframe.)</li><li><strong>Worst Case:</strong> <em>O(∞)</em> (If randomness keeps preventing correct placement, it could theoretically never end.)</li></ol><p>Effectively, <em>Random Insertion Sort</em> has no deterministic upper bound — it might complete instantly, or it might leave you staring at the screen for eternity.</p><p>Fun fact: In probability theory, algorithms like this fall into the category of <em>Las Vegas algorithms</em>, meaning they might never halt within a reasonable timeframe.</p><h4>API call to Stack Overflow</h4><p>This next algorithm sidesteps the issue by calling on the wisdom of our best developers. Because sometimes the best sorting strategy is outsourcing the problem entirely.</p><pre>procedure APICallToStackOverflow(arr):<br>    query = &quot;How do I sort an array in the best possible way?&quot;  # Ask Stack Overflow<br>    api = &quot;https://www.stackoverflow.com&quot; # Stack Overflow URL<br>    answer = fetchBestAnswer(query, api)  # Retrieve the top-rated solution<br>    if answer is not None:<br>        execute(answer)  # Blindly trust the wisdom of the internet<br>    else:<br>        print(&quot;Error: No good solutions found. Try rephrasing the question.&quot;)</pre><p><strong><em>Time Complexity</em></strong></p><p><em>Complexity:</em> Undefined. It depends on how quickly someone responds on Stack Overflow</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rz3deES-KhxGeRr-_cqrIw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@bettinaaa123?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Bettina Otott Kovács</a> on <a href="https://unsplash.com/photos/statue-of-liberty-new-york-EfHqouvZU2Y?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h4>Miracle Sort</h4><p>For when faith in the universe is your sorting strategy.</p><pre>procedure MiracleSort(arr):<br>    if isSorted(arr):<br>        return arr  # It&#39;s already sorted, yay!<br>    else:<br>        doNothing()  # Trust that eventually, through sheer cosmic luck, it will be sorted</pre><p><strong><em>Time Complexity</em></strong></p><p><em>Complexity:</em> O(1) if you’re lucky. O(∞) if the universe refuses to cooperate</p><h3>Conclusion</h3><p>Let’s review what we’ve covered. <strong>Bubble Sort</strong> and <strong>Insertion Sort</strong> are traditional, comparison-based methods that systematically move elements into order. <strong>Sleep Sort</strong> leverages timeout functions to provide an unconventional solution.</p><p><strong>Random Insertion Sort</strong> disrupts the normal sorting process by inserting elements into random positions, often leading to chaos rather than order. <strong>APICallToStackOverflow Sort</strong> bypasses computation entirely by outsourcing the problem to the broader developer community. Finally, <strong>Miracle Sort</strong> relies more on faith in our shared reality than on logic.</p><p>All in all, these are excellent illustrations of what <em>not</em> to do when solving problems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=358860b4ec2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Tower of Hanoi Problem]]></title>
            <link>https://greatdeveloper66.medium.com/the-tower-of-hanoi-problem-95784aa50c40?source=rss-f466aa6c814d------2</link>
            <guid isPermaLink="false">https://medium.com/p/95784aa50c40</guid>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Adam Shaffer]]></dc:creator>
            <pubDate>Thu, 27 Feb 2025 00:02:23 GMT</pubDate>
            <atom:updated>2025-02-27T00:04:29.276Z</atom:updated>
            <content:encoded><![CDATA[<p>One of my favorite puzzles of all time is the Tower of Hanoi problem. This puzzle has a fascinating history. French mathematician Édouard Lucas invented it in 1883. Shortly after, in 1889, it was published in a booklet and later turned into toys sold in stores worldwide.</p><h3>Understanding the Problem</h3><p>The Tower of Hanoi consists of three rods and an unspecified number of discs, each of a different size. Initially, all discs are stacked on one rod, arranged from largest to smallest. The objective is to move all discs to another rod while never placing a larger disc on top of a smaller one. The challenge lies in figuring out the most efficient way to achieve this goal.</p><p>When I first encountered this problem, it took much trial and error to find the solution. However, once I discovered it, the logic became clear. More importantly, the Tower of Hanoi serves as an excellent introduction to recursion, a fundamental concept in computer science.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*izxTSgdgRBVqkS2irLwX9g.jpeg" /></figure><h3>Building the Solution Step By Step</h3><p>To develop an algorithm, let’s start with the simplest base case and gradually increase the number of discs.</p><h4>One Disc</h4><p>With only one disc, the solution is straightforward: move the disc from the source rod to the target rod. In pseudocode, this translates to:</p><pre>MOVE(1, Source, Target)</pre><p>This single move serves as the foundation for solving the problem with multiple discs.</p><h4>Two Discs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*LgAhDV2TH2RQw-ymEHKgyQ.gif" /><figcaption>Tower of Hanoi with two discs</figcaption></figure><p>With two discs, the process becomes slightly more complex. The steps are as follows:</p><ol><li>Move the smallest disc to the auxiliary rod.</li><li>Move the larger disc to the target rod.</li><li>Move the smallest disc from the auxiliary rod to the target rod</li></ol><p>In pseudocode:</p><pre>MOVE(1, Source, Auxiliary)<br>MOVE(2, Source, Target)<br>MOVE(1, Auxiliary, Target)</pre><h4>Three Discs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*qMZVgYekRZ6Wgalu6w1jkA.gif" /><figcaption>Tower of Hanoi with three discs</figcaption></figure><p>To solve the problem with three discs, we use a recursive approach:</p><ol><li>Move the top two discs to the auxiliary rod.</li><li>Move the largest disc to the target rod.</li><li>Move the two smaller discs from the auxiliary rod to the target rod.</li></ol><p>This pattern extends to any number of discs. The recursive nature of the problem becomes evident, allowing us to generalize the solution.</p><h3>Recursive Algorithm</h3><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*8u9QnRO8qEQa1v4lsPzfZw.gif" /><figcaption>Tower of Hanoi Recursive Solution</figcaption></figure><p>The Tower of Hanoi problem follows a well-defined recursive structure:</p><ol><li>Move the n — 1 top discs from the source rod to the auxiliary rod.</li><li>Move the largest disc from the source rod to the target rod.</li><li>Move the n — 1 discs from the auxiliary rod to the target rod.</li></ol><p>In pseudocode:</p><pre>PROCEDURE HANOITOWER(n, source, auxiliary, target):<br>    IF n == 1 THEN<br>        PRINT &quot;Move disc from &quot; source &quot; to &quot; target<br>        RETURN<br>    ENDIF<br>    <br>    HANOITOWER(n - 1, source, target, auxiliary)  // Step 1<br>    PRINT &quot;Move disc from &quot; source &quot; to &quot; target  // Step 2<br>    HANOITOWER(n - 1, auxiliary, source, target)  // Step 3<br>ENDPROCEDURE</pre><h3>Java Implementation</h3><pre>public class TowerOfHanoi {<br>    public static void solveHanoi(int n, char source, char auxiliary, char target) {<br>        if (n == 1) {<br>            System.out.println(&quot;Move disc from &quot; + source + &quot; to &quot; + target);<br>            return;<br>        }<br>        <br>        solveHanoi(n - 1, source, target, auxiliary); // Step 1<br>        System.out.println(&quot;Move disc from &quot; + source + &quot; to &quot; + target); // Step 2<br>        solveHanoi(n - 1, auxiliary, source, target); // Step 3<br>    }<br><br>    public static void main(String[] args) {<br>        int numDiscs = 4; // Change this for different numbers of discs<br>        solveHanoi(numDiscs, &#39;A&#39;, &#39;B&#39;, &#39;C&#39;);<br>    }<br>}</pre><h4>Explanation of Java Code</h4><p>The solveHanoi method follows a recursive approach:</p><ul><li>If n == 1, it moves the disc directly from the source to the target.</li><li>Otherwise, it: 1) Moves n — 1 discs from the source to the auxiliary rod. 2) Moves the largest disc from the source to the target rod 3) Moves the n — 1 discs from the auxiliary rod to the target rod.</li></ul><p>The main method initiates the process with four discs, but the number can be adjusted as needed.</p><h3>Conclusion</h3><p>The Tower of Hanoi puzzle beautifully illustrates recursion. By breaking the problem into smaller subproblems, we create an elegant and efficient solution. Understanding this recursive pattern not only helps in solving this classic puzzle but also provides insight into solving many other recursive problems in computer science.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95784aa50c40" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Code Smells — the biggest ones to avoid]]></title>
            <link>https://greatdeveloper66.medium.com/code-smells-the-biggest-ones-to-avoid-e1ce20236e20?source=rss-f466aa6c814d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1ce20236e20</guid>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Adam Shaffer]]></dc:creator>
            <pubDate>Fri, 16 Feb 2024 20:03:22 GMT</pubDate>
            <atom:updated>2024-02-16T20:03:22.512Z</atom:updated>
            <content:encoded><![CDATA[<h3>Code Smells — the biggest ones to avoid</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*09KRvMPY4malXkW2F21nwQ.jpeg" /></figure><p>Poorly written code always reveals itself. Experienced software developers often comment on how they can sense poorly written code without being able to pinpoint why at first. I can partly attest to this in m y experiences refactoring poor code bases. I sometimes found it amazing how such obviously poorly written code could be developed at well-established companies. Below, I will list and detail some of the most critical code smells a developer will likely run into. It is also essential to remember this list when writing your code.</p><h4><strong>Duplicate Code</strong></h4><p>This one doesn’t require a detailed explanation. Modern programming languages have a wide variety of tools to address this problem. Most coders know to avoid this problem; however, duplication can arise in subtler ways in which the same problem is being solved twice but differently.</p><pre>public class BankingSystem {<br>    public void transferFunds(Account fromAccount, Account toAccount, double amount) {<br>        // Code block A<br>        fromAccount.withdraw(amount);<br>        toAccount.deposit(amount);<br>        System.out.println(&quot;Transaction type: TRANSFER, Amount: &quot; + amount);<br>    }<br>    <br>    public void payBill(Account fromAccount, Bill bill) {<br>        // Code block A<br>        fromAccount.withdraw(bill.getAmount());<br>        bill.setPaid(true);<br>        System.out.println(&quot;Transaction type: PAYMENT, Amount: &quot; + bill.getAmount());<br>    }<br>}</pre><p>The code above duplicates code in a couple of ways. First, the System print line statements are very similar. Also, the withdrawal statements perform identical purposes in both methods. We can simplify the code with private methods to minimize code repeat and make the flow more understandable.</p><pre>public class BankingSystem {<br>    public void transferFunds(Account fromAccount, Account toAccount, double amount) {<br>        performTransaction(fromAccount, toAccount, amount, TransactionType.TRANSFER);<br>    }<br>    <br>    public void payBill(Account fromAccount, Bill bill) {<br>        performTransaction(fromAccount, bill.getAmount(), TransactionType.PAYMENT);<br>    }<br>    <br>    private void performTransaction(Account fromAccount, Account toAccount, double amount, TransactionType type) {<br>        fromAccount.withdraw(amount);<br>        toAccount.deposit(amount);<br>        System.out.println(&quot;Transaction type: &quot; + type + &quot;, Amount: &quot; + amount);<br>    }<br>    <br>    private void performTransaction(Account fromAccount, double amount, TransactionType type) {<br>        fromAccount.withdraw(amount);<br>        System.out.println(&quot;Transaction type: &quot; + type + &quot;, Amount: &quot; + amount);<br>    }<br>}</pre><p>In this case, the repetitious logic in “transferFunds” and “payBill” are extracted out to private methods that encapsulate the tasks. The two private methods focus on the basic transaction of moving money between accounts. This makes the code more understandable and streamlined.</p><h4><strong>Bad Naming</strong></h4><p>Variable and function names should explicitly convey the purpose of the variable or function. It should tell us what it does and how it fits into the codebase overall. Good naming should make adding comments unnecessary.</p><pre>public class Account {<br>  private double bal;<br>  <br>  public double a() {<br>    return bal;<br>  }<br>}</pre><pre>public class Account {<br>    private double balance;<br><br>    public double getBalance() {<br>        return balance;<br>    }<br>}</pre><p>The two blocks of code above provide a straightforward example of bad variable and method naming and how it is fixed with good naming. In the first block of code, the names tell us nothing about the purpose of the variables and functions. In the second, the purpose of the data is self-explanatory through their given names.</p><h4><strong>No handling of errors or edge cases</strong></h4><p>It is natural to write code for only the case when it works as expected. This is understandable to some extent. Writing the code for the “happy path” is much more direct and less tedious than predicting all the issues it may encounter in its running environment. Robust code, however, must handle a variety of errors or edge cases that arise in its actual use and application.</p><pre>public class Account {<br>  private double balance;<br><br>  public withdraw(double amount) {<br>    balance -= amount;<br>  }<br>}</pre><p>We must remember Murphy’s rule: if something can go wrong, it will. The first code snippet above only addresses the happy path when the customer withdraws an amount from their account that doesn’t break anything. The upgraded code snippet below fixes some weaknesses by handling two possible exceptions: withdrawing an amount that exceeds the balance or withdrawing a negative amount.</p><pre>public class Account {<br>  private double balance;<br><br>  public void withdraw(double amount) {<br>    if (amount &lt;= 0) {<br>      throw new IllegalArgumentException(&quot;Amount to witdraw must be positive&quot;);<br>    }<br>    if (balance &lt; amount) {<br>      throw new IllegalStateException(&quot;Insufficient funds&quot;);<br>    }<br>    balance -= amount;<br>  }<br>}</pre><h4>Dead Code</h4><p>You would be surprised how often you will run into this in a company’s codebase. Dead code is never run, no matter how the program progresses. Conditions of ‘if-else’ statements that never evaluate to true are among the most common examples of dead code. The code above evaluates four conditions for payment type being: transfer, payment, deposit, or other.</p><pre> public class BankingSystem {<br>    public void processTransaction(Account fromAccount, Account toAccount, double amount, TransactionType type) {<br>        if (type == TransactionType.TRANSFER) {<br>                fromAccount.withdraw(amount);<br>                toAccount.deposit(amount);<br>            }<br>        } else if (type == TransactionType.PAYMENT) {<br>            fromAccount.withdraw(amount);<br>            <br>        } else if (type == TransactionType.DEPOSIT) {<br>            toAccount.deposit(amount);<br>        } else {<br>            toAccount.withdraw(amount);<br>            fromAccount.deposit(amount);<br>        }<br>       <br>    }<br>}</pre><p>However, in this code base, there is no need for the last conditional, as deposit, withdrawal, and transfer are the only types we consider. The code below simplifies the method by excluding the never-reached code.</p><pre>public class BankingSystem {<br>    public void processTransaction(Account fromAccount, Account toAccount, double amount, TransactionType type) {<br>        f (type == TransactionType.TRANSFER) {<br>                fromAccount.withdraw(amount);<br>                toAccount.deposit(amount);<br>            }<br>        } else if (type == TransactionType.PAYMENT) {<br>            fromAccount.withdraw(amount);<br>            <br>        } else {<br>            toAccount.deposit(amount);<br>        }<br>       <br>    }<br>}</pre><h4><strong>Overly Complex</strong></h4><p>Failing to minimize complexity is among the most common mistakes developers make. In fact, many other types of code smells result from not following this principle. Intelligent code achieves its goals in the most straightforward way possible. Overly complex code is challenging to read, less maintainable, and less extendable.</p><pre>public class BankingSystem {<br>    public void processTransaction(Account fromAccount, Account toAccount, double amount, TransactionType type) {<br>        if (type == TransactionType.TRANSFER) {<br>            if (fromAccount.getBalance() &gt;= amount) {<br>                fromAccount.withdraw(amount);<br>                toAccount.deposit(amount);<br>            } else {<br>                throw new IllegalStateException(&quot;Insufficient funds for transfer&quot;);<br>            }<br>        } else if (type == TransactionType.PAYMENT) {<br>            fromAccount.withdraw(amount);<br>            // Process payment<br>        } else if (type == TransactionType.DEPOSIT) {<br>            if (toAccount != null) {<br>                toAccount.deposit(amount);<br>            } else {<br>                throw new IllegalArgumentException(&quot;Invalid destination account&quot;);<br>            }<br>        } else {<br>            System.out.println(&quot;No such transaction type&quot;);<br>        }<br>    }<br>}</pre><p>The above code is a complete mess. The if-else statement branches are overly nested and confusing, and the methods needs to be shorter.</p><pre>public class BankingSystem {<br>    public void processTransaction(Account fromAccount, Account toAccount, double amount, TransactionType type) {<br>        switch (type) {<br>            case TRANSFER:<br>                performTransfer(fromAccount, toAccount, amount);<br>                break;<br>            case PAYMENT:<br>                fromAccount.withdraw(amount);<br>                // Process payment<br>                break;<br>            case DEPOSIT:<br>                performDeposit(toAccount, amount);<br>                break;<br>            default:<br>                System.out.println(&quot;No such transaction type&quot;);<br>        }<br>        // More conditions and logic...<br>    }<br>    <br>    private void performTransfer(Account fromAccount, Account toAccount, double amount) {<br>        if (fromAccount.getBalance() &gt;= amount) {<br>            fromAccount.withdraw(amount);<br>            toAccount.deposit(amount);<br>        } else {<br>            throw new IllegalStateException(&quot;Insufficient funds for transfer&quot;);<br>        }<br>    }<br>    <br>    private void performDeposit(Account toAccount, double amount) {<br>        if (toAccount != null) {<br>            toAccount.deposit(amount);<br>        } else {<br>            throw new IllegalArgumentException(&quot;Invalid destination account&quot;);<br>        }<br>    }<br>}</pre><p>The more appropriate “switch-case” statement handles different transaction types in the improved version above. Additionally, each case calls a private method that encapsulates the logic for that specific transaction type, reducing the complexity and improving the readability of the code.</p><h4>Conclusion</h4><p>The examples of code smells given above may seem trivial; however, in a large, complicated, and interconnected code base, these bad practices can add up to something utterly unmanageable that costs a company entirely too much time and money. The main takeaways to remember are:</p><ul><li>Well-written code should rarely require any commenting. Good naming conventions and other best practices should make commenting completely unnecessary.</li><li>It is easy to overlook error conditions, but handling errors and exceptions must be built into the software development process.</li><li>Duplicate or dead code wastes space and clutters the codebase with dead weight.</li><li>Keep it Simple. Code should achieve its objective in the most effortless way possible.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1ce20236e20" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>