在 JavaScript 和 TypeScript 框架中应用 SOLID 原则
介绍
SOLID 原则构成了简洁、可扩展且可维护的软件开发的基础。虽然这些原则起源于面向对象编程 (OOP),但它们可以有效地应用于 JavaScript (JS) 和 TypeScript (TS) 框架,例如 React 和 Angular。本文将通过 JS 和 TS 中的实际示例来解释每个原则。
1.单一职责原则(SRP)
原则:一个类或模块应该只有一个修改的理由。它应该只负责单一的功能。
- JavaScript(React)中的示例:
在 React 中,我们经常看到组件负责太多的事情——例如同时管理 UI 和业务逻辑。
反模式:
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
fetchUserData();
}, [userId]);
async function fetchUserData() {
const response = await fetch(`/api/users/${userId}`);
const data = await response.json();
setUser(data);
}
return <div>{user?.name}</div>;
}
这里,UserProfile组件违反了 SRP,因为它同时处理 UI 渲染和数据提取。
重构:
// Custom hook for fetching user data
function useUserData(userId) {
const [user, setUser] = useState(null);
useEffect(() => {
async function fetchUserData() {
const response = await fetch(`/api/users/${userId}`);
const data = await response.json();
setUser(data);
}
fetchUserData();
}, [userId]);
return user;
}
// UI Component
function UserProfile({ userId }) {
const user = useUserData(userId); // Moved data fetching logic to a hook
return <div>{user?.name}</div>;
}
通过使用自定义钩子 (useUserData),我们将数据获取逻辑与 UI 分开,使每个部分负责单个任务。
- TypeScript(Angular)中的示例:
在 Angular 中,服务和组件可能会因多项职责而变得混乱。
反模式:
@Injectable()
export class UserService {
constructor(private http: HttpClient) {}
getUser(userId: string) {
return this.http.get(`/api/users/${userId}`);
}
updateUserProfile(userId: string, data: any) {
// Updating the profile and handling notifications
return this.http.put(`/api/users/${userId}`, data).subscribe(() => {
console.log('User updated');
alert('Profile updated successfully');
});
}
}
此UserService具有多项职责:获取、更新和处理通知。
重构:
@Injectable()
export class UserService {
constructor(private http: HttpClient) {}
getUser(userId: string) {
return this.http.get(`/api/users/${userId}`);
}
updateUserProfile(userId: string, data: any) {
return this.http.put(`/api/users/${userId}`, data);
}
}
// Separate notification service
@Injectable()
export class NotificationService {
notify(message: string) {
alert(message);
}
}
通过将通知处理分成单独的服务(NotificationService),我们确保每个类都有单一的职责。
2.开放/封闭原则(OCP)
原则:软件实体应该对扩展开放,但对修改关闭。这意味着你应该能够在不修改模块源代码的情况下扩展其行为。
- JavaScript(React)中的示例:
您可能有一个运行良好的表单验证功能,但将来可能需要额外的验证逻辑。
反模式:
function validate(input) {
if (input.length < 5) {
return 'Input is too short';
}
if (!input.includes('@')) {
return 'Invalid email';
}
return 'Valid input';
}
每当您需要新的验证规则时,您都必须修改此功能,这违反了 OCP。
重构:
function validate(input, rules) {
return rules.map(rule => rule(input)).find(result => result !== 'Valid') || 'Valid input';
}
const lengthRule = input => input.length >= 5 ? 'Valid' : 'Input is too short';
const emailRule = input => input.includes('@') ? 'Valid' : 'Invalid email';
validate('test@domain.com', [lengthRule, emailRule]);
现在,我们可以扩展验证规则,而无需修改原始验证功能,并遵守 OCP。
- TypeScript(Angular)中的示例:
在 Angular 中,服务和组件应设计为允许添加新功能而无需修改核心逻辑。
反模式:
export class NotificationService {
send(type: 'email' | 'sms', message: string) {
if (type === 'email') {
// Send email
} else if (type === 'sms') {
// Send SMS
}
}
}
此服务违反了 OCP,因为每次添加新的通知类型(例如推送通知)时都需要修改发送方法。
重构:
interface Notification {
send(message: string): void;
}
@Injectable()
export class EmailNotification implements Notification {
send(message: string) {
// Send email logic
}
}
@Injectable()
export class SMSNotification implements Notification {
send(message: string) {
// Send SMS logic
}
}
@Injectable()
export class NotificationService {
constructor(private notifications: Notification[]) {}
notify(message: string) {
this.notifications.forEach(n => n.send(message));
}
}
现在,添加新的通知类型只需要创建新的类,而无需更改 NotificationService 本身。
3.里氏替换原则(LSP)
原则:子类型必须能够替换其基类型。派生类或组件应该能够替换基类,而不会影响程序的正确性。
- JavaScript(React)中的示例:
当使用高阶组件(HOC)或有条件地渲染不同的组件时,LSP 有助于确保所有组件的行为都可预测。
反模式:
function Button({ onClick }) {
return <button onClick={onClick}>Click me</button>;
}
function LinkButton({ href }) {
return <a href={href}>Click me</a>;
}
// Inconsistent use of onClick and href makes substitution difficult
<Button onClick={() => {}} />;
<LinkButton href="/home" />;
这里,和不能互换,因为它们使用不同的道具(onClick 与 href)。
重构:
function Actionable({ onClick, href, children }) {
if (href) {
return <a href={href}>{children}</a>;
} else {
return <button onClick={onClick}>{children}</button>;
}
}
function Button({ onClick }) {
return <Actionable onClick={onClick}>Click me</Actionable>;
}
function LinkButton({ href }) {
return <Actionable href={href}>Go Home</Actionable>;
}
现在,两个组件(Button 和 LinkButton)在语义上都是正确的,遵守 HTML 可访问性标准,并且在遵循 LSP 时行为一致。
- TypeScript(Angular)中的示例:
反模式:
class Rectangle {
constructor(protected width: number, protected height: number) {}
area() {
return this.width * this.height;
}
}
class Square extends Rectangle {
constructor(size: number) {
super(size, size);
}
setWidth(width: number) {
this.width = width;
this.height = width; // Breaks LSP
}
}
修改 Square 中的 setWidth 违反了 LSP,因为 Square 的行为与 Rectangle 不同。
重构:
class Shape {
area(): number {
throw new Error('Method not implemented');
}
}
class Rectangle extends Shape {
constructor(private width: number, private height: number) {
super();
}
area() {
return this.width * this.height;
}
}
class Square extends Shape {
constructor(private size: number) {
super();
}
area() {
return this.size * this.size;
}
}
现在,正方形和长方形可以相互替代,而不会违反 LSP。
4.接口隔离原则(ISP):
原则:客户端不应该被迫依赖他们不使用的接口。
- JavaScript(React)中的示例:
React 组件有时会接收不必要的 props,导致代码紧密耦合且臃肿。
反模式:
function MultiPurposeComponent({ user, posts, comments }) {
return (
<div>
<UserProfile user={user} />
<UserPosts posts={posts} />
<UserComments comments={comments} />
</div>
);
}
在这里,组件依赖于多个 props,即使它可能并不总是使用它们。
重构:
function UserProfileComponent({ user }) {
return <UserProfile user={user} />;
}
function UserPostsComponent({ posts }) {
return <UserPosts posts={posts} />;
}
function UserCommentsComponent({ comments }) {
return <UserComments comments={comments} />;
}
通过将组件拆分成更小的组件,每个组件仅依赖于它实际使用的数据。
- TypeScript(Angular)中的示例:
反模式:
interface Worker {
work(): void;
eat(): void;
}
class HumanWorker implements Worker {
work() {
console.log('Working');
}
eat() {
console.log('Eating');
}
}
class RobotWorker implements Worker {
work() {
console.log('Working');
}
eat() {
throw new Error('Robots do not eat'); // Violates ISP
}
}
这里,RobotWorker被迫实现了一个不相关的eat方法。
重构:
interface Worker {
work(): void;
}
interface Eater {
eat(): void;
}
class HumanWorker implements Worker, Eater {
work() {
console.log('Working');
}
eat() {
console.log('Eating');
}
}
class RobotWorker implements Worker {
work() {
console.log('Working');
}
}
通过分离 Worker 和 Eater 接口,我们确保客户端只依赖它们所需要的东西。
5.依赖倒置原则(DIP):
原则:高级模块不应该依赖于低级模块。两者都应该依赖于抽象(例如接口)。
- JavaScript(React)中的示例:
反模式:
function fetchUser(userId) {
return fetch(`/api/users/${userId}`).then(res => res.json());
}
function UserComponent({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
fetchUser(userId).then(setUser);
}, [userId]);
return <div>{user?.name}</div>;
}
这里,UserComponent 与 fetchUser 函数紧密耦合。
重构:
function UserComponent({ userId, fetchUserData }) {
const [user, setUser] = useState(null);
useEffect(() => {
fetchUserData(userId).then(setUser);
}, [userId, fetchUserData]);
return <div>{user?.name}</div>;
}
// Usage
<UserComponent userId={1} fetchUserData={fetchUser} />;
通过将 fetchUserData 注入组件,我们可以轻松地交换实现以进行测试或用于不同的用例。
- TypeScript(Angular)中的示例:
反模式:
@Injectable()
export class UserService {
constructor(private http: HttpClient) {}
getUser(userId: string) {
return this.http.get(`/api/users/${userId}`);
}
}
@Injectable()
export class UserComponent {
constructor(private userService: UserService) {}
loadUser(userId: string) {
this.userService.getUser(userId).subscribe(user => console.log(user));
}
}
UserComponent 与 UserService 紧密耦合,因此很难更换 UserService。
重构:
interface UserService {
getUser(userId: string): Observable<User>;
}
@Injectable()
export class ApiUserService implements UserService {
constructor(private http: HttpClient) {}
getUser(userId: string) {
return this.http.get<User>(`/api/users/${userId}`);
}
}
@Injectable()
export class UserComponent {
constructor(private userService: UserService) {}
loadUser(userId: string) {
this.userService.getUser(userId).subscribe(user => console.log(user));
}
}
通过依赖接口(UserService),UserComponent 现在与 ApiUserService 的具体实现解耦。
后续步骤
无论您使用 React 或 Angular 等框架在前端工作,还是使用 Node.js 在后端工作,SOLID 原则都可以作为指南,确保您的软件架构保持稳固。
要将这些原则完全融入到您的项目中:
- 定期练习:重构现有代码库以应用 SOLID 原则并检查代码是否遵守。
- 与您的团队合作:通过代码审查和围绕清洁架构的讨论来鼓励最佳实践。
- 保持好奇心: SOLID 原则仅仅是个开始。探索基于这些基础的其他架构模式,例如 MVC、MVVM 或 CQRS,以进一步完善您的设计。
结论
SOLID 原则能够有效确保您的代码简洁、可维护且可扩展,即使在 JavaScript 和 TypeScript 框架(例如 React 和 Angular)中也是如此。运用这些原则,开发人员能够编写灵活、可复用的代码,并且这些代码能够随着需求的变化而轻松扩展和重构。遵循 SOLID,您可以确保代码库稳健,并为未来的增长做好准备。
文章来源:https://dev.to/wafa_bergaoui/applying-solid-principles-in-javascript-and-typescript-framework-2d1d