JavaScript Design Patterns and Clean Code Practices: Build Maintainable Applications
Quick Answer: Design patterns are proven ways to solve common software design problems. Clean code makes those solutions easier to read, test and change. In this guide, we use Strategy, Observer and Factory patterns in a grocery ordering application. We also improve naming, functions, error handling and code structure.
1. Why Do JavaScript Applications Need Better Design?
Imagine you manage an online grocery shop with 1,000 daily orders. Customers use different discounts and payment options. They also expect updates when their orders change.
Would you place every rule inside one large function? Think about how difficult that function becomes as the shop grows.
The problem: One function handles everything
This example calculates discounts for three customer types. It works, but every new discount adds another condition.
Example 1: A tightly coupled discount function
function calculateDiscount(order, customerType) {
if (customerType === "regular") {
return order.total * 0.05;
}
if (customerType === "premium") {
return order.total * 0.10;
}
if (customerType === "festival") {
return order.total * 0.15;
}
return 0;
}
const order = { total: 2000 };
console.log(calculateDiscount(order, "regular"));
console.log(calculateDiscount(order, "premium"));
console.log(calculateDiscount(order, "festival"));
Expected output
100 200 300
This works, but it gets hard to manage.
- Every new discount changes the same function.
- Testing one discount may require testing every condition.
- Discount rules become mixed with order calculations.
- Large functions become harder to review.
Now think about hundreds of discount rules and frequent business changes. We need a better structure.
The solution: Separate rules and responsibilities
We can give each discount its own strategy. The order service then uses the selected strategy.
Example 2: The same discount calculation using Strategy
const discountStrategies = {
regular: (total) => total * 0.05,
premium: (total) => total * 0.10,
festival: (total) => total * 0.15
};
function calculateDiscount(total, customerType) {
const strategy = discountStrategies[customerType];
if (!strategy) {
return 0;
}
return strategy(total);
}
const orderTotal = 2000;
console.log(calculateDiscount(orderTotal, "regular"));
console.log(calculateDiscount(orderTotal, "premium"));
console.log(calculateDiscount(orderTotal, "festival"));
Expected output
100 200 300
The result stays the same. However, each discount rule now has a clear place.
| Without Strategy | With Strategy |
|---|---|
| Many conditions in one function | Separate discount rules |
| Changes affect shared logic | New rules can be added separately |
| Testing conditions becomes harder | Each strategy can be tested alone |
| Responsibilities are mixed | Responsibilities are clearer |
Terms to remember:
- Design pattern = a reusable approach to a common design problem.
- Strategy = a separate way to perform one task.
- Coupling = how strongly one part depends on another.
- Maintainability = how easily we can understand and change code.
2. What Are JavaScript Design Patterns?
A design pattern gives developers a familiar structure for solving a problem. It is not a ready-made library or a fixed rule.
JavaScript supports many patterns through objects, functions, closures and classes. We should choose a pattern only when it makes the design clearer.
Common design pattern categories
| Category | Purpose | Examples |
|---|---|---|
| Creational | Controls how objects are created. | Factory, Singleton, Builder |
| Structural | Organises relationships between objects. | Adapter, Decorator, Facade |
| Behavioral | Organises communication and behaviour. | Strategy, Observer, Command |
3. Strategy Pattern: Change Business Rules Without Large Conditions
Strategy = a separate method for performing the same kind of task.
Our grocery shop offers different discounts. Each discount follows the same input and output contract. The checkout service does not need to know the internal discount formula.
The order passes through one selected discount strategy before checkout returns the final amount.
Example 3: Complete Strategy implementation
const discountStrategies = {
regular: (total) => total * 0.05,
premium: (total) => total * 0.10,
festival: (total) => total * 0.15
};
function getDiscount(total, customerType) {
const strategy = discountStrategies[customerType];
if (!strategy) {
throw new Error("Unsupported customer type");
}
return strategy(total);
}
function checkout(order, customerType) {
const discount = getDiscount(order.total, customerType);
const finalTotal = order.total - discount;
return {
originalTotal: order.total,
discount,
finalTotal
};
}
const result = checkout(
{ total: 2000 },
"premium"
);
console.log(result);
Expected output
{
originalTotal: 2000,
discount: 200,
finalTotal: 1800
}
Why does this design help?
- Each strategy owns one discount calculation.
- The checkout function only coordinates the calculation.
- New strategies can be added without rewriting checkout.
- Tests can check each discount rule separately.
Important: This object-based approach is suitable for simple strategies. Larger strategies may need separate modules or classes.
4. Observer Pattern: Notify Everyone When an Order Changes
Observer = a pattern where subscribers receive updates from a publisher.
When a grocery order is packed, several parts need that update. The customer needs a notification. The delivery team needs the order details. The inventory service may need to update stock.
Without Observer, the order service may call every system directly. That creates unnecessary dependencies.
The publisher sends one order event, and each registered subscriber handles its own update.
Example 4: Observer using JavaScript classes
class OrderPublisher {
constructor() {
this.listeners = [];
}
subscribe(listener) {
this.listeners.push(listener);
}
unsubscribe(listener) {
this.listeners =
this.listeners.filter(
(item) => item !== listener
);
}
notify(order) {
for (const listener of this.listeners) {
listener(order);
}
}
}
const orderPublisher = new OrderPublisher();
const customerNotification = (order) => {
console.log("Customer update: " + order.status);
};
const deliveryUpdate = (order) => {
console.log("Delivery team: " + order.id);
};
orderPublisher.subscribe(customerNotification);
orderPublisher.subscribe(deliveryUpdate);
orderPublisher.notify({
id: "GROC-101",
status: "Packed"
});
Expected output
Customer update: Packed Delivery team: GROC-101
Important Observer considerations
- Subscribers should have a clear unsubscribe method.
- One failing listener should not silently block important updates.
- Listeners should not retain unnecessary references.
- Define whether notifications run synchronously or asynchronously.
Production note: This example stores listeners in memory. It does not deliver events across servers. Distributed systems need a message broker or another shared event mechanism.
5. Factory Pattern: Create Payment Methods in One Place
Factory = a function or object that creates the required object.
Our grocery shop accepts UPI and card payments. The checkout process should not create payment objects in many places.
Example 5: A simple payment factory
class UpiPayment {
pay(amount) {
return `UPI payment received: ₹${amount}`;
}
}
class CardPayment {
pay(amount) {
return `Card payment received: ₹${amount}`;
}
}
function createPaymentMethod(method) {
switch (method) {
case "upi":
return new UpiPayment();
case "card":
return new CardPayment();
default:
throw new Error("Unsupported payment method");
}
}
const payment = createPaymentMethod("upi");
console.log(payment.pay(1500));
Expected output
UPI payment received: ₹1500
The factory centralises object creation. Checkout can work with the returned payment object.
Security reminder: Real payment integrations need provider verification, secure credentials and server-side payment confirmation. This example only demonstrates object creation.
6. Clean Code Practices Every JavaScript Developer Should Follow
Clean code = code that developers can understand and safely change.
Design patterns help with structure. Clean code helps with everyday implementation. These practices work together.
6.1 Use meaningful names
Names should explain the purpose of a variable or function.
Before: Unclear variable names
const x = 2500;
const y = 0.10;
const z = x * y;
After: Names that explain the business meaning
const orderTotal = 2500;
const premiumDiscountRate = 0.10;
const discountAmount = orderTotal * premiumDiscountRate;
Good names reduce the need for extra comments.
6.2 Keep functions small and focused
One function should have one clear responsibility. Avoid mixing validation, calculations and notifications.
Before: One function handles unrelated tasks
function processOrder(order) {
if (!order.customerId) {
throw new Error("Customer is required");
}
const total = order.items.reduce(
(sum, item) => sum + item.price * item.quantity,
0
);
console.log("Order total: " + total);
console.log("Sending customer notification");
}
After: Separate validation, calculation and notification
function validateOrder(order) {
if (!order.customerId) {
throw new Error("Customer is required");
}
}
function calculateOrderTotal(items) {
return items.reduce(
(sum, item) => sum + item.price * item.quantity,
0
);
}
function notifyCustomer(customerId, total) {
console.log(`Order for ${customerId}: ₹${total}`);
}
function processOrder(order) {
validateOrder(order);
const total = calculateOrderTotal(order.items);
notifyCustomer(order.customerId, total);
}
Each function now has one clear job. We can test each part separately.
6.3 Avoid magic numbers
A magic number is a value whose meaning is not clear.
Before: Unexplained discount limit
if (order.total > 1000) {
console.log("Free delivery");
}
After: Give the value a meaningful name
const FREE_DELIVERY_MINIMUM = 1000;
if (order.total > FREE_DELIVERY_MINIMUM) {
console.log("Free delivery");
}
6.4 Use guard clauses
A guard clause checks invalid conditions early. It helps avoid deeply nested code.
Before: Nested conditions
function confirmOrder(order) {
if (order) {
if (order.items.length > 0) {
if (order.paymentConfirmed) {
return "Order confirmed";
}
}
}
return "Order cannot be confirmed";
}
After: Check invalid states first
function confirmOrder(order) {
if (!order) {
return "Order is missing";
}
if (order.items.length === 0) {
return "Order has no items";
}
if (!order.paymentConfirmed) {
return "Payment is pending";
}
return "Order confirmed";
}
6.5 Avoid duplicated logic
Repeated logic makes future changes risky. Move shared behaviour into a reusable function.
Example 6: Reuse one price formatter
function formatRupees(amount) {
return new Intl.NumberFormat("en-IN", {
style: "currency",
currency: "INR"
}).format(amount);
}
console.log(formatRupees(1500));
console.log(formatRupees(2750));
Expected output
₹1,500.00 ₹2,750.00
7. Clean Code Refactoring: From Change Request to Maintainable Code
Refactoring = improving code structure without changing its external behaviour.
When a new delivery rule arrives, we should not rewrite the whole checkout flow. We should identify the part that changes and keep the rest stable.
The refactoring flow separates mixed responsibilities while preserving the checkout behaviour.
8. How to Choose the Right Design Pattern
Do not apply every pattern to every problem. Start with the problem, then choose the smallest useful solution.
| Your problem | Possible pattern | Why it helps |
|---|---|---|
| Many interchangeable business rules | Strategy | Keeps each rule separate |
| Several parts need the same event | Observer | Reduces direct dependencies |
| Object creation is repeated | Factory | Centralises creation decisions |
| An API needs a simpler interface | Facade | Hides internal complexity |
| Extra behaviour is needed around an object | Decorator | Adds behaviour without changing the original object |
| Operations need to be represented as objects | Command | Supports queues, logs and undo workflows |
9. Common Mistakes and Best Practices
Mistake 1: Using patterns without a real problem
Extra classes and layers can make simple code harder. Start with the simplest clear solution.
Mistake 2: Creating one giant utility file
Unrelated functions become difficult to discover and test. Group code by business responsibility.
Mistake 3: Hiding errors
Empty catch blocks hide failures. Log useful context and handle errors at the correct boundary.
Better error handling
async function loadOrder(orderId) {
try {
const response = await fetch(
`/api/orders/${orderId}`
);
if (!response.ok) {
throw new Error("Could not load order");
}
return await response.json();
} catch (error) {
console.error("Order loading failed:", error);
throw error;
}
}
Mistake 4: Ignoring tests
Refactoring without tests can change business behaviour by accident. Test important rules before changing their structure.
Mistake 5: Making everything a class
JavaScript functions and plain objects are often enough. Use classes when they make state and behaviour easier to manage.
Best-practice checklist
- Use names that explain business meaning.
- Keep functions focused and reasonably small.
- Separate business rules from infrastructure code.
- Prefer composition when it keeps dependencies simple.
- Handle errors at clear boundaries.
- Write tests for important business rules.
- Document decisions that are not obvious from code.
- Choose patterns only when they reduce complexity.
10. How This Topic Comes Up in Interviews
Question 1: What is a design pattern?
What the interviewer wants: They want to know whether you understand reusable design approaches.
Strong answer: A design pattern is a proven approach to a common software design problem. For example, I can use Strategy when a grocery checkout supports different discount rules. Each rule stays separate, and checkout uses the selected one.
Question 2: Explain the Strategy and Observer patterns.
Strong answer: Strategy separates interchangeable business rules. Observer notifies registered listeners when something changes. In a grocery application, Strategy can calculate discounts. Observer can notify customers and delivery teams when an order status changes.
Question 3: What do you mean by clean code?
Strong answer: Clean code is easy to read, test and change. I use meaningful names and focused functions. I avoid duplicated logic and unexplained values. I also keep business rules separate from infrastructure concerns.
Question 4: Can design patterns make an application worse?
Strong answer: Yes. A pattern can add unnecessary layers when the problem is simple. I first understand the requirement and expected changes. Then I choose the simplest design that keeps the code maintainable.
Senior and architect-level follow-ups
- How would you test a Strategy implementation?
- How would you prevent memory leaks in an Observer implementation?
- When would you use a message broker instead of an in-memory Observer?
- How do you keep patterns consistent across multiple teams?
- How would you refactor a large legacy JavaScript module safely?
11. Hands-On Practice
Beginner: Add another discount strategy
Add a student discount to the grocery checkout example. Use a 7% discount rate.
Expected result: A ₹2,000 order should receive a ₹140 discount.
Intermediate: Add another Observer
Register an inventory listener. Print a message when the grocery order becomes packed.
Hint: Use the existing subscribe method. Do not change the publisher.
Advanced: Build a checkout module
Create a small checkout module using these requirements:
- Use a Factory to create UPI or card payment objects.
- Use Strategy to calculate customer discounts.
- Use Observer to publish order status changes.
- Use separate functions for validation and total calculation.
- Add tests for invalid payments and unsupported discounts.
Expected result: Checkout should support new rules without changing unrelated modules.
12. Final Thoughts
Good JavaScript is not about using the most patterns. It is about choosing a clear design for the problem. Strategy separates business rules. Observer separates event publishers from subscribers. Factory centralises object creation.
Combine these patterns with meaningful names, focused functions and automated tests. Your application becomes easier to understand and safer to change.
Explore Further
Share Your Knowledge: Try these patterns in a small project. Share your implementation and discuss other approaches with the Upgradix community.
Learn Technology. Build Your Future.
Upgradix by Shrash Studio — Quality Technology Education. Completely Free.