Why Repeating Code Is Killing Your Projects: Master DRY, SOLID, and High‑Availability Design
This article explores essential software engineering practices—including the DRY principle, SOLID design principles, common design patterns, high‑availability architecture, automation, effective communication, and career development—offering concrete examples, code snippets, and actionable advice to help developers write cleaner, more maintainable, and scalable code.
01 DRY Principle
The DRY (Don’t Repeat Yourself) principle means avoiding duplicate code; however, not every repetition violates DRY, and some seemingly different code may still break the principle.
Typical duplicate cases are logical duplication, functional‑semantic duplication, and execution duplication.
1.1 Logical Duplication
Example:
class Calculator:
def add(self, a, b):
return a + b
def subtract(self, a, b):
return a - b
def multiply(self, a, b):
return a * b
def divide(self, a, b):
if b == 0:
# ...throw DivideByZeroException...
pass
return a / b
class AdvancedCalculator(Calculator):
def power(self, a, b):
result = 1
for i in range(b):
result *= a
return result
def square_root(self, a):
if a < 0:
# ...throw InvalidInputException...
pass
return math.sqrt(a)AdvancedCalculator inherits Calculator, but methods power and square_root repeat logic already present in multiply and divide. This redundancy makes the code longer, harder to maintain, and error‑prone.
1.2 Functional‑Semantic Duplication
Two functions that compute a square in different ways:
def square1(x):
return x ** 2
def square2(x):
return pow(x, 2)Both perform the same operation; they can be abstracted into a single square function:
def square(x):
return x ** 21.3 Execution Duplication
In a UserService.login method, both check_if_user_existed and get_user_by_email validate the email and password, causing unnecessary database I/O. Consolidating validation into login reduces duplicate execution and improves performance.
Refactored version:
class UserService:
def __init__(self, user_repo):
self.user_repo = user_repo
def login(self, email, password):
if not EmailValidation.validate(email):
# ...throw InvalidEmailException...
pass
if not PasswordValidation.validate(password):
# ...throw InvalidPasswordException...
pass
user = self.user_repo.get_user_by_email(email)
if user is None or password != user.password:
# ...throw AuthenticationFailureException...
pass
return user
class UserRepo:
def __init__(self, db):
self.db = db
def check_if_user_existed(self, email, password):
# ...query db to check if email&password exists...
pass
def get_user_by_email(self, email):
# ...query db to get user by email...
passAfter refactoring, the code is clearer and responsibilities are better separated.
1.2 SOLID Principles
1.2.1 Single Responsibility Principle (SRP)
A class should have only one responsibility. By abstracting responsibilities into separate classes or methods, code becomes easier to organize and maintain.
1.2.2 Open‑Closed Principle (OCP)
Software entities should be open for extension but closed for modification. Using abstract classes or interfaces enables adding new functionality without changing existing code.
1.2.3 Liskov Substitution Principle (LSP)
Subclasses must be replaceable for their base classes without affecting program correctness. Example with Rectangle and Square demonstrates proper substitution.
1.2.4 Interface Segregation Principle (ISP)
Clients should not be forced to depend on methods they do not use. Interfaces should be small and specific.
1.2.5 Dependency Inversion Principle (DIP)
High‑level modules should depend on abstractions, not on low‑level implementations. This reduces coupling and improves extensibility.
1.3 Design Patterns
A summary of 23 common design patterns across creational, structural, and behavioral categories, such as Singleton, Factory Method, Abstract Factory, Builder, Prototype, Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy, Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, and Visitor.
2 High‑Availability Design
2.1 System Architecture
Design for high availability using load balancing, clustering, distributed systems, and multi‑region deployment (e.g., Tencent Cloud CLB, Kubernetes, distributed databases).
2.2 Logging and Monitoring
Implement comprehensive monitoring (performance, health, network, logs) with goals of readability, reliability, scalability, and real‑time alerts.
2.3 Disaster Recovery
Adopt distributed architecture, multi‑data‑center redundancy, regular backups, disaster‑recovery plans, monitoring, and capacity planning to ensure resilience.
2.4 System Stability for Backend Developers
Stability is a backend developer’s lifeline; prioritize design, testing, deployment, and operations to maintain reliable services.
3 Productivity and Automation
3.1 Optimize Repetitive Processes
Identify and automate recurring tasks (e.g., data export, report generation) to reduce manual effort and errors.
3.2 Use Templates and Standardized Workflows
Standardize documents and reports with templates and scripts to streamline production.
3.3 Apply Project Management Tools
Leverage tools for task tracking, progress visualization, and workflow optimization.
4 Value‑Driven Focus
Prioritize work that delivers user and business value; question whether a task is truly essential before investing effort.
5 Communication and Collaboration
Effective communication with product managers, teammates, and stakeholders is crucial for understanding requirements, coordinating work, and solving problems efficiently.
6 Accountability
Maintain clear ownership, follow‑up, and feedback loops to ensure tasks are completed reliably.
7 Continuous Learning
Stay open to new technologies and tools; continuous learning improves efficiency, quality, and career growth.
8 Career Development
Assess job satisfaction, growth opportunities, and compensation; consider lateral moves to broaden skills, enhance competitiveness, and open future career paths.
Author: Wu Lianhuo Source: Tencent Cloud Community
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
21CTO
21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
