Mastering Clean Code: SOLID Principles, Architecture Patterns, and Naming Strategies
This article distills essential software design knowledge—covering the five SOLID principles, three common architecture styles, effective diagramming, naming conventions, and techniques for simplifying nested if‑else logic—providing concrete Python examples and visual aids to help developers write more maintainable and robust code.
Why Good Code Matters
Many readers have studied Python Programming Reference and understand coding standards, yet they still struggle to produce clean, maintainable code. The author shares personal experiences and resources that helped improve program design, including Clean Code and a paid column on software design.
Key Knowledge Points
Five basic SOLID principles
Three common architecture styles
Effective diagramming
Choosing good names
Optimizing nested if‑else statements
SOLID Principles
Single Responsibility Principle (SRP)
SRP advocates that a function should do only one thing. The article shows a flawed example that reads a file, extracts data, and makes a network request in a single function, then refactors it into four small functions, each handling a single responsibility.
import re
import requests
FILE = "./information.fet"
def extract(file):
fil = open(file, "r")
content = fil.read()
fil.close()
find_object = re.search(r"url=\d+", content)
find = find_object.group(1)
text = requests.get(find)
return text
if __name__ == "__main__":
text = extract(FILE)
print(text)Refactored version:
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 refactor isolates each step, making the code easier to modify when requirements change.
Open/Closed Principle (OCP) and Dependency Inversion Principle (DIP)
OCP encourages software to be open for extension but closed for modification. The article demonstrates a naïve storage implementation that requires changes to both the storage class and the business logic when switching from MySQL to Excel.
class MySQLSave:
def __init__(self):
pass
def insert(self):
pass
def update(self):
pass
class Business:
def __init__(self):
pass
def save(self):
saver = MySQLSave()
saver.insert()Using an abstract base class and dependency injection solves the problem:
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)This decouples business logic from concrete storage implementations, satisfying both OCP and DIP.
Interface Segregation Principle (ISP)
ISP advises that clients should not be forced to depend on interfaces they do not use. The article illustrates a monolithic Book abstract class with methods for buying, borrowing, shelving on/off, and suggests splitting it into separate interfaces for management and user operations.
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):
passComposite Reuse Principle (CRP)
CRP recommends composition over inheritance to reduce tight coupling. The article compares inheritance‑based Car subclasses with a composition approach that injects a Color object.
class Car:
def move(self):
pass
def engine(self):
pass
class KateCar(Car):
def move(self):
pass
def engine(self):
pass
class FluentCar(Car):
def move(self):
pass
def engine(self):
pass
# Composition version
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):
passCommon Architecture Styles
Monolithic Architecture
All functionality resides in a single application. It is simple to deploy but suffers from high complexity, low deployment frequency, performance bottlenecks, limited innovation, and low reliability.
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.
Huawei Cloud Developer Alliance
The Huawei Cloud Developer Alliance creates a tech sharing platform for developers and partners, gathering Huawei Cloud product knowledge, event updates, expert talks, and more. Together we continuously innovate to build the cloud foundation of an intelligent world.
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.
