Mastering Code Quality: SOLID Principles, Architecture & Refactoring Techniques
This article explains how to instantly improve program design by mastering the five SOLID principles, understanding three common architectures, using diagrams, choosing clear names, and optimizing nested if‑else logic, all illustrated with Python code examples and visual diagrams.
Five Basic Object‑Oriented Principles
The five SOLID principles are:
Single Responsibility Principle
Open‑Closed Principle
Dependency Inversion Principle
Interface Segregation Principle
Composition over Inheritance Principle
Each principle is demonstrated with concrete Python examples that show how refactoring improves readability, maintainability, and adaptability to change.
Single‑Responsibility Principle in Action
A poorly written script that reads a file, extracts data, and makes a network request is shown, followed by a refactored version that splits the work into five tiny functions (get_source, extract_, fetch, trim, extract). This separation makes the code resilient to changes in the data source, network response, or processing logic.
import re
import requests
FILE = "./information.fet"
def get_source():
"""获取数据源"""
return
def extract_(val):
"""匹配关键数据"""
return
def fetch(val):
"""发出网络请求"""
return
def trim(val):
"""修剪数据"""
return
def extract(file):
"""提取目标数据"""
source = get_source()
content = extract_(source)
text = trim(fetch(content))
return text
if __name__ == "__main__":
text = extract(FILE)
print(text)The refactored version isolates responsibilities, so only the relevant function needs to change when requirements evolve.
Open‑Closed and Dependency‑Inversion Principles
Using an abstract Save base class and concrete MySQLSave and Excel implementations demonstrates how to keep high‑level modules closed for modification but open for extension. The Business class depends on the abstraction, allowing the storage backend to be swapped without changing business logic.
import abc
class Save(metaclass=abc.ABCMeta):
@abc.abstractmethod
def insert(self):
pass
@abc.abstractmethod
def update(self):
pass
class MySQLSave(Save):
def __init__(self):
self.classify = "mysql"
def insert(self):
pass
def update(self):
pass
class Excel(Save):
def __init__(self):
self.classify = "excel"
def insert(self):
pass
def update(self):
pass
class Business:
def __init__(self, saver):
self.saver = saver
def insert(self):
self.saver.insert()
def update(self):
self.saver.update()
if __name__ == "__main__":
mysql_saver = MySQLSave()
excel_saver = Excel()
business = Business(mysql_saver)Interface Segregation Principle
Instead of a single large interface, the example splits a Book abstraction into separate interfaces for buying, borrowing, shelving on, and shelving off, allowing clients to depend only on the methods they actually need.
import abc
class Book(metaclass=abc.ABCMeta):
@abc.abstractmethod
def buy(self):
pass
@abc.abstractmethod
def borrow(self):
pass
@abc.abstractmethod
def shelf_off(self):
pass
@abc.abstractmethod
def shelf_on(self):
passComposition Over Inheritance
Instead of deep inheritance hierarchies, the article shows how to compose objects (e.g., a Color class) inside concrete car classes, reducing coupling and making future extensions easier.
class Color:
pass
class KateCar:
color = Color()
def move(self):
pass
def engine(self):
pass
class FluentCar:
color = Color()
def move(self):
pass
def engine(self):
passThree Common Architectures
Understanding monolithic, distributed, and microservice architectures helps developers choose the right structure for a given problem.
Monolithic Architecture
All functionality lives in a single application, which is simple to deploy but suffers from high complexity, low deployment frequency, performance bottlenecks, limited innovation, and low reliability.
Distributed Architecture
Splits the system into multiple services to overcome monolithic bottlenecks, improving performance and reliability while still retaining many of the monolith’s drawbacks.
Microservice Architecture
Further decomposes functionality into independent services that communicate over the network, offering better scalability, independent deployment, and language‑agnostic implementation, but introduces operational overhead and network latency.
Importance of Diagrams
Visual diagrams (use‑case, collaboration, class, state) clarify requirements, module relationships, and interface contracts, making design discussions more effective.
Good Naming Practices
Choosing clear, descriptive identifiers improves code readability and maintainability; the article references a naming guide for deeper insight.
Optimizing Nested if‑else Statements
Guard clauses (early returns) simplify deeply nested conditionals, and the responsibility‑chain pattern replaces long if‑elif‑else ladders with a chain of handler objects.
class Manager:
def __init__(self):
self.obj = None
def next_handler(self, obj):
self.obj = obj
def handler(self, price):
pass
class General(Manager):
def handler(self, price):
if price < 300000:
print(f"{price} 普通销售")
else:
self.obj.handler(price)
class Elite(Manager):
def handler(self, price):
if 300000 <= price < 800000:
print(f"{price} 精英销售")
else:
self.obj.handler(price)
class BOSS(Manager):
def handler(self, price):
if price >= 800000:
print(f"{price} 店长")
# Build chain
general = General()
elite = Elite()
boss = BOSS()
general.next_handler(elite)
elite.next_handler(boss)
prices = [550000, 220000, 1500000, 200000, 330000]
for price in prices:
general.handler(price)This pattern decouples request senders from concrete handlers, making the logic extensible without modifying existing code.
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.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
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.
